summaryrefslogtreecommitdiff
path: root/jstests/sharding/transactions_view_resolution.js
blob: 1a8224ee08902ccabfbeb0e6c7971795f07f4ed4 (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
// Tests mongos behavior when reading against views in a transaction.
//
// @tags: [
//   requires_find_command,
//   requires_sharding,
//   uses_multi_shard_transaction,
//   uses_transactions,
// ]
(function() {
"use strict";

load("jstests/aggregation/extras/utils.js");  // For arrayEq.
load("jstests/sharding/libs/sharded_transactions_helpers.js");

const shardedDbName = "shardedDB";
const shardedCollName = "sharded";
const shardedViewName = "sharded_view";

const unshardedDbName = "unshardedDB";
const unshardedCollName = "unsharded";
const unshardedViewName = "unsharded_view";

const viewOnShardedViewName = "sharded_view_view";

function setUpUnshardedCollectionAndView(st, session, primaryShard) {
    assert.writeOK(st.s.getDB(unshardedDbName)[unshardedCollName].insert(
        {_id: 1, x: "unsharded"}, {writeConcern: {w: "majority"}}));
    st.ensurePrimaryShard(unshardedDbName, primaryShard);

    const unshardedView = session.getDatabase(unshardedDbName)[unshardedViewName];
    assert.commandWorked(unshardedView.runCommand(
        "create", {viewOn: unshardedCollName, pipeline: [], writeConcern: {w: "majority"}}));

    return unshardedView;
}

function setUpShardedCollectionAndView(st, session, primaryShard) {
    const ns = shardedDbName + "." + shardedCollName;

    assert.writeOK(st.s.getDB(shardedDbName)[shardedCollName].insert(
        {_id: -1}, {writeConcern: {w: "majority"}}));
    assert.writeOK(st.s.getDB(shardedDbName)[shardedCollName].insert(
        {_id: 1}, {writeConcern: {w: "majority"}}));
    assert.commandWorked(st.s.adminCommand({enableSharding: shardedDbName}));
    st.ensurePrimaryShard(shardedDbName, primaryShard);

    assert.commandWorked(st.s.adminCommand({shardCollection: ns, key: {_id: 1}}));
    assert.commandWorked(st.s.adminCommand({split: ns, middle: {_id: 0}}));
    assert.commandWorked(
        st.s.adminCommand({moveChunk: ns, find: {_id: 1}, to: st.shard1.shardName}));

    const shardedView = session.getDatabase(shardedDbName)[shardedViewName];
    assert.commandWorked(shardedView.runCommand(
        "create", {viewOn: shardedCollName, pipeline: [], writeConcern: {w: "majority"}}));

    flushRoutersAndRefreshShardMetadata(st, {ns, dbNames: [shardedDbName, unshardedDbName]});

    return shardedView;
}

const st = new ShardingTest({shards: 2, mongos: 1, config: 1});
const session = st.s.startSession();

// Set up an unsharded collection on shard0.
const unshardedView = setUpUnshardedCollectionAndView(st, session, st.shard0.shardName);

// Set up a sharded collection with one chunk on each shard in a database with shard0 as its
// primary shard.
const shardedView = setUpShardedCollectionAndView(st, session, st.shard0.shardName);

// Set up a view on the sharded view, in the same database.
const viewOnShardedView = session.getDatabase(shardedDbName)[viewOnShardedViewName];
assert.commandWorked(viewOnShardedView.runCommand(
    "create", {viewOn: shardedViewName, pipeline: [], writeConcern: {w: "majority"}}));

//
// The first statement a participant shard receives reading from a view should succeed.
//

function readFromViewOnFirstParticipantStatement(session, view, viewFunc, numDocsExpected) {
    session.startTransaction();
    assert.eq(viewFunc(view), numDocsExpected);
    assert.commandWorked(session.commitTransaction_forTesting());
}

// Unsharded view.
readFromViewOnFirstParticipantStatement(session, unshardedView, (view) => {
    return view.aggregate({$match: {}}).itcount();
}, 1);
readFromViewOnFirstParticipantStatement(session, unshardedView, (view) => {
    return view.distinct("_id").length;
}, 1);
readFromViewOnFirstParticipantStatement(session, unshardedView, (view) => {
    return view.find().itcount();
}, 1);

// Sharded view.
readFromViewOnFirstParticipantStatement(session, shardedView, (view) => {
    return view.aggregate({$match: {}}).itcount();
}, 2);
readFromViewOnFirstParticipantStatement(session, shardedView, (view) => {
    return view.distinct("_id").length;
}, 2);
readFromViewOnFirstParticipantStatement(session, shardedView, (view) => {
    return view.find().itcount();
}, 2);

// View on sharded view.
readFromViewOnFirstParticipantStatement(session, viewOnShardedView, (view) => {
    return view.aggregate({$match: {}}).itcount();
}, 2);
readFromViewOnFirstParticipantStatement(session, viewOnShardedView, (view) => {
    return view.distinct("_id").length;
}, 2);
readFromViewOnFirstParticipantStatement(session, viewOnShardedView, (view) => {
    return view.find().itcount();
}, 2);

//
// A later statement a participant shard receives reading from a view should succeed.
//

function readFromViewOnLaterParticipantStatement(session, view, viewFunc, numDocsExpected) {
    session.startTransaction();
    assert.eq(view.aggregate({$match: {}}).itcount(), numDocsExpected);
    assert.eq(viewFunc(view), numDocsExpected);
    assert.commandWorked(session.commitTransaction_forTesting());
}

// Unsharded view.
readFromViewOnLaterParticipantStatement(session, unshardedView, (view) => {
    return view.aggregate({$match: {}}).itcount();
}, 1);
readFromViewOnLaterParticipantStatement(session, unshardedView, (view) => {
    return view.distinct("_id").length;
}, 1);
readFromViewOnLaterParticipantStatement(session, unshardedView, (view) => {
    return view.find().itcount();
}, 1);

// Sharded view.
readFromViewOnLaterParticipantStatement(session, shardedView, (view) => {
    return view.aggregate({$match: {}}).itcount();
}, 2);
readFromViewOnLaterParticipantStatement(session, shardedView, (view) => {
    return view.distinct("_id").length;
}, 2);
readFromViewOnLaterParticipantStatement(session, shardedView, (view) => {
    return view.find().itcount();
}, 2);

// View on sharded view.
readFromViewOnLaterParticipantStatement(session, viewOnShardedView, (view) => {
    return view.aggregate({$match: {}}).itcount();
}, 2);
readFromViewOnLaterParticipantStatement(session, viewOnShardedView, (view) => {
    return view.distinct("_id").length;
}, 2);
readFromViewOnLaterParticipantStatement(session, viewOnShardedView, (view) => {
    return view.find().itcount();
}, 2);

//
// Transactions on shards that return a view resolution error on the first statement remain
// aborted if the shard is not targeted by the retry on the resolved namespace.
//
// This may happen when reading from a sharded view, because mongos will target the primary
// shard first to resolve the view, but the retry on the underlying sharded collection is not
// guaranteed to target the primary again.
//

// Assumes the request in viewFunc does not target the primary shard, Shard0.
function primaryShardNotReTargeted_FirstStatement(session, view, viewFunc, numDocsExpected) {
    session.startTransaction();
    assert.eq(viewFunc(view), numDocsExpected);

    // There should not be an in-progress transaction on the primary shard.
    assert.commandFailedWithCode(st.rs0.getPrimary().getDB("foo").runCommand({
        find: "bar",
        lsid: session.getSessionId(),
        txnNumber: NumberLong(session.getTxnNumber_forTesting()),
        autocommit: false,
    }),
                                 ErrorCodes.NoSuchTransaction);

    assert.commandWorked(session.commitTransaction_forTesting());

    // The transaction should not have been committed on the primary shard.
    assert.commandFailedWithCode(st.rs0.getPrimary().getDB("foo").runCommand({
        find: "bar",
        lsid: session.getSessionId(),
        txnNumber: NumberLong(session.getTxnNumber_forTesting()),
        autocommit: false,
    }),
                                 ErrorCodes.NoSuchTransaction);
}

// This is only possible against sharded views.
primaryShardNotReTargeted_FirstStatement(session, shardedView, (view) => {
    return view.aggregate({$match: {_id: 1}}).itcount();
}, 1);
primaryShardNotReTargeted_FirstStatement(session, shardedView, (view) => {
    return view.distinct("_id", {_id: {$gte: 1}}).length;
}, 1);
primaryShardNotReTargeted_FirstStatement(session, shardedView, (view) => {
    return view.find({_id: 1}).itcount();
}, 1);

// View on sharded view.
primaryShardNotReTargeted_FirstStatement(session, viewOnShardedView, (view) => {
    return view.aggregate({$match: {_id: 1}}).itcount();
}, 1);
primaryShardNotReTargeted_FirstStatement(session, viewOnShardedView, (view) => {
    return view.distinct("_id", {_id: {$gte: 1}}).length;
}, 1);
primaryShardNotReTargeted_FirstStatement(session, viewOnShardedView, (view) => {
    return view.find({_id: 1}).itcount();
}, 1);

//
// Shards do not abort on a view resolution error if they have already completed a statement for
// a transaction.
//

// Assumes the primary shard for view is Shard0.
function primaryShardNotReTargeted_LaterStatement(session, view, viewFunc, numDocsExpected) {
    session.startTransaction();
    // Complete a statement on the primary shard for the view.
    assert.eq(view.aggregate({$match: {_id: -1}}).itcount(), 1);
    // Targets the primary first, but the resolved retry only targets Shard1.
    assert.eq(viewFunc(view), numDocsExpected);
    assert.commandWorked(session.commitTransaction_forTesting());
}

// This is only possible against sharded views.
primaryShardNotReTargeted_LaterStatement(session, shardedView, (view) => {
    return view.aggregate({$match: {_id: 1}}).itcount();
}, 1);
primaryShardNotReTargeted_LaterStatement(session, shardedView, (view) => {
    return view.distinct("_id", {_id: {$gte: 1}}).length;
}, 1);
primaryShardNotReTargeted_LaterStatement(session, shardedView, (view) => {
    return view.find({_id: 1}).itcount();
}, 1);

// View on sharded view.
primaryShardNotReTargeted_LaterStatement(session, viewOnShardedView, (view) => {
    return view.aggregate({$match: {_id: 1}}).itcount();
}, 1);
primaryShardNotReTargeted_LaterStatement(session, viewOnShardedView, (view) => {
    return view.distinct("_id", {_id: {$gte: 1}}).length;
}, 1);
primaryShardNotReTargeted_LaterStatement(session, viewOnShardedView, (view) => {
    return view.find({_id: 1}).itcount();
}, 1);

//
// Reading from a view using $lookup and $graphLookup should succeed.
//

function assertAggResultEqInTransaction(coll, pipeline, expected) {
    session.startTransaction();
    const resArray = coll.aggregate(pipeline).toArray();
    assert(arrayEq(resArray, expected), tojson({got: resArray, expected: expected}));
    assert.commandWorked(session.commitTransaction_forTesting());
}

// Set up an unsharded collection to use for $lookup. We cannot lookup into sharded collections.
// TODO SERVER-29159: Add testing for lookup into sharded collections in a transaction once that
// is supported.
const lookupDbName = "dbForLookup";
const lookupCollName = "collForLookup";
assert.writeOK(
    st.s.getDB(lookupDbName)[lookupCollName].insert({_id: 1}, {writeConcern: {w: "majority"}}));
const lookupColl = session.getDatabase(unshardedDbName)[unshardedCollName];

// Lookup the document in the unsharded collection with _id: 1 through the unsharded view.
assertAggResultEqInTransaction(
    lookupColl,
    [
        {$match: {_id: 1}},
        {$lookup: {from: unshardedViewName, localField: "_id", foreignField: "_id", as: "matched"}},
        {$unwind: "$matched"},
        {$project: {_id: 1, matchedX: "$matched.x"}}
    ],
    [{_id: 1, matchedX: "unsharded"}]);

// Find the same document through the view using $graphLookup.
assertAggResultEqInTransaction(lookupColl,
                                   [
                                     {$match: {_id: 1}},
                                     {
                                       $graphLookup: {
                                           from: unshardedViewName,
                                           startWith: "$_id",
                                           connectFromField: "_id",
                                           connectToField: "_id",
                                           as: "matched"
                                       }
                                     },
                                     {$unwind: "$matched"},
                                     {$project: {_id: 1, matchedX: "$matched.x"}}
                                   ],
                                   [{_id: 1, matchedX: "unsharded"}]);

st.stop();
})();