1 /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
3 * Copyright 2016 Couchbase, Inc
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 #include "vbucket_test.h"
21 #include "bgfetcher.h"
23 #include "failover-table.h"
25 #include "programs/engine_testapp/mock_server.h"
26 #include "tests/module_tests/test_helpers.h"
28 #include <platform/cb_malloc.h>
30 void VBucketTest::SetUp() {
31 const auto eviction_policy = GetParam();
32 vbucket.reset(new EPVBucket(0,
41 std::make_shared<DummyCB>(),
42 /*newSeqnoCb*/ nullptr,
47 void VBucketTest::TearDown() {
51 std::vector<StoredDocKey> VBucketTest::generateKeys(int num, int start) {
52 std::vector<StoredDocKey> rv;
54 for (int i = start; i < num + start; i++) {
55 rv.push_back(makeStoredDocKey(std::to_string(i)));
61 AddStatus VBucketTest::addOne(const StoredDocKey& k, int expiry) {
62 Item i(k, 0, expiry, k.data(), k.size());
63 return public_processAdd(i);
66 void VBucketTest::addMany(std::vector<StoredDocKey>& keys, AddStatus expect) {
67 for (const auto& k : keys) {
68 EXPECT_EQ(expect, addOne(k));
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());
77 void VBucketTest::setMany(std::vector<StoredDocKey>& keys,
78 MutationStatus expect) {
79 for (const auto& k : keys) {
80 EXPECT_EQ(expect, setOne(k));
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);
88 EXPECT_EQ(expect, public_processSoftDelete(v->getKey(), v, 0))
89 << "Failed to soft delete key " << k.c_str();
92 void VBucketTest::softDeleteMany(std::vector<StoredDocKey>& keys,
93 MutationStatus expect) {
94 for (const auto& k : keys) {
95 softDeleteOne(k, expect);
99 StoredValue* VBucketTest::findValue(StoredDocKey& key) {
100 return vbucket->ht.find(key, TrackReference::Yes, WantsDeleted::Yes);
103 void VBucketTest::verifyValue(StoredDocKey& key,
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();
111 EXPECT_EQ(nullptr, val.get());
113 EXPECT_STREQ(value, val->to_s().c_str());
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);
125 MutationStatus VBucketTest::public_processSet(Item& itm, const uint64_t cas) {
126 auto hbl_sv = lockAndFind(itm.getKey());
127 VBQueueItemCtx queueItmCtx(GenerateBySeqno::Yes,
130 /*isBackfillItem*/ false,
131 /*preLinkDocumentContext_*/ nullptr);
133 ->processSet(hbl_sv.first,
143 AddStatus VBucketTest::public_processAdd(Item& itm) {
144 auto hbl_sv = lockAndFind(itm.getKey());
146 ->processAdd(hbl_sv.first,
149 /*maybeKeyExists*/ true,
150 /*isReplication*/ false)
154 MutationStatus VBucketTest::public_processSoftDelete(const DocKey& key,
157 auto hbl = vbucket->ht.getLockedBucket(key);
159 v = vbucket->ht.unlocked_find(
160 key, hbl.getBucketNum(), WantsDeleted::No, TrackReference::No);
162 return MutationStatus::NotFound;
165 ItemMetaData metadata;
166 metadata.revSeqno = v->getRevSeqno() + 1;
167 MutationStatus status;
168 std::tie(status, std::ignore, std::ignore) = vbucket->processSoftDelete(
173 VBQueueItemCtx(GenerateBySeqno::Yes,
176 /*isBackfillItem*/ false,
177 /*preLinkDocCtx*/ nullptr),
179 /*bySeqno*/ v->getBySeqno());
183 bool VBucketTest::public_deleteStoredValue(const DocKey& key) {
184 auto hbl_sv = lockAndFind(key);
185 if (!hbl_sv.second) {
188 return vbucket->deleteStoredValue(hbl_sv.first, *hbl_sv.second);
191 GetValue VBucketTest::public_getAndUpdateTtl(const DocKey& key,
193 auto hbl = lockAndFind(key);
195 MutationStatus status;
196 std::tie(status, gv) = vbucket->processGetAndUpdateTtl(
197 hbl.first, key, hbl.second, exptime);
201 size_t EPVBucketTest::public_queueBGFetchItem(
203 std::unique_ptr<VBucketBGFetchItem> fetchItem,
204 BgFetcher* bgFetcher) {
205 return dynamic_cast<EPVBucket&>(*vbucket).queueBGFetchItem(
206 key, std::move(fetchItem), bgFetcher);
209 class BlobTest : public Blob {
211 BlobTest() : Blob(0,0) {}
212 static size_t getAllocationSize(size_t len){
213 return Blob::getAllocationSize(len);
217 TEST(BlobTest, basicAllocationSize){
218 EXPECT_EQ(BlobTest::getAllocationSize(10), 20);
220 // Expected to be 10 because the 2 bytes of the data member array will not
221 // be allocated because they will not be used.
222 EXPECT_EQ(BlobTest::getAllocationSize(0), 10);
225 // Measure performance of VBucket::getBGFetchItems - queue and then get
226 // 10,000 items from the vbucket.
227 TEST_P(EPVBucketTest, GetBGFetchItemsPerformance) {
228 BgFetcher fetcher(/*store*/ nullptr, /*shard*/ nullptr, this->global_stats);
230 for (unsigned int ii = 0; ii < 100000; ii++) {
231 auto fetchItem = std::make_unique<VBucketBGFetchItem>(
234 this->public_queueBGFetchItem(
235 makeStoredDocKey(std::to_string(ii)),
236 std::move(fetchItem),
239 auto items = this->vbucket->getBGFetchItems();
242 // Check the existence of bloom filter after performing a
243 // swap of existing filter with a temporary filter.
244 TEST_P(VBucketTest, SwapFilter) {
245 this->vbucket->createFilter(1, 1.0);
246 ASSERT_FALSE(this->vbucket->isTempFilterAvailable());
247 ASSERT_NE("DOESN'T EXIST", this->vbucket->getFilterStatusString());
248 this->vbucket->swapFilter();
249 EXPECT_NE("DOESN'T EXIST", this->vbucket->getFilterStatusString());
252 TEST_P(VBucketTest, Add) {
253 const auto eviction_policy = GetParam();
254 if (eviction_policy != VALUE_ONLY) {
257 const int nkeys = 1000;
259 auto keys = generateKeys(nkeys);
260 addMany(keys, AddStatus::Success);
262 StoredDocKey missingKey = makeStoredDocKey("aMissingKey");
263 EXPECT_FALSE(this->vbucket->ht.find(
264 missingKey, TrackReference::Yes, WantsDeleted::No));
266 for (const auto& key : keys) {
267 EXPECT_TRUE(this->vbucket->ht.find(
268 key, TrackReference::Yes, WantsDeleted::No));
271 addMany(keys, AddStatus::Exists);
272 for (const auto& key : keys) {
273 EXPECT_TRUE(this->vbucket->ht.find(
274 key, TrackReference::Yes, WantsDeleted::No));
277 // Verify we can read after a soft deletion.
278 EXPECT_EQ(MutationStatus::WasDirty,
279 this->public_processSoftDelete(keys[0], nullptr, 0));
280 EXPECT_EQ(MutationStatus::NotFound,
281 this->public_processSoftDelete(keys[0], nullptr, 0));
282 EXPECT_FALSE(this->vbucket->ht.find(
283 keys[0], TrackReference::Yes, WantsDeleted::No));
285 Item i(keys[0], 0, 0, "newtest", 7);
286 EXPECT_EQ(AddStatus::UnDel, this->public_processAdd(i));
287 EXPECT_EQ(nkeys, this->vbucket->ht.getNumItems());
290 TEST_P(VBucketTest, AddExpiry) {
291 const auto eviction_policy = GetParam();
292 if (eviction_policy != VALUE_ONLY) {
295 StoredDocKey k = makeStoredDocKey("aKey");
297 ASSERT_EQ(AddStatus::Success, addOne(k, ep_real_time() + 5));
298 EXPECT_EQ(AddStatus::Exists, addOne(k, ep_real_time() + 5));
301 this->vbucket->ht.find(k, TrackReference::Yes, WantsDeleted::No);
303 EXPECT_FALSE(v->isExpired(ep_real_time()));
304 EXPECT_TRUE(v->isExpired(ep_real_time() + 6));
306 TimeTraveller biffTannen(6);
307 EXPECT_TRUE(v->isExpired(ep_real_time()));
309 EXPECT_EQ(AddStatus::UnDel, addOne(k, ep_real_time() + 5));
311 EXPECT_FALSE(v->isExpired(ep_real_time()));
312 EXPECT_TRUE(v->isExpired(ep_real_time() + 6));
316 * Test to check if an unlocked_softDelete performed on an
317 * existing item with a new value results in a success
319 TEST_P(VBucketTest, unlockedSoftDeleteWithValue) {
320 const auto eviction_policy = GetParam();
321 if (eviction_policy != VALUE_ONLY) {
325 // Setup - create a key and then delete it with a value.
326 StoredDocKey key = makeStoredDocKey("key");
327 Item stored_item(key, 0, 0, "value", strlen("value"));
328 ASSERT_EQ(MutationStatus::WasClean,
329 this->public_processSet(stored_item, stored_item.getCas()));
332 this->vbucket->ht.find(key, TrackReference::No, WantsDeleted::No));
333 EXPECT_NE(nullptr, v);
335 // Create an item and set its state to deleted
336 Item deleted_item(key, 0, 0, "deletedvalue", strlen("deletedvalue"));
337 deleted_item.setDeleted();
339 auto prev_revseqno = v->getRevSeqno();
340 deleted_item.setRevSeqno(prev_revseqno);
342 EXPECT_EQ(MutationStatus::WasDirty,
343 this->public_processSet(deleted_item, 0));
344 verifyValue(key, "deletedvalue", TrackReference::Yes, WantsDeleted::Yes);
345 EXPECT_EQ(prev_revseqno + 1, v->getRevSeqno());
349 * Test to check that if an item has expired, an incoming mutation
350 * on that item, if in deleted state results in an invalid cas and
351 * if not in deleted state, results in not found
353 TEST_P(VBucketTest, updateExpiredItem) {
354 // Setup - create a key
355 StoredDocKey key = makeStoredDocKey("key");
356 Item stored_item(key, 0, ep_real_time() - 1, "value", strlen("value"));
357 ASSERT_EQ(MutationStatus::WasClean,
358 this->public_processSet(stored_item, stored_item.getCas()));
360 StoredValue* v = this->vbucket->ht.find(key, TrackReference::No, WantsDeleted::No);
362 EXPECT_TRUE(v->isExpired(ep_real_time()));
364 auto cas = v->getCas();
365 // Create an item and set its state to deleted.
366 Item deleted_item(key, 0, 0, "deletedvalue", strlen("deletedvalue"));
368 EXPECT_EQ(MutationStatus::NotFound,
369 this->public_processSet(deleted_item, cas + 1));
371 deleted_item.setDeleted();
372 EXPECT_EQ(MutationStatus::InvalidCas,
373 this->public_processSet(deleted_item, cas + 1));
377 * Test to check if an unlocked_softDelete performed on a
378 * deleted item without a value and with a value
380 TEST_P(VBucketTest, updateDeletedItem) {
381 const auto eviction_policy = GetParam();
382 if (eviction_policy != VALUE_ONLY) {
386 // Setup - create a key and then delete it.
387 StoredDocKey key = makeStoredDocKey("key");
388 Item stored_item(key, 0, 0, "value", strlen("value"));
389 ASSERT_EQ(MutationStatus::WasClean,
390 this->public_processSet(stored_item, stored_item.getCas()));
393 this->vbucket->ht.find(key, TrackReference::No, WantsDeleted::No));
394 EXPECT_NE(nullptr, v);
396 ItemMetaData itm_meta;
397 EXPECT_EQ(MutationStatus::WasDirty,
398 this->public_processSoftDelete(v->getKey(), v, 0));
399 verifyValue(key, nullptr, TrackReference::Yes, WantsDeleted::Yes);
400 EXPECT_EQ(1, this->vbucket->getNumItems());
401 EXPECT_EQ(1, this->vbucket->getNumInMemoryDeletes());
403 Item deleted_item(key, 0, 0, "deletedvalue", strlen("deletedvalue"));
404 deleted_item.setDeleted();
406 auto prev_revseqno = v->getRevSeqno();
407 deleted_item.setRevSeqno(prev_revseqno);
409 EXPECT_EQ(MutationStatus::WasDirty,
410 this->public_processSet(deleted_item, 0));
416 EXPECT_EQ(1, this->vbucket->getNumItems());
417 EXPECT_EQ(1, this->vbucket->getNumInMemoryDeletes());
418 EXPECT_EQ(prev_revseqno + 1, v->getRevSeqno());
420 Item update_deleted_item(
421 key, 0, 0, "updatedeletedvalue", strlen("updatedeletedvalue"));
422 update_deleted_item.setDeleted();
424 prev_revseqno = v->getRevSeqno();
425 update_deleted_item.setRevSeqno(prev_revseqno);
427 EXPECT_EQ(MutationStatus::WasDirty,
428 this->public_processSet(update_deleted_item, 0));
430 key, "updatedeletedvalue", TrackReference::Yes, WantsDeleted::Yes);
431 EXPECT_EQ(1, this->vbucket->getNumItems());
432 EXPECT_EQ(1, this->vbucket->getNumInMemoryDeletes());
433 EXPECT_EQ(prev_revseqno + 1, v->getRevSeqno());
436 TEST_P(VBucketTest, SizeStatsSoftDel) {
437 this->global_stats.reset();
438 ASSERT_EQ(0, this->vbucket->ht.memSize.load());
439 ASSERT_EQ(0, this->vbucket->ht.cacheSize.load());
440 size_t initialSize = this->global_stats.currentSize.load();
442 const StoredDocKey k = makeStoredDocKey("somekey");
443 const size_t itemSize(16 * 1024);
444 char* someval(static_cast<char*>(cb_calloc(1, itemSize)));
445 EXPECT_TRUE(someval);
447 Item i(k, 0, 0, someval, itemSize);
449 EXPECT_EQ(MutationStatus::WasClean,
450 this->public_processSet(i, i.getCas()));
452 EXPECT_EQ(MutationStatus::WasDirty,
453 this->public_processSoftDelete(k, nullptr, 0));
454 this->public_deleteStoredValue(k);
456 EXPECT_EQ(0, this->vbucket->ht.memSize.load());
457 EXPECT_EQ(0, this->vbucket->ht.cacheSize.load());
458 EXPECT_EQ(initialSize, this->global_stats.currentSize.load());
463 TEST_P(VBucketTest, SizeStatsSoftDelFlush) {
464 this->global_stats.reset();
465 ASSERT_EQ(0, this->vbucket->ht.memSize.load());
466 ASSERT_EQ(0, this->vbucket->ht.cacheSize.load());
467 size_t initialSize = this->global_stats.currentSize.load();
469 StoredDocKey k = makeStoredDocKey("somekey");
470 const size_t itemSize(16 * 1024);
471 char* someval(static_cast<char*>(cb_calloc(1, itemSize)));
472 EXPECT_TRUE(someval);
474 Item i(k, 0, 0, someval, itemSize);
476 EXPECT_EQ(MutationStatus::WasClean,
477 this->public_processSet(i, i.getCas()));
479 EXPECT_EQ(MutationStatus::WasDirty,
480 this->public_processSoftDelete(k, nullptr, 0));
481 this->vbucket->ht.clear();
483 EXPECT_EQ(0, this->vbucket->ht.memSize.load());
484 EXPECT_EQ(0, this->vbucket->ht.cacheSize.load());
485 EXPECT_EQ(initialSize, this->global_stats.currentSize.load());
490 class VBucketEvictionTest : public VBucketTest {};
492 // Check that counts of items and resident items are as expected when items are
493 // ejected from the HashTable.
494 TEST_P(VBucketEvictionTest, EjectionResidentCount) {
495 const auto eviction_policy = GetParam();
496 ASSERT_EQ(0, this->vbucket->getNumItems());
497 ASSERT_EQ(0, this->vbucket->getNumNonResidentItems());
499 Item item(makeStoredDocKey("key"), /*flags*/0, /*exp*/0,
500 /*data*/nullptr, /*ndata*/0);
502 EXPECT_EQ(MutationStatus::WasClean,
503 this->public_processSet(item, item.getCas()));
505 EXPECT_EQ(1, this->vbucket->getNumItems());
506 EXPECT_EQ(0, this->vbucket->getNumNonResidentItems());
508 // TODO-MT: Should acquire lock really (ok given this is currently
510 auto* stored_item = this->vbucket->ht.find(
511 makeStoredDocKey("key"), TrackReference::Yes, WantsDeleted::No);
512 EXPECT_NE(nullptr, stored_item);
513 // Need to clear the dirty flag to allow it to be ejected.
514 stored_item->markClean();
515 EXPECT_TRUE(this->vbucket->ht.unlocked_ejectItem(stored_item,
518 // After ejection, should still have 1 item in VBucket, but also have
519 // 1 non-resident item.
520 EXPECT_EQ(1, this->vbucket->getNumItems());
521 EXPECT_EQ(1, this->vbucket->getNumNonResidentItems());
524 // Regression test for MB-21448 - if an attempt is made to perform a CAS
525 // operation on a logically deleted item we should return NOT_FOUND
526 // (aka KEY_ENOENT) and *not* INVALID_CAS (aka KEY_EEXISTS).
527 TEST_P(VBucketEvictionTest, MB21448_UnlockedSetWithCASDeleted) {
528 // Setup - create a key and then delete it.
529 StoredDocKey key = makeStoredDocKey("key");
530 Item item(key, 0, 0, "deleted", strlen("deleted"));
531 ASSERT_EQ(MutationStatus::WasClean,
532 this->public_processSet(item, item.getCas()));
533 ASSERT_EQ(MutationStatus::WasDirty,
534 this->public_processSoftDelete(key, nullptr, 0));
536 // Attempt to perform a set on a deleted key with a CAS.
537 Item replacement(key, 0, 0, "value", strlen("value"));
538 EXPECT_EQ(MutationStatus::NotFound,
539 this->public_processSet(replacement,
541 << "When trying to replace-with-CAS a deleted item";
544 // Test cases which run in both Full and Value eviction
545 INSTANTIATE_TEST_CASE_P(
546 FullAndValueEviction,
548 ::testing::Values(VALUE_ONLY, FULL_EVICTION),
549 [](const ::testing::TestParamInfo<item_eviction_policy_t>& info) {
550 if (info.param == VALUE_ONLY) {
553 return "FULL_EVICTION";
557 INSTANTIATE_TEST_CASE_P(
558 FullAndValueEviction,
560 ::testing::Values(VALUE_ONLY, FULL_EVICTION),
561 [](const ::testing::TestParamInfo<item_eviction_policy_t>& info) {
562 if (info.param == VALUE_ONLY) {
565 return "FULL_EVICTION";
569 INSTANTIATE_TEST_CASE_P(
570 FullAndValueEviction,
572 ::testing::Values(VALUE_ONLY, FULL_EVICTION),
573 [](const ::testing::TestParamInfo<item_eviction_policy_t>& info) {
574 if (info.param == VALUE_ONLY) {
577 return "FULL_EVICTION";