MB-24034: VBucketTest: addOne/setOne to return Add/MutationStatus
[ep-engine.git] / tests / module_tests / vbucket_test.cc
1 /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2 /*
3  *     Copyright 2016 Couchbase, Inc
4  *
5  *   Licensed under the Apache License, Version 2.0 (the "License");
6  *   you may not use this file except in compliance with the License.
7  *   You may obtain a copy of the License at
8  *
9  *       http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *   Unless required by applicable law or agreed to in writing, software
12  *   distributed under the License is distributed on an "AS IS" BASIS,
13  *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *   See the License for the specific language governing permissions and
15  *   limitations under the License.
16  */
17
18 #include "config.h"
19
20 #include "vbucket_test.h"
21 #include "bgfetcher.h"
22 #include "ep_vb.h"
23 #include "failover-table.h"
24 #include "item.h"
25 #include "programs/engine_testapp/mock_server.h"
26 #include "tests/module_tests/test_helpers.h"
27
28 #include <platform/cb_malloc.h>
29
30 void VBucketTest::SetUp() {
31     const auto eviction_policy = GetParam();
32     vbucket.reset(new EPVBucket(0,
33                                 vbucket_state_active,
34                                 global_stats,
35                                 checkpoint_config,
36                                 /*kvshard*/ nullptr,
37                                 /*lastSeqno*/ 1000,
38                                 /*lastSnapStart*/ 0,
39                                 /*lastSnapEnd*/ 0,
40                                 /*table*/ nullptr,
41                                 std::make_shared<DummyCB>(),
42                                 /*newSeqnoCb*/ nullptr,
43                                 config,
44                                 eviction_policy));
45 }
46
47 void VBucketTest::TearDown() {
48     vbucket.reset();
49 }
50
51 std::vector<StoredDocKey> VBucketTest::generateKeys(int num, int start) {
52     std::vector<StoredDocKey> rv;
53
54     for (int i = start; i < num; i++) {
55         rv.push_back(makeStoredDocKey(std::to_string(i)));
56     }
57
58     return rv;
59 }
60
61 AddStatus VBucketTest::addOne(const StoredDocKey& k, int expiry) {
62     Item i(k, 0, expiry, k.data(), k.size());
63     return public_processAdd(i);
64 }
65
66 void VBucketTest::addMany(std::vector<StoredDocKey>& keys, AddStatus expect) {
67     for (const auto& k : keys) {
68         EXPECT_EQ(expect, addOne(k));
69     }
70 }
71
72 MutationStatus VBucketTest::setOne(const StoredDocKey& k, int expiry) {
73     Item i(k, 0, expiry, k.data(), k.size());
74     return public_processSet(i, i.getCas());
75 }
76
77 void VBucketTest::setMany(std::vector<StoredDocKey>& keys,
78                           MutationStatus expect) {
79     for (const auto& k : keys) {
80         EXPECT_EQ(expect, setOne(k));
81     }
82 }
83
84 void VBucketTest::softDeleteOne(const StoredDocKey& k, MutationStatus expect) {
85     StoredValue* v(vbucket->ht.find(k, TrackReference::No, WantsDeleted::No));
86     EXPECT_NE(nullptr, v);
87
88     EXPECT_EQ(expect, public_processSoftDelete(v->getKey(), v, 0))
89             << "Failed to soft delete key " << k.c_str();
90 }
91
92 void VBucketTest::softDeleteMany(std::vector<StoredDocKey>& keys,
93                                  MutationStatus expect) {
94     for (const auto& k : keys) {
95         softDeleteOne(k, expect);
96     }
97 }
98
99 StoredValue* VBucketTest::findValue(StoredDocKey& key) {
100     return vbucket->ht.find(key, TrackReference::Yes, WantsDeleted::Yes);
101 }
102
103 void VBucketTest::verifyValue(StoredDocKey& key,
104                               const char* value,
105                               TrackReference trackReference,
106                               WantsDeleted wantDeleted) {
107     StoredValue* v = vbucket->ht.find(key, trackReference, wantDeleted);
108     EXPECT_NE(nullptr, v);
109     value_t val = v->getValue();
110     if (!value) {
111         EXPECT_EQ(nullptr, val.get());
112     } else {
113         EXPECT_STREQ(value, val->to_s().c_str());
114     }
115 }
116
117 std::pair<HashTable::HashBucketLock, StoredValue*> VBucketTest::lockAndFind(
118         const StoredDocKey& key) {
119     auto hbl = vbucket->ht.getLockedBucket(key);
120     auto* storedVal = vbucket->ht.unlocked_find(
121             key, hbl.getBucketNum(), WantsDeleted::Yes, TrackReference::No);
122     return std::make_pair(std::move(hbl), storedVal);
123 }
124
125 MutationStatus VBucketTest::public_processSet(Item& itm, const uint64_t cas) {
126     auto hbl_sv = lockAndFind(itm.getKey());
127     VBQueueItemCtx queueItmCtx(GenerateBySeqno::Yes,
128                                GenerateCas::No,
129                                TrackCasDrift::No,
130                                /*isBackfillItem*/ false,
131                                /*preLinkDocumentContext_*/ nullptr);
132     return vbucket
133             ->processSet(hbl_sv.first,
134                          hbl_sv.second,
135                          itm,
136                          cas,
137                          true,
138                          false,
139                          &queueItmCtx)
140             .first;
141 }
142
143 AddStatus VBucketTest::public_processAdd(Item& itm) {
144     auto hbl_sv = lockAndFind(itm.getKey());
145     return vbucket
146             ->processAdd(hbl_sv.first,
147                          hbl_sv.second,
148                          itm,
149                          /*maybeKeyExists*/ true,
150                          /*isReplication*/ false)
151             .first;
152 }
153
154 MutationStatus VBucketTest::public_processSoftDelete(const DocKey& key,
155                                                      StoredValue* v,
156                                                      uint64_t cas) {
157     auto hbl = vbucket->ht.getLockedBucket(key);
158     if (!v) {
159         v = vbucket->ht.unlocked_find(
160                 key, hbl.getBucketNum(), WantsDeleted::No, TrackReference::No);
161         if (!v) {
162             return MutationStatus::NotFound;
163         }
164     }
165     ItemMetaData metadata;
166     metadata.revSeqno = v->getRevSeqno() + 1;
167     MutationStatus status;
168     std::tie(status, std::ignore, std::ignore) = vbucket->processSoftDelete(
169             hbl,
170             *v,
171             cas,
172             metadata,
173             VBQueueItemCtx(GenerateBySeqno::Yes,
174                            GenerateCas::Yes,
175                            TrackCasDrift::No,
176                            /*isBackfillItem*/ false,
177                            /*preLinkDocCtx*/ nullptr),
178             /*use_meta*/ false,
179             /*bySeqno*/ v->getBySeqno());
180     return status;
181 }
182
183 bool VBucketTest::public_deleteStoredValue(const DocKey& key) {
184     auto hbl_sv = lockAndFind(key);
185     if (!hbl_sv.second) {
186         return false;
187     }
188     return vbucket->deleteStoredValue(hbl_sv.first, *hbl_sv.second);
189 }
190
191 size_t EPVBucketTest::public_queueBGFetchItem(
192         const DocKey& key,
193         std::unique_ptr<VBucketBGFetchItem> fetchItem,
194         BgFetcher* bgFetcher) {
195     return dynamic_cast<EPVBucket&>(*vbucket).queueBGFetchItem(
196             key, std::move(fetchItem), bgFetcher);
197 }
198
199 class BlobTest : public Blob {
200 public:
201     BlobTest() : Blob(0,0) {}
202     static size_t getAllocationSize(size_t len){
203         return Blob::getAllocationSize(len);
204     }
205 };
206
207 TEST(BlobTest, basicAllocationSize){
208     EXPECT_EQ(BlobTest::getAllocationSize(10), 20);
209
210     // Expected to be 10 because the 2 bytes of the data member array will not
211     // be allocated because they will not be used.
212     EXPECT_EQ(BlobTest::getAllocationSize(0), 10);
213 }
214
215 // Measure performance of VBucket::getBGFetchItems - queue and then get
216 // 10,000 items from the vbucket.
217 TEST_P(EPVBucketTest, GetBGFetchItemsPerformance) {
218     BgFetcher fetcher(/*store*/ nullptr, /*shard*/ nullptr, this->global_stats);
219
220     for (unsigned int ii = 0; ii < 100000; ii++) {
221         auto fetchItem = std::make_unique<VBucketBGFetchItem>(
222                 /*cookie*/ nullptr,
223                 /*isMeta*/ false);
224         this->public_queueBGFetchItem(
225                 makeStoredDocKey(std::to_string(ii)),
226                 std::move(fetchItem),
227                 &fetcher);
228     }
229     auto items = this->vbucket->getBGFetchItems();
230 }
231
232 // Check the existence of bloom filter after performing a
233 // swap of existing filter with a temporary filter.
234 TEST_P(VBucketTest, SwapFilter) {
235     this->vbucket->createFilter(1, 1.0);
236     ASSERT_FALSE(this->vbucket->isTempFilterAvailable());
237     ASSERT_NE("DOESN'T EXIST", this->vbucket->getFilterStatusString());
238     this->vbucket->swapFilter();
239     EXPECT_NE("DOESN'T EXIST", this->vbucket->getFilterStatusString());
240 }
241
242 TEST_P(VBucketTest, Add) {
243     const auto eviction_policy = GetParam();
244     if (eviction_policy != VALUE_ONLY) {
245         return;
246     }
247     const int nkeys = 1000;
248
249     auto keys = generateKeys(nkeys);
250     addMany(keys, AddStatus::Success);
251
252     StoredDocKey missingKey = makeStoredDocKey("aMissingKey");
253     EXPECT_FALSE(this->vbucket->ht.find(
254             missingKey, TrackReference::Yes, WantsDeleted::No));
255
256     for (const auto& key : keys) {
257         EXPECT_TRUE(this->vbucket->ht.find(
258                 key, TrackReference::Yes, WantsDeleted::No));
259     }
260
261     addMany(keys, AddStatus::Exists);
262     for (const auto& key : keys) {
263         EXPECT_TRUE(this->vbucket->ht.find(
264                 key, TrackReference::Yes, WantsDeleted::No));
265     }
266
267     // Verify we can read after a soft deletion.
268     EXPECT_EQ(MutationStatus::WasDirty,
269               this->public_processSoftDelete(keys[0], nullptr, 0));
270     EXPECT_EQ(MutationStatus::NotFound,
271               this->public_processSoftDelete(keys[0], nullptr, 0));
272     EXPECT_FALSE(this->vbucket->ht.find(
273             keys[0], TrackReference::Yes, WantsDeleted::No));
274
275     Item i(keys[0], 0, 0, "newtest", 7);
276     EXPECT_EQ(AddStatus::UnDel, this->public_processAdd(i));
277     EXPECT_EQ(nkeys, this->vbucket->ht.getNumItems());
278 }
279
280 TEST_P(VBucketTest, AddExpiry) {
281     const auto eviction_policy = GetParam();
282     if (eviction_policy != VALUE_ONLY) {
283         return;
284     }
285     StoredDocKey k = makeStoredDocKey("aKey");
286
287     ASSERT_EQ(AddStatus::Success, addOne(k, ep_real_time() + 5));
288     EXPECT_EQ(AddStatus::Exists, addOne(k, ep_real_time() + 5));
289
290     StoredValue* v =
291             this->vbucket->ht.find(k, TrackReference::Yes, WantsDeleted::No);
292     EXPECT_TRUE(v);
293     EXPECT_FALSE(v->isExpired(ep_real_time()));
294     EXPECT_TRUE(v->isExpired(ep_real_time() + 6));
295
296     TimeTraveller biffTannen(6);
297     EXPECT_TRUE(v->isExpired(ep_real_time()));
298
299     EXPECT_EQ(AddStatus::UnDel, addOne(k, ep_real_time() + 5));
300     EXPECT_TRUE(v);
301     EXPECT_FALSE(v->isExpired(ep_real_time()));
302     EXPECT_TRUE(v->isExpired(ep_real_time() + 6));
303 }
304
305 /**
306  * Test to check if an unlocked_softDelete performed on an
307  * existing item with a new value results in a success
308  */
309 TEST_P(VBucketTest, unlockedSoftDeleteWithValue) {
310     const auto eviction_policy = GetParam();
311     if (eviction_policy != VALUE_ONLY) {
312         return;
313     }
314
315     // Setup - create a key and then delete it with a value.
316     StoredDocKey key = makeStoredDocKey("key");
317     Item stored_item(key, 0, 0, "value", strlen("value"));
318     ASSERT_EQ(MutationStatus::WasClean,
319               this->public_processSet(stored_item, stored_item.getCas()));
320
321     StoredValue* v(
322             this->vbucket->ht.find(key, TrackReference::No, WantsDeleted::No));
323     EXPECT_NE(nullptr, v);
324
325     // Create an item and set its state to deleted
326     Item deleted_item(key, 0, 0, "deletedvalue", strlen("deletedvalue"));
327     deleted_item.setDeleted();
328
329     auto prev_revseqno = v->getRevSeqno();
330     deleted_item.setRevSeqno(prev_revseqno);
331
332     EXPECT_EQ(MutationStatus::WasDirty,
333               this->public_processSet(deleted_item, 0));
334     verifyValue(key, "deletedvalue", TrackReference::Yes, WantsDeleted::Yes);
335     EXPECT_EQ(prev_revseqno + 1, v->getRevSeqno());
336 }
337
338 /**
339  * Test to check that if an item has expired, an incoming mutation
340  * on that item, if in deleted state results in an invalid cas and
341  * if not in deleted state, results in not found
342  */
343 TEST_P(VBucketTest, updateExpiredItem) {
344     // Setup - create a key
345     StoredDocKey key = makeStoredDocKey("key");
346     Item stored_item(key, 0, ep_real_time() - 1, "value", strlen("value"));
347     ASSERT_EQ(MutationStatus::WasClean,
348               this->public_processSet(stored_item, stored_item.getCas()));
349
350     StoredValue* v = this->vbucket->ht.find(key, TrackReference::No, WantsDeleted::No);
351     EXPECT_TRUE(v);
352     EXPECT_TRUE(v->isExpired(ep_real_time()));
353
354     auto cas = v->getCas();
355     // Create an item and set its state to deleted.
356     Item deleted_item(key, 0, 0, "deletedvalue", strlen("deletedvalue"));
357
358     EXPECT_EQ(MutationStatus::NotFound,
359               this->public_processSet(deleted_item, cas + 1));
360
361     deleted_item.setDeleted();
362     EXPECT_EQ(MutationStatus::InvalidCas,
363               this->public_processSet(deleted_item, cas + 1));
364 }
365
366 /**
367  * Test to check if an unlocked_softDelete performed on a
368  * deleted item without a value and with a value
369  */
370 TEST_P(VBucketTest, updateDeletedItem) {
371     const auto eviction_policy = GetParam();
372     if (eviction_policy != VALUE_ONLY) {
373         return;
374     }
375
376     // Setup - create a key and then delete it.
377     StoredDocKey key = makeStoredDocKey("key");
378     Item stored_item(key, 0, 0, "value", strlen("value"));
379     ASSERT_EQ(MutationStatus::WasClean,
380               this->public_processSet(stored_item, stored_item.getCas()));
381
382     StoredValue* v(
383             this->vbucket->ht.find(key, TrackReference::No, WantsDeleted::No));
384     EXPECT_NE(nullptr, v);
385
386     ItemMetaData itm_meta;
387     EXPECT_EQ(MutationStatus::WasDirty,
388               this->public_processSoftDelete(v->getKey(), v, 0));
389     verifyValue(key, nullptr, TrackReference::Yes, WantsDeleted::Yes);
390     EXPECT_EQ(1, this->vbucket->getNumItems());
391     EXPECT_EQ(1, this->vbucket->getNumInMemoryDeletes());
392
393     Item deleted_item(key, 0, 0, "deletedvalue", strlen("deletedvalue"));
394     deleted_item.setDeleted();
395
396     auto prev_revseqno = v->getRevSeqno();
397     deleted_item.setRevSeqno(prev_revseqno);
398
399     EXPECT_EQ(MutationStatus::WasDirty,
400               this->public_processSet(deleted_item, 0));
401     verifyValue(
402                 key,
403                 "deletedvalue",
404                 TrackReference::Yes,
405                 WantsDeleted::Yes);
406     EXPECT_EQ(1, this->vbucket->getNumItems());
407     EXPECT_EQ(1, this->vbucket->getNumInMemoryDeletes());
408     EXPECT_EQ(prev_revseqno + 1, v->getRevSeqno());
409
410     Item update_deleted_item(
411             key, 0, 0, "updatedeletedvalue", strlen("updatedeletedvalue"));
412     update_deleted_item.setDeleted();
413
414     prev_revseqno = v->getRevSeqno();
415     update_deleted_item.setRevSeqno(prev_revseqno);
416
417     EXPECT_EQ(MutationStatus::WasDirty,
418               this->public_processSet(update_deleted_item, 0));
419     verifyValue(
420             key, "updatedeletedvalue", TrackReference::Yes, WantsDeleted::Yes);
421     EXPECT_EQ(1, this->vbucket->getNumItems());
422     EXPECT_EQ(1, this->vbucket->getNumInMemoryDeletes());
423     EXPECT_EQ(prev_revseqno + 1, v->getRevSeqno());
424 }
425
426 TEST_P(VBucketTest, SizeStatsSoftDel) {
427     this->global_stats.reset();
428     ASSERT_EQ(0, this->vbucket->ht.memSize.load());
429     ASSERT_EQ(0, this->vbucket->ht.cacheSize.load());
430     size_t initialSize = this->global_stats.currentSize.load();
431
432     const StoredDocKey k = makeStoredDocKey("somekey");
433     const size_t itemSize(16 * 1024);
434     char* someval(static_cast<char*>(cb_calloc(1, itemSize)));
435     EXPECT_TRUE(someval);
436
437     Item i(k, 0, 0, someval, itemSize);
438
439     EXPECT_EQ(MutationStatus::WasClean,
440               this->public_processSet(i, i.getCas()));
441
442     EXPECT_EQ(MutationStatus::WasDirty,
443               this->public_processSoftDelete(k, nullptr, 0));
444     this->public_deleteStoredValue(k);
445
446     EXPECT_EQ(0, this->vbucket->ht.memSize.load());
447     EXPECT_EQ(0, this->vbucket->ht.cacheSize.load());
448     EXPECT_EQ(initialSize, this->global_stats.currentSize.load());
449
450     cb_free(someval);
451 }
452
453 TEST_P(VBucketTest, SizeStatsSoftDelFlush) {
454     this->global_stats.reset();
455     ASSERT_EQ(0, this->vbucket->ht.memSize.load());
456     ASSERT_EQ(0, this->vbucket->ht.cacheSize.load());
457     size_t initialSize = this->global_stats.currentSize.load();
458
459     StoredDocKey k = makeStoredDocKey("somekey");
460     const size_t itemSize(16 * 1024);
461     char* someval(static_cast<char*>(cb_calloc(1, itemSize)));
462     EXPECT_TRUE(someval);
463
464     Item i(k, 0, 0, someval, itemSize);
465
466     EXPECT_EQ(MutationStatus::WasClean,
467               this->public_processSet(i, i.getCas()));
468
469     EXPECT_EQ(MutationStatus::WasDirty,
470               this->public_processSoftDelete(k, nullptr, 0));
471     this->vbucket->ht.clear();
472
473     EXPECT_EQ(0, this->vbucket->ht.memSize.load());
474     EXPECT_EQ(0, this->vbucket->ht.cacheSize.load());
475     EXPECT_EQ(initialSize, this->global_stats.currentSize.load());
476
477     cb_free(someval);
478 }
479
480 class VBucketEvictionTest : public VBucketTest {};
481
482 // Check that counts of items and resident items are as expected when items are
483 // ejected from the HashTable.
484 TEST_P(VBucketEvictionTest, EjectionResidentCount) {
485     const auto eviction_policy = GetParam();
486     ASSERT_EQ(0, this->vbucket->getNumItems());
487     ASSERT_EQ(0, this->vbucket->getNumNonResidentItems());
488
489     Item item(makeStoredDocKey("key"), /*flags*/0, /*exp*/0,
490               /*data*/nullptr, /*ndata*/0);
491
492     EXPECT_EQ(MutationStatus::WasClean,
493               this->public_processSet(item, item.getCas()));
494
495     EXPECT_EQ(1, this->vbucket->getNumItems());
496     EXPECT_EQ(0, this->vbucket->getNumNonResidentItems());
497
498     // TODO-MT: Should acquire lock really (ok given this is currently
499     // single-threaded).
500     auto* stored_item = this->vbucket->ht.find(
501             makeStoredDocKey("key"), TrackReference::Yes, WantsDeleted::No);
502     EXPECT_NE(nullptr, stored_item);
503     // Need to clear the dirty flag to allow it to be ejected.
504     stored_item->markClean();
505     EXPECT_TRUE(this->vbucket->ht.unlocked_ejectItem(stored_item,
506                                                      eviction_policy));
507
508     // After ejection, should still have 1 item in VBucket, but also have
509     // 1 non-resident item.
510     EXPECT_EQ(1, this->vbucket->getNumItems());
511     EXPECT_EQ(1, this->vbucket->getNumNonResidentItems());
512 }
513
514 // Regression test for MB-21448 - if an attempt is made to perform a CAS
515 // operation on a logically deleted item we should return NOT_FOUND
516 // (aka KEY_ENOENT) and *not* INVALID_CAS (aka KEY_EEXISTS).
517 TEST_P(VBucketEvictionTest, MB21448_UnlockedSetWithCASDeleted) {
518     // Setup - create a key and then delete it.
519     StoredDocKey key = makeStoredDocKey("key");
520     Item item(key, 0, 0, "deleted", strlen("deleted"));
521     ASSERT_EQ(MutationStatus::WasClean,
522               this->public_processSet(item, item.getCas()));
523     ASSERT_EQ(MutationStatus::WasDirty,
524               this->public_processSoftDelete(key, nullptr, 0));
525
526     // Attempt to perform a set on a deleted key with a CAS.
527     Item replacement(key, 0, 0, "value", strlen("value"));
528     EXPECT_EQ(MutationStatus::NotFound,
529               this->public_processSet(replacement,
530                                                /*cas*/ 10))
531             << "When trying to replace-with-CAS a deleted item";
532 }
533
534 // Test cases which run in both Full and Value eviction
535 INSTANTIATE_TEST_CASE_P(
536         FullAndValueEviction,
537         VBucketTest,
538         ::testing::Values(VALUE_ONLY, FULL_EVICTION),
539         [](const ::testing::TestParamInfo<item_eviction_policy_t>& info) {
540             if (info.param == VALUE_ONLY) {
541                 return "VALUE_ONLY";
542             } else {
543                 return "FULL_EVICTION";
544             }
545         });
546
547 INSTANTIATE_TEST_CASE_P(
548         FullAndValueEviction,
549         VBucketEvictionTest,
550         ::testing::Values(VALUE_ONLY, FULL_EVICTION),
551         [](const ::testing::TestParamInfo<item_eviction_policy_t>& info) {
552             if (info.param == VALUE_ONLY) {
553                 return "VALUE_ONLY";
554             } else {
555                 return "FULL_EVICTION";
556             }
557         });
558
559 INSTANTIATE_TEST_CASE_P(
560         FullAndValueEviction,
561         EPVBucketTest,
562         ::testing::Values(VALUE_ONLY, FULL_EVICTION),
563         [](const ::testing::TestParamInfo<item_eviction_policy_t>& info) {
564             if (info.param == VALUE_ONLY) {
565                 return "VALUE_ONLY";
566             } else {
567                 return "FULL_EVICTION";
568             }
569         });