summaryrefslogtreecommitdiff
path: root/jstests/change_streams/oplog_rewrite/change_stream_match_pushdown_documentKey_rewrite.js
blob: a9a7bfc34554d6c6f9227b75a0a68399e6aa14c1 (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
// Test that a pipeline of the form [{$changeStream: {}}, {$match: <predicate>}] with a predicate
// involving the 'documentKey' field can push down the $match and rewrite the $match and make it
// part of the oplog cursor's filter in order to filter out results as early as possible.
// @tags: [
//   featureFlagChangeStreamsRewrite,
//   requires_fcv_51,
//   requires_pipeline_optimization,
//   requires_sharding,
//   uses_change_streams,
//   change_stream_does_not_expect_txns,
//   assumes_unsharded_collection,
//   assumes_read_preference_unchanged
// ]
(function() {
"use strict";

load("jstests/libs/change_stream_rewrite_util.js");  // For rewrite helpers.
load("jstests/libs/fixture_helpers.js");             // For FixtureHelpers.

const dbName = "change_stream_match_pushdown_documentKey_rewrite";
const collName = "change_stream_match_pushdown_documentKey_rewrite";

const st = new ShardingTest({
    shards: 2,
    rs: {nodes: 1, setParameter: {writePeriodicNoops: true, periodicNoopIntervalSecs: 1}}
});

const mongosConn = st.s;
const db = mongosConn.getDB(dbName);

// Returns a newly created sharded collection, where shard key is 'shard'.
const coll = createShardedCollection(st, "shard" /* shardKey */, dbName, collName, 1 /* splitAt */);

// A helper that opens a change stream with the user supplied match expression 'userMatchExpr' and
// validates that:
// (1) for each shard, the events are seen in that order as specified in 'expectedOps'; and
// (2) each shard returns the expected number of events; and
// (3) the number of docs returned by the oplog cursor on each shard matches what we expect
//     as specified in 'expectedOplogCursorReturnedDocs'.
function verifyOps(resumeAfterToken, userMatchExpr, expectedOps, expectedOplogCursorReturnedDocs) {
    const cursor =
        coll.aggregate([{$changeStream: {resumeAfter: resumeAfterToken}}, userMatchExpr]);

    let expectedChangeStreamDocsReturned = [0, 0];
    for (const [op, id, shardId] of expectedOps) {
        assert.soon(() => cursor.hasNext());
        const event = cursor.next();
        assert.eq(event.operationType, op, event);
        assert.eq(event.documentKey._id, id, event);
        assert.eq(event.documentKey.shard, shardId, event);
        if (shardId == 0 || shardId == 1) {
            ++expectedChangeStreamDocsReturned[shardId];
        }
    }

    assert(!cursor.hasNext());

    // An 'executionStats' could only be captured for a non-invalidating stream.
    const stats = coll.explain("executionStats")
                      .aggregate([{$changeStream: {resumeAfter: resumeAfterToken}}, userMatchExpr]);

    assertNumChangeStreamDocsReturnedFromShard(
        stats, st.rs0.name, expectedChangeStreamDocsReturned[0]);
    assertNumChangeStreamDocsReturnedFromShard(
        stats, st.rs1.name, expectedChangeStreamDocsReturned[1]);
    assertNumMatchingOplogEventsForShard(stats, st.rs0.name, expectedOplogCursorReturnedDocs[0]);
    assertNumMatchingOplogEventsForShard(stats, st.rs1.name, expectedOplogCursorReturnedDocs[1]);
}

// Open a change stream and store the resume token. This resume token will be used to replay the
// stream after this point.
const resumeAfterToken = coll.watch([]).getResumeToken();

// These operations will create oplog events. The change stream will apply several filters on these
// series of events and ensure that the '$match' expressions are rewritten correctly.
assert.commandWorked(coll.insert({_id: 2, shard: 0}));
assert.commandWorked(coll.insert({_id: 3, shard: 0, z: 4}));
assert.commandWorked(coll.insert({_id: 2, shard: 1, z: 4}));
assert.commandWorked(coll.insert({_id: 3, shard: 1}));
assert.commandWorked(coll.update({_id: 2, shard: 0}, {$set: {foo: "a"}}));
assert.commandWorked(coll.update({_id: 3, shard: 0}, {$set: {foo: "a"}}));
assert.commandWorked(coll.update({_id: 2, shard: 1}, {$set: {foo: "a"}}));
assert.commandWorked(coll.update({_id: 3, shard: 1}, {$set: {foo: "a"}}));
assert.commandWorked(coll.replaceOne({_id: 2, shard: 0}, {_id: 2, shard: 0, foo: "b"}));
assert.commandWorked(coll.replaceOne({_id: 3, shard: 0}, {_id: 3, shard: 0, z: 4, foo: "b"}));
assert.commandWorked(coll.replaceOne({_id: 2, shard: 1}, {_id: 2, shard: 1, z: 4, foo: "b"}));
assert.commandWorked(coll.replaceOne({_id: 3, shard: 1}, {_id: 3, shard: 1, foo: "b"}));
assert.commandWorked(coll.deleteOne({_id: 2, shard: 0}));
assert.commandWorked(coll.deleteOne({_id: 3, shard: 0}));
assert.commandWorked(coll.deleteOne({_id: 2, shard: 1}));
assert.commandWorked(coll.deleteOne({_id: 3, shard: 1}));

// Enable a failpoint that will prevent $expr match expressions from generating $_internalExprEq
// or similar expressions. This ensures that the following test-cases only exercise the $expr
// rewrites.
assert.commandWorked(
    db.adminCommand({configureFailPoint: "disableMatchExpressionOptimization", mode: "alwaysOn"}));
FixtureHelpers.runCommandOnEachPrimary({
    db: db.getSiblingDB("admin"),
    cmdObj: {configureFailPoint: "disableMatchExpressionOptimization", mode: "alwaysOn"}
});

// Ensure that the '$match' on the 'insert', 'update', 'replace', and 'delete' operation types with
// various predicates are rewritten correctly.
for (const op of ["insert", "update", "replace", "delete"]) {
    // Test out a predicate on the full 'documentKey' field.
    verifyOps(resumeAfterToken,
              {$match: {operationType: op, documentKey: {shard: 0, _id: 2}}},
              [[op, 2, 0]],
              [1, 0] /* expectedOplogCursorReturnedDocs */);

    // Test out a predicate on 'documentKey._id'.
    verifyOps(resumeAfterToken,
              {$match: {operationType: op, "documentKey._id": 2}},
              [[op, 2, 0], [op, 2, 1]],
              [1, 1] /* expectedOplogCursorReturnedDocs */);

    // Test out a predicate on 'documentKey.shard'.
    verifyOps(resumeAfterToken,
              {$match: {operationType: op, "documentKey.shard": 1}},
              [[op, 2, 1], [op, 3, 1]],
              [0, 2] /* expectedOplogCursorReturnedDocs */);

    // Test out a negated predicate on the full 'documentKey' field. It's not possible to rewrite
    // this predicate and make it part of the oplog filter, so we expect the oplog cursor to return
    // 2 docs on each shard.
    verifyOps(resumeAfterToken,
              {$match: {operationType: op, documentKey: {$not: {$eq: {shard: 0, _id: 2}}}}},
              [[op, 3, 0], [op, 2, 1], [op, 3, 1]],
              [2, 2] /* expectedOplogCursorReturnedDocs */);

    // Test out a negated predicate on 'documentKey._id'.
    verifyOps(resumeAfterToken,
              {$match: {operationType: op, "documentKey._id": {$not: {$eq: 2}}}},
              [[op, 3, 0], [op, 3, 1]],
              [1, 1] /* expectedOplogCursorReturnedDocs */);

    // Test out an {$eq: null} predicate on 'documentKey._id'.
    verifyOps(resumeAfterToken,
              {$match: {operationType: op, "documentKey._id": {$eq: null}}},
              [],
              [0, 0] /* expectedOplogCursorReturnedDocs */);

    // Test out a negated predicate on 'documentKey.shard'. It's not possible to rewrite this
    // predicate and make it part of the oplog filter, so we expect the oplog cursor to return 2
    // docs on each shard.
    verifyOps(resumeAfterToken,
              {$match: {operationType: op, "documentKey.shard": {$not: {$eq: 1}}}},
              [[op, 2, 0], [op, 3, 0]],
              [2, 2] /* expectedOplogCursorReturnedDocs */);

    // Test out the '{$exists: false}' predicate on a field that doesn't exist in 'documentKey' but
    // that does exist in some of the underlying documents.
    verifyOps(resumeAfterToken,
              {$match: {operationType: op, "documentKey.z": {$exists: false}}},
              [[op, 2, 0], [op, 3, 0], [op, 2, 1], [op, 3, 1]],
              [2, 2] /* expectedOplogCursorReturnedDocs */);

    // Test out the '{$eq: null}' predicate on a field that doesn't exist in 'documentKey' but that
    // does exist in some of the underlying documents.
    verifyOps(resumeAfterToken,
              {$match: {operationType: op, "documentKey.z": {$eq: null}}},
              [[op, 2, 0], [op, 3, 0], [op, 2, 1], [op, 3, 1]],
              [2, 2] /* expectedOplogCursorReturnedDocs */);

    // Test out an $expr predicate on the full 'documentKey' field.
    verifyOps(
        resumeAfterToken,
        {
            $match:
                {$and: [{operationType: op}, {$expr: {$eq: ["$documentKey", {shard: 0, _id: 2}]}}]}
        },
        [[op, 2, 0]],
        [2, 2] /* expectedOplogCursorReturnedDocs */);

    // Test out a negated predicate on the full 'documentKey' field.
    verifyOps(resumeAfterToken,
              {
                  $match: {
                      $and: [
                          {operationType: op},
                          {$expr: {$not: {$eq: ["$documentKey", {shard: 0, _id: 2}]}}}
                      ]
                  }
              },
              [[op, 3, 0], [op, 2, 1], [op, 3, 1]],
              [2, 2] /* expectedOplogCursorReturnedDocs */);

    // Test out an $expr predicate on 'documentKey._id'.
    verifyOps(resumeAfterToken,
              {$match: {$and: [{operationType: op}, {$expr: {$eq: ["$documentKey._id", 2]}}]}},
              [[op, 2, 0], [op, 2, 1]],
              [1, 1] /* expectedOplogCursorReturnedDocs */);

    // Test out a negated $expr predicate on 'documentKey._id'.
    verifyOps(
        resumeAfterToken,
        {$match: {$and: [{operationType: op}, {$expr: {$not: {$eq: ["$documentKey._id", 2]}}}]}},
        [[op, 3, 0], [op, 3, 1]],
        [1, 1] /* expectedOplogCursorReturnedDocs */);

    // Test out an $expr predicate on 'documentKey.shard'.
    verifyOps(resumeAfterToken,
              {$match: {$and: [{operationType: op}, {$expr: {$eq: ["$documentKey.shard", 1]}}]}},
              [[op, 2, 1], [op, 3, 1]],
              [2, 2] /* expectedOplogCursorReturnedDocs */);

    // Test out a negated $expr predicate on 'documentKey.shard'.
    verifyOps(
        resumeAfterToken,
        {$match: {$and: [{operationType: op}, {$expr: {$not: {$eq: ["$documentKey.shard", 1]}}}]}},
        [[op, 2, 0], [op, 3, 0]],
        [2, 2] /* expectedOplogCursorReturnedDocs */);
}

st.stop();
})();