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 size_t EPVBucketTest::public_queueBGFetchItem(
193 std::unique_ptr<VBucketBGFetchItem> fetchItem,
194 BgFetcher* bgFetcher) {
195 return dynamic_cast<EPVBucket&>(*vbucket).queueBGFetchItem(
196 key, std::move(fetchItem), bgFetcher);
199 class BlobTest : public Blob {
201 BlobTest() : Blob(0,0) {}
202 static size_t getAllocationSize(size_t len){
203 return Blob::getAllocationSize(len);
207 TEST(BlobTest, basicAllocationSize){
208 EXPECT_EQ(BlobTest::getAllocationSize(10), 20);
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);
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);
220 for (unsigned int ii = 0; ii < 100000; ii++) {
221 auto fetchItem = std::make_unique<VBucketBGFetchItem>(
224 this->public_queueBGFetchItem(
225 makeStoredDocKey(std::to_string(ii)),
226 std::move(fetchItem),
229 auto items = this->vbucket->getBGFetchItems();
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());
242 TEST_P(VBucketTest, Add) {
243 const auto eviction_policy = GetParam();
244 if (eviction_policy != VALUE_ONLY) {
247 const int nkeys = 1000;
249 auto keys = generateKeys(nkeys);
250 addMany(keys, AddStatus::Success);
252 StoredDocKey missingKey = makeStoredDocKey("aMissingKey");
253 EXPECT_FALSE(this->vbucket->ht.find(
254 missingKey, TrackReference::Yes, WantsDeleted::No));
256 for (const auto& key : keys) {
257 EXPECT_TRUE(this->vbucket->ht.find(
258 key, TrackReference::Yes, WantsDeleted::No));
261 addMany(keys, AddStatus::Exists);
262 for (const auto& key : keys) {
263 EXPECT_TRUE(this->vbucket->ht.find(
264 key, TrackReference::Yes, WantsDeleted::No));
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));
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());
280 TEST_P(VBucketTest, AddExpiry) {
281 const auto eviction_policy = GetParam();
282 if (eviction_policy != VALUE_ONLY) {
285 StoredDocKey k = makeStoredDocKey("aKey");
287 ASSERT_EQ(AddStatus::Success, addOne(k, ep_real_time() + 5));
288 EXPECT_EQ(AddStatus::Exists, addOne(k, ep_real_time() + 5));
291 this->vbucket->ht.find(k, TrackReference::Yes, WantsDeleted::No);
293 EXPECT_FALSE(v->isExpired(ep_real_time()));
294 EXPECT_TRUE(v->isExpired(ep_real_time() + 6));
296 TimeTraveller biffTannen(6);
297 EXPECT_TRUE(v->isExpired(ep_real_time()));
299 EXPECT_EQ(AddStatus::UnDel, addOne(k, ep_real_time() + 5));
301 EXPECT_FALSE(v->isExpired(ep_real_time()));
302 EXPECT_TRUE(v->isExpired(ep_real_time() + 6));
306 * Test to check if an unlocked_softDelete performed on an
307 * existing item with a new value results in a success
309 TEST_P(VBucketTest, unlockedSoftDeleteWithValue) {
310 const auto eviction_policy = GetParam();
311 if (eviction_policy != VALUE_ONLY) {
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()));
322 this->vbucket->ht.find(key, TrackReference::No, WantsDeleted::No));
323 EXPECT_NE(nullptr, v);
325 // Create an item and set its state to deleted
326 Item deleted_item(key, 0, 0, "deletedvalue", strlen("deletedvalue"));
327 deleted_item.setDeleted();
329 auto prev_revseqno = v->getRevSeqno();
330 deleted_item.setRevSeqno(prev_revseqno);
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());
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
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()));
350 StoredValue* v = this->vbucket->ht.find(key, TrackReference::No, WantsDeleted::No);
352 EXPECT_TRUE(v->isExpired(ep_real_time()));
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"));
358 EXPECT_EQ(MutationStatus::NotFound,
359 this->public_processSet(deleted_item, cas + 1));
361 deleted_item.setDeleted();
362 EXPECT_EQ(MutationStatus::InvalidCas,
363 this->public_processSet(deleted_item, cas + 1));
367 * Test to check if an unlocked_softDelete performed on a
368 * deleted item without a value and with a value
370 TEST_P(VBucketTest, updateDeletedItem) {
371 const auto eviction_policy = GetParam();
372 if (eviction_policy != VALUE_ONLY) {
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()));
383 this->vbucket->ht.find(key, TrackReference::No, WantsDeleted::No));
384 EXPECT_NE(nullptr, v);
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());
393 Item deleted_item(key, 0, 0, "deletedvalue", strlen("deletedvalue"));
394 deleted_item.setDeleted();
396 auto prev_revseqno = v->getRevSeqno();
397 deleted_item.setRevSeqno(prev_revseqno);
399 EXPECT_EQ(MutationStatus::WasDirty,
400 this->public_processSet(deleted_item, 0));
406 EXPECT_EQ(1, this->vbucket->getNumItems());
407 EXPECT_EQ(1, this->vbucket->getNumInMemoryDeletes());
408 EXPECT_EQ(prev_revseqno + 1, v->getRevSeqno());
410 Item update_deleted_item(
411 key, 0, 0, "updatedeletedvalue", strlen("updatedeletedvalue"));
412 update_deleted_item.setDeleted();
414 prev_revseqno = v->getRevSeqno();
415 update_deleted_item.setRevSeqno(prev_revseqno);
417 EXPECT_EQ(MutationStatus::WasDirty,
418 this->public_processSet(update_deleted_item, 0));
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());
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();
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);
437 Item i(k, 0, 0, someval, itemSize);
439 EXPECT_EQ(MutationStatus::WasClean,
440 this->public_processSet(i, i.getCas()));
442 EXPECT_EQ(MutationStatus::WasDirty,
443 this->public_processSoftDelete(k, nullptr, 0));
444 this->public_deleteStoredValue(k);
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());
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();
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);
464 Item i(k, 0, 0, someval, itemSize);
466 EXPECT_EQ(MutationStatus::WasClean,
467 this->public_processSet(i, i.getCas()));
469 EXPECT_EQ(MutationStatus::WasDirty,
470 this->public_processSoftDelete(k, nullptr, 0));
471 this->vbucket->ht.clear();
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());
480 class VBucketEvictionTest : public VBucketTest {};
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());
489 Item item(makeStoredDocKey("key"), /*flags*/0, /*exp*/0,
490 /*data*/nullptr, /*ndata*/0);
492 EXPECT_EQ(MutationStatus::WasClean,
493 this->public_processSet(item, item.getCas()));
495 EXPECT_EQ(1, this->vbucket->getNumItems());
496 EXPECT_EQ(0, this->vbucket->getNumNonResidentItems());
498 // TODO-MT: Should acquire lock really (ok given this is currently
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,
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());
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));
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,
531 << "When trying to replace-with-CAS a deleted item";
534 // Test cases which run in both Full and Value eviction
535 INSTANTIATE_TEST_CASE_P(
536 FullAndValueEviction,
538 ::testing::Values(VALUE_ONLY, FULL_EVICTION),
539 [](const ::testing::TestParamInfo<item_eviction_policy_t>& info) {
540 if (info.param == VALUE_ONLY) {
543 return "FULL_EVICTION";
547 INSTANTIATE_TEST_CASE_P(
548 FullAndValueEviction,
550 ::testing::Values(VALUE_ONLY, FULL_EVICTION),
551 [](const ::testing::TestParamInfo<item_eviction_policy_t>& info) {
552 if (info.param == VALUE_ONLY) {
555 return "FULL_EVICTION";
559 INSTANTIATE_TEST_CASE_P(
560 FullAndValueEviction,
562 ::testing::Values(VALUE_ONLY, FULL_EVICTION),
563 [](const ::testing::TestParamInfo<item_eviction_policy_t>& info) {
564 if (info.param == VALUE_ONLY) {
567 return "FULL_EVICTION";