summaryrefslogtreecommitdiff
path: root/jstests/sharding/internal_txns/libs/resharding_test.js
blob: ce4d96b98580e7d4162f884ff83710376a7239e8 (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
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
/*
 * Utilities for performing a set of retryable or non-retryable internal transactions during or
 * before a resharding operation, and verifying that the transaction history is correctly
 * transferred or not transferred to the recipient shard.
 *
 * Example usage:
 *      const transactionTest = new InternalTransactionReshardingTest();
 *      transactionTest.runTest*(...);
 *      transactionTest.stop();
 *
 * Note that this fixture does not support resetting the collection after each runTest() call so it
 * is illegal to do more than one runTest() call.
 */
'use strict';

load("jstests/libs/discover_topology.js");
load('jstests/sharding/internal_txns/libs/fixture_helpers.js');
load("jstests/sharding/libs/resharding_test_fixture.js");
load('jstests/sharding/libs/sharded_transactions_helpers.js');

function InternalTransactionReshardingTest(
    {reshardInPlace, storeFindAndModifyImagesInSideCollection}) {
    jsTest.log(`Running resharding test with options ${
        tojson({reshardInPlace, storeFindAndModifyImagesInSideCollection})}`);

    const reshardingTest = new ReshardingTest({
        numDonors: 2,
        numRecipients: 1,
        reshardInPlace,
        storeFindAndModifyImagesInSideCollection,
        oplogSize: 256
    });
    reshardingTest.setup();

    const donorShardNames = reshardingTest.donorShardNames;
    const recipientShardNames = reshardingTest.recipientShardNames;
    const reshardingOptions = {
        primaryShardName: donorShardNames[0],
        oldShardKeyPattern: {oldShardKey: 1},
        oldShardKeyChunks: [
            {min: {oldShardKey: MinKey}, max: {oldShardKey: 0}, shard: donorShardNames[0]},
            {min: {oldShardKey: 0}, max: {oldShardKey: MaxKey}, shard: donorShardNames[1]}
        ],
        newShardKeyPattern: {newShardKey: 1},
        newShardKeyChunks: [
            {min: {newShardKey: MinKey}, max: {newShardKey: MaxKey}, shard: recipientShardNames[0]}
        ],
    };

    const kSize10MB = 10 * 1024 * 1024;
    const kInternalTxnType = {kRetryable: 1, kNonRetryable: 2};
    const kImageType = {kPreImage: 1, kPostImage: 2};

    const kDbName = "testDb";
    const kCollName = "testColl";
    const kNs = kDbName + "." + kCollName;

    const mongosTestColl = reshardingTest.createShardedCollection({
        ns: kNs,
        shardKeyPattern: reshardingOptions.oldShardKeyPattern,
        chunks: reshardingOptions.oldShardKeyChunks,
        primaryShardName: reshardingOptions.primaryShardName,
    });
    const mongosConn = mongosTestColl.getMongo();

    let lastTestId = 0;

    function makeSessionOptionsForTest(testId) {
        const sessionUUID = UUID();
        const parentLsid = {id: sessionUUID};
        const parentTxnNumber = testId;
        const childLsidForRetryableWrite = {
            id: sessionUUID,
            txnNumber: NumberLong(parentTxnNumber),
            txnUUID: UUID()
        };
        const childTxnNumberForRetryableWrite = 0;
        const childLsidForNonRetryableWrite = {id: sessionUUID, txnUUID: UUID()};
        const childTxnNumberForNonRetryableWrite = 0;

        return {
            sessionUUID,
            parentLsid,
            parentTxnNumber,
            childLsidForRetryableWrite,
            childTxnNumberForRetryableWrite,
            childLsidForNonRetryableWrite,
            childTxnNumberForNonRetryableWrite
        };
    }

    // Helpers for defining transaction test cases.

    function makeTransactionOptionsForInsertUpdateDeleteTest(
        {isPreparedTxn, isLargeTxn, abortOnInitialTry}) {
        const testId = ++lastTestId;

        const testCase = makeSessionOptionsForTest(testId);
        testCase.id = testId;
        testCase.isPreparedTxn = isPreparedTxn;
        testCase.isLargeTxn = isLargeTxn;
        testCase.abortOnInitialTry = abortOnInitialTry;
        testCase.lastUsedStmtId = -1;

        testCase.commands = [];

        // Define the retryable insert, update and delete statements to be run in the test internal
        // transaction. Prior to resharding, these write statements will be routed to donor0.
        const docToInsert = {insertOp: -testId, oldShardKey: -testId, newShardKey: -testId};
        testCase.commands.push({
            cmdObj: {
                insert: kCollName,
                documents: [docToInsert],
                stmtId: NumberInt(++testCase.lastUsedStmtId)
            },
            checkResponseFunc: (res) => {
                assert.eq(res.n, 1);
            }
        });

        const docToUpdate = {updateOp: -testId, oldShardKey: -testId, newShardKey: -testId};
        testCase.commands.push({
            cmdObj: {
                update: kCollName,
                updates: [{q: docToUpdate, u: {$mul: {updateOp: 100}}}],
                stmtId: NumberInt(++testCase.lastUsedStmtId)
            },
            checkResponseFunc: (res) => {
                assert.eq(res.n, 1);
                assert.eq(res.nModified, 1);
            }
        });
        const updatedDoc = {updateOp: -testId * 100, oldShardKey: -testId, newShardKey: -testId};

        const docToDelete = {deleteOp: -testId, oldShardKey: -testId, newShardKey: -testId};
        testCase.commands.push({
            cmdObj: {
                delete: kCollName,
                deletes: [{q: docToDelete, limit: 1}],
                stmtId: NumberInt(++testCase.lastUsedStmtId)
            },
            checkResponseFunc: (res) => {
                assert.eq(res.n, 1);
            }
        });

        // If testing a prepared and/or large transaction, define additional insert statements to
        // make the transaction a prepared and/or large transaction.
        const additionalDocsToInsert =
            makeInsertCommandsIfTestingPreparedOrLargeTransaction(testId, testCase);

        testCase.setUpFunc = () => {
            const coll = mongosConn.getCollection(kNs);
            assert.commandWorked(coll.insert(docToUpdate));
            assert.commandWorked(coll.insert(docToDelete));
        };

        testCase.checkDocsFunc = (isTxnCommitted) => {
            const coll = mongosConn.getCollection(kNs);
            const docs = coll.find().toArray();

            assert.eq(coll.find(docToInsert).itcount(), isTxnCommitted ? 1 : 0, tojson(docs));
            assert.eq(coll.find(docToUpdate).itcount(), isTxnCommitted ? 0 : 1, tojson(docs));
            assert.eq(coll.find(updatedDoc).itcount(), isTxnCommitted ? 1 : 0, tojson(docs));
            assert.eq(coll.find(docToDelete).itcount(), isTxnCommitted ? 0 : 1, tojson(docs));

            additionalDocsToInsert.forEach(docToInsert => {
                assert.eq(coll.find(docToInsert).itcount(), isTxnCommitted ? 1 : 0, tojson(docs));
            });
        };

        return testCase;
    }

    function makeTransactionOptionsForFindAndModifyTest(
        {imageType, isPreparedTxn, isLargeTxn, abortOnInitialTry}) {
        const testId = ++lastTestId;

        const testCase = makeSessionOptionsForTest(testId);
        testCase.id = testId;
        testCase.isPreparedTxn = isPreparedTxn;
        testCase.isLargeTxn = isLargeTxn;
        testCase.abortOnInitialTry = abortOnInitialTry;
        testCase.imageType = imageType;
        testCase.lastUsedStmtId = -1;

        testCase.commands = [];

        // Define the retryable findAndModify statement to be run in the test internal transaction.
        // Prior to resharding, the write statement will be routed to donor0.
        const docToUpdate = {findAndModifyOp: -testId, oldShardKey: -testId, newShardKey: -testId};
        const findAndModifyCmdObj = {
            findAndModify: kCollName,
            query: docToUpdate,
            update: {$mul: {findAndModifyOp: 100}},
            stmtId: NumberInt(++testCase.lastUsedStmtId)
        };
        if (imageType == kImageType.kPostImage) {
            findAndModifyCmdObj.new = true;
        }
        testCase.commands.push({
            cmdObj: findAndModifyCmdObj,
            checkResponseFunc: (res) => {
                assert.eq(res.lastErrorObject.n, 1);
                if (imageType == kImageType.kNone) {
                    assert.eq(res.lastErrorObject.updatedExisting, false);
                } else {
                    assert.eq(res.lastErrorObject.updatedExisting, true);
                    delete res.value._id;
                    assert.eq(res.value,
                              imageType == kImageType.kPreImage ? docToUpdate : updatedDoc);
                }
            }
        });
        const updatedDoc = {
            findAndModifyOp: -testId * 100,
            oldShardKey: -testId,
            newShardKey: -testId
        };

        // If testing a prepared and/or large transaction, define additional insert statements to
        // make the transaction a prepared and/or large transaction.
        const docsToInsert =
            makeInsertCommandsIfTestingPreparedOrLargeTransaction(testId, testCase);

        testCase.setUpFunc = () => {
            const coll = mongosConn.getCollection(kNs);
            assert.commandWorked(coll.insert(docToUpdate));
        };

        testCase.checkDocsFunc = (isTxnCommitted) => {
            const coll = mongosConn.getCollection(kNs);
            const docs = coll.find().toArray();

            assert.eq(coll.find(docToUpdate).itcount(), isTxnCommitted ? 0 : 1, tojson(docs));
            assert.eq(coll.find(updatedDoc).itcount(), isTxnCommitted ? 1 : 0, tojson(docs));

            docsToInsert.forEach(docToInsert => {
                assert.eq(coll.find(docToInsert).itcount(), isTxnCommitted ? 1 : 0, tojson(docs));
            });
        };

        return testCase;
    }

    function makeInsertCommandsIfTestingPreparedOrLargeTransaction(testId, testCase) {
        const additionalDocsToInsert = [];
        if (testCase.isLargeTxn) {
            // Prior to resharding, the insert statements below will be routed to donor0.
            const numLargeDocs = 2;
            for (let i = 0; i < numLargeDocs; i++) {
                const docToInsert = {
                    insert10MB: i.toString() + new Array(kSize10MB).join("x"),
                    oldShardKey: -testId,
                    newShardKey: -testId
                };
                testCase.commands.push({
                    // Use stmtId -1 to get test coverage for "applyOps" entries without a stmtId.
                    cmdObj: {insert: kCollName, documents: [docToInsert], stmtId: NumberInt(-1)},
                    checkResponseFunc: (res) => {
                        assert.eq(res.n, 1);
                    }
                });
                additionalDocsToInsert.push(docToInsert);
            }
        }
        if (testCase.isPreparedTxn) {
            // Prior to resharding, this insert statement below will be routed to donor1.
            const docToInsert = {insertOp: testId, oldShardKey: testId, newShardKey: testId};
            testCase.commands.push({
                cmdObj: {
                    insert: kCollName,
                    documents: [docToInsert],
                    stmtId: NumberInt(++testCase.lastUsedStmtId)
                },
                checkResponseFunc: (res) => {
                    assert.eq(res.n, 1);
                }
            });
            additionalDocsToInsert.push(docToInsert);
        }
        return additionalDocsToInsert;
    }

    function commitTransaction(lsid, txnNumber) {
        assert.commandWorked(mongosConn.adminCommand(makeCommitTransactionCmdObj(lsid, txnNumber)));
    }

    function abortTransaction(lsid, txnNumber, isPreparedTxn) {
        if (isPreparedTxn) {
            const topology = DiscoverTopology.findConnectedNodes(mongosConn);
            const donor0Conn =
                new Mongo(topology.shards[reshardingTest.donorShardNames[0]].primary);
            assert.commandWorked(
                donor0Conn.adminCommand(makePrepareTransactionCmdObj(lsid, txnNumber)));
        }
        assert.commandWorked(mongosConn.adminCommand(makeAbortTransactionCmdObj(lsid, txnNumber)));
    }

    function getTransactionSessionId(txnType, testCase) {
        return Object.assign({},
                             txnType == kInternalTxnType.kRetryable
                                 ? testCase.childLsidForRetryableWrite
                                 : testCase.childLsidForNonRetryableWrite);
    }

    function getNextTxnNumber(txnType, testCase) {
        return NumberLong(txnType == kInternalTxnType.kRetryable
                              ? ++testCase.childTxnNumberForRetryableWrite
                              : ++testCase.childTxnNumberForNonRetryableWrite);
    }

    /*
     * Runs the commands defined inside 'testCase' in an internal transaction of the specified
     * type.
     */
    function runInternalTransactionOnInitialTry(txnType, testCase) {
        jsTest.log(`Running write statements in an internal transaction with options ${tojson({
            id: testCase.id,
            isPreparedTxn: testCase.isPreparedTxn,
            isLargeTxn: testCase.isLargeTxn,
            abortOnInitialTry: testCase.abortOnInitialTry,
            imageType: testCase.imageType
        })}`);
        testCase.setUpFunc();

        const lsid = getTransactionSessionId(txnType, testCase);
        runTxnRetryOnTransientError(() => {
            const txnNumber = getNextTxnNumber(txnType, testCase);

            for (let i = 0; i < testCase.commands.length; i++) {
                const command = testCase.commands[i];
                const cmdObj =
                    Object.assign({}, command.cmdObj, {lsid, txnNumber, autocommit: false});
                if (i == 0) {
                    cmdObj.startTransaction = true;
                }
                const res = assert.commandWorked(mongosConn.getDB(kDbName).runCommand(cmdObj));
                command.checkResponseFunc(res);
            }
            if (testCase.abortOnInitialTry) {
                abortTransaction(lsid, txnNumber, testCase.isPreparedTxn);
            } else {
                commitTransaction(lsid, txnNumber);
            }
        });

        testCase.checkDocsFunc(!testCase.abortOnInitialTry /* isTxnCommitted */);
    }

    /*
     * Retries the commands defined inside 'testCase' in an internal transaction of the specified
     * type. If this retry is expected to fail, asserts that the command to start the transaction
     * fails with an IncompleteTransactionHistory error.
     */
    function runInternalTransactionOnRetry(
        txnType, testCase, isRetryAfterAbort, expectRetryToSucceed) {
        jsTest.log(
            `Retrying write statements executed in an internal transaction with options ${tojson({
                id: testCase.id,
                isPreparedTxn: testCase.isPreparedTxn,
                isLargeTxn: testCase.isLargeTxn,
                abortOnInitialTry: testCase.abortOnInitialTry,
                imageType: testCase.imageType,
                isRetryAfterAbort: isRetryAfterAbort,
                expectRetryToSucceed: expectRetryToSucceed
            })} in another internal transaction`);

        const lsid = getTransactionSessionId(txnType, testCase);
        // Give the session a different txnUUID to simulate a retry from a different mongos.
        lsid.txnUUID = UUID();
        runTxnRetryOnTransientError(() => {
            const txnNumber = getNextTxnNumber(txnType, testCase);

            for (let i = 0; i < testCase.commands.length; i++) {
                const command = testCase.commands[i];

                if (!isRetryAfterAbort && command.cmdObj.stmtId == -1) {
                    // The transaction has already committed and the statement in this command
                    // is not retryable so do not retry it.
                    continue;
                }

                const cmdObj =
                    Object.assign({}, command.cmdObj, {lsid, txnNumber, autocommit: false});
                if (i == 0) {
                    cmdObj.startTransaction = true;
                }
                const res = mongosConn.getDB(kDbName).runCommand(cmdObj);

                if (expectRetryToSucceed) {
                    assert.commandWorked(res);
                    command.checkResponseFunc(res);
                } else {
                    assert.commandFailedWithCode(res, ErrorCodes.IncompleteTransactionHistory);
                    return;
                }
            }
            commitTransaction(lsid, txnNumber);
            testCase.checkDocsFunc(true /* isTxnCommitted */);
        });
    }

    /*
     * Retries the commands specified inside 'testCase' as retryable writes. If this retry is
     * expected to fail, asserts that all commands fail with an IncompleteTransactionHistory error.
     */
    function runRetryableWriteOnRetry(testCase, expectRetryToSucceed) {
        jsTest.log(
            `Retrying write statements executed in an internal transaction with options ${tojson({
                id: testCase.id,
                isPreparedTxn: testCase.isPreparedTxn,
                isLargeTxn: testCase.isLargeTxn,
                abortOnInitialTry: testCase.abortOnInitialTry,
                imageType: testCase.imageType,
                expectRetryToSucceed: expectRetryToSucceed
            })} in a retryable write`);

        const lsid = testCase.parentLsid;
        const txnNumber = NumberLong(testCase.parentTxnNumber);

        for (let i = 0; i < testCase.commands.length; i++) {
            const command = testCase.commands[i];

            if (command.cmdObj.stmtId == -1) {
                // The statement in this command is not retryable so do not retry it.
                continue;
            }

            const cmdObj = Object.assign({}, command.cmdObj, {lsid, txnNumber});
            const res = mongosConn.getDB(kDbName).runCommand(cmdObj);

            if (expectRetryToSucceed) {
                assert.commandWorked(res);
                command.checkResponseFunc(res);
            } else {
                assert.commandFailedWithCode(res, ErrorCodes.IncompleteTransactionHistory);
            }
        }

        testCase.checkDocsFunc(!testCase.abortOnInitialTry ||
                               expectRetryToSucceed /* isTxnCommitted */);
    }

    /*
     * Runs the commands defined in each 'testCase' inside an internal transaction of the specified
     * type while resharding is running in the background.
     * - If the type is non-retryable, verifies that none of the transactions has a
     *   config.transactions entry on the recipient if the recipient is not also a donor.
     * - If the type is retryable, verifies that the retryable write statements in each transaction
     *   are retryable on the recipient after resharding completes regardless of whether the
     *   transaction committed or aborted on the donor(s).
     */
    function testTransactionsDuringResharding(txnType, testCases) {
        reshardingTest.withReshardingInBackground(
            {
                newShardKeyPattern: reshardingOptions.newShardKeyPattern,
                newChunks: reshardingOptions.newShardKeyChunks,
            },
            () => {
                // The cloneTimestamp is the boundary for whether a retryable write statement will
                // be retryable after the resharding operation completes.
                assert.soon(() => {
                    const coordinatorDoc =
                        mongosConn.getCollection("config.reshardingOperations").findOne({ns: kNs});

                    return coordinatorDoc !== null && coordinatorDoc.cloneTimestamp !== undefined;
                });

                jsTest.log("Start running retryable internal transactions during resharding");
                for (let testCase of testCases) {
                    runInternalTransactionOnInitialTry(txnType, testCase);
                }
                jsTest.log("Finished running retryable internal transactions during resharding");
            });

        const recipientRst = reshardingTest.getReplSetForShard(recipientShardNames[0]);

        if (txnType == kInternalTxnType.kNonRetryable) {
            if (!reshardInPlace) {
                for (let testCase of testCases) {
                    const configTxnEntries = getTxnEntriesForSession(
                        recipientRst, testCase.childLsidForNonRetryableWrite);
                    assert.eq(configTxnEntries.length, 0, tojson(configTxnEntries));
                }
            }
            return;
        }

        // Refresh the mongos so that write statements are routed to the recipient on retries.
        assert.commandWorked(mongosConn.adminCommand({flushRouterConfig: 1}));
        const expectRetryToSucceed = true;

        jsTest.log("Start retrying retryable internal transactions after resharding");
        for (let testCase of testCases) {
            runInternalTransactionOnRetry(txnType,
                                          testCase,
                                          testCase.abortOnInitialTry /* isRetryAfterAbort */,
                                          expectRetryToSucceed);
            // Also retry the write statements as retryable writes.
            runRetryableWriteOnRetry(testCase, expectRetryToSucceed);
        }
        jsTest.log("Finished retrying retryable internal transactions after resharding");

        recipientRst.stopSet(null /* signal */, true /*forRestart */);
        recipientRst.startSet({restart: true});
        recipientRst.getPrimary();

        jsTest.log("Start retrying retryable internal transactions after restarting the recipient");
        for (let testCase of testCases) {
            runInternalTransactionOnRetry(
                txnType, testCase, false /* isRetryAfterAbort */, expectRetryToSucceed);
            // Also retry the write statements as retryable writes.
            runRetryableWriteOnRetry(testCase, expectRetryToSucceed);
        }
        jsTest.log("Finished retrying retryable internal transactions after restart the recipient");
    }

    /*
     * Runs the commands specified in each 'testCase' inside an internal transaction of the
     * specified and then runs resharding to completion.
     * - If the type is non-retryable, verifies that none of the transactions has a
     *   config.transactions entry on the recipient if the recipient is not also a donor.
     * - If the type is retryable, verifies that none of the retryable write statements in each
     *   transaction is retryable on the recipient unless the transaction aborts without prepare
     *   on the donor.
     */
    function testTransactionsBeforeResharding(txnType, testCases) {
        jsTest.log("Start running retryable internal transactions before resharding");
        for (let testCase of testCases) {
            runInternalTransactionOnInitialTry(txnType, testCase);
        }
        jsTest.log("Finished running retryable internal transactions before resharding");

        reshardingTest.withReshardingInBackground({
            newShardKeyPattern: reshardingOptions.newShardKeyPattern,
            newChunks: reshardingOptions.newShardKeyChunks,
        });

        const recipientRst = reshardingTest.getReplSetForShard(recipientShardNames[0]);

        if (txnType == kInternalTxnType.kNonRetryable) {
            if (!reshardInPlace) {
                for (let testCase of testCases) {
                    const configTxnEntries = getTxnEntriesForSession(
                        recipientRst, testCase.childLsidForNonRetryableWrite);
                    assert.eq(configTxnEntries.length, 0, tojson(configTxnEntries));
                }
            }
            return;
        }

        // Refresh the mongos so that write statements are routed to the recipient on retries.
        assert.commandWorked(mongosConn.adminCommand({flushRouterConfig: 1}));
        // To make retryable writes and transactions that existed prior to resharding not retryable
        // after resharding, each recipient performs a snapshot read of the the config.transactions
        // collection and then writes a dead-end noop oplog entry for every retryable write and
        // transaction that it finds. Therefore, a transaction that does not have a
        // config.transactions entry (i.e. an aborted unprepared transaction) is expected to be
        // retryable after resharding.
        let expectRetryForTestCaseToSucceed = (testCase) =>
            !testCase.isPreparedTxn && testCase.abortOnInitialTry;

        jsTest.log("Start retrying retryable internal transactions after resharding");
        for (let testCase of testCases) {
            const expectRetryToSucceed = expectRetryForTestCaseToSucceed(testCase);
            runInternalTransactionOnRetry(txnType,
                                          testCase,
                                          testCase.abortOnInitialTry /* isRetryAfterAbort */,
                                          expectRetryToSucceed);
            // Also retry the write statements as retryable writes.
            runRetryableWriteOnRetry(testCase, expectRetryToSucceed);
        }
        jsTest.log("Finished retrying retryable internal transactions after resharding");

        recipientRst.stopSet(null /* signal */, true /*forRestart */);
        recipientRst.startSet({restart: true});
        recipientRst.getPrimary();

        jsTest.log("Start retrying retryable internal transactions after restarting the recipient");
        for (let testCase of testCases) {
            const expectRetryToSucceed = expectRetryForTestCaseToSucceed(testCase);
            runInternalTransactionOnRetry(
                txnType, testCase, false /* isRetryAfterAbort */, expectRetryToSucceed);
            // Also retry the write statements as retryable writes.
            runRetryableWriteOnRetry(testCase, expectRetryToSucceed);
        }
        jsTest.log(
            "Finished retrying retryable internal transactions after restarting the recipient");
    }

    this.InternalTxnType = kInternalTxnType;

    // Helpers for testing retryable internal transactions with resharding. Each helper defines
    // transaction test cases using the makeTransactionOptions*() helpers above and runs one
    // of the testTransactions*Resharding() helpers above.

    this.runTestForInsertUpdateDeleteDuringResharding = function(txnType, abortOnInitialTry) {
        const testCases = [];
        for (let isPreparedTxn of [true, false]) {
            for (let isLargeTxn of [true, false]) {
                testCases.push(makeTransactionOptionsForInsertUpdateDeleteTest(
                    {isPreparedTxn, isLargeTxn, abortOnInitialTry}));
            }
        }
        testTransactionsDuringResharding(txnType, testCases);
    };

    this.runTestForInsertUpdateDeleteBeforeResharding = function(txnType, abortOnInitialTry) {
        const testCases = [];
        for (let isPreparedTxn of [true, false]) {
            for (let isLargeTxn of [true, false]) {
                testCases.push(makeTransactionOptionsForInsertUpdateDeleteTest(
                    {isPreparedTxn, isLargeTxn, abortOnInitialTry}));
            }
        }
        testTransactionsBeforeResharding(txnType, testCases);
    };

    this.runTestForFindAndModifyDuringResharding = function(txnType, abortOnInitialTry) {
        const testCases = [];
        for (let imageTypeName in kImageType) {
            const imageType = kImageType[imageTypeName];
            for (let isPreparedTxn of [true, false]) {
                for (let isLargeTxn of [true, false]) {
                    testCases.push(makeTransactionOptionsForFindAndModifyTest(
                        {isPreparedTxn, isLargeTxn, abortOnInitialTry, imageType}));
                }
            }
        }
        testTransactionsDuringResharding(txnType, testCases);
    };

    this.stop = function() {
        reshardingTest.teardown();
    };
}