skiplist_test.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  7. // Use of this source code is governed by a BSD-style license that can be
  8. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  9. #include "memtable/skiplist.h"
  10. #include <set>
  11. #include "memory/arena.h"
  12. #include "rocksdb/env.h"
  13. #include "test_util/testharness.h"
  14. #include "util/hash.h"
  15. #include "util/random.h"
  16. namespace ROCKSDB_NAMESPACE {
  17. typedef uint64_t Key;
  18. struct TestComparator {
  19. int operator()(const Key& a, const Key& b) const {
  20. if (a < b) {
  21. return -1;
  22. } else if (a > b) {
  23. return +1;
  24. } else {
  25. return 0;
  26. }
  27. }
  28. };
  29. class SkipTest : public testing::Test {};
  30. TEST_F(SkipTest, Empty) {
  31. Arena arena;
  32. TestComparator cmp;
  33. SkipList<Key, TestComparator> list(cmp, &arena);
  34. ASSERT_TRUE(!list.Contains(10));
  35. SkipList<Key, TestComparator>::Iterator iter(&list);
  36. ASSERT_TRUE(!iter.Valid());
  37. iter.SeekToFirst();
  38. ASSERT_TRUE(!iter.Valid());
  39. iter.Seek(100);
  40. ASSERT_TRUE(!iter.Valid());
  41. iter.SeekForPrev(100);
  42. ASSERT_TRUE(!iter.Valid());
  43. iter.SeekToLast();
  44. ASSERT_TRUE(!iter.Valid());
  45. }
  46. TEST_F(SkipTest, InsertAndLookup) {
  47. const int N = 2000;
  48. const int R = 5000;
  49. Random rnd(1000);
  50. std::set<Key> keys;
  51. Arena arena;
  52. TestComparator cmp;
  53. SkipList<Key, TestComparator> list(cmp, &arena);
  54. for (int i = 0; i < N; i++) {
  55. Key key = rnd.Next() % R;
  56. if (keys.insert(key).second) {
  57. list.Insert(key);
  58. }
  59. }
  60. for (int i = 0; i < R; i++) {
  61. if (list.Contains(i)) {
  62. ASSERT_EQ(keys.count(i), 1U);
  63. } else {
  64. ASSERT_EQ(keys.count(i), 0U);
  65. }
  66. }
  67. // Simple iterator tests
  68. {
  69. SkipList<Key, TestComparator>::Iterator iter(&list);
  70. ASSERT_TRUE(!iter.Valid());
  71. iter.Seek(0);
  72. ASSERT_TRUE(iter.Valid());
  73. ASSERT_EQ(*(keys.begin()), iter.key());
  74. iter.SeekForPrev(R - 1);
  75. ASSERT_TRUE(iter.Valid());
  76. ASSERT_EQ(*(keys.rbegin()), iter.key());
  77. iter.SeekToFirst();
  78. ASSERT_TRUE(iter.Valid());
  79. ASSERT_EQ(*(keys.begin()), iter.key());
  80. iter.SeekToLast();
  81. ASSERT_TRUE(iter.Valid());
  82. ASSERT_EQ(*(keys.rbegin()), iter.key());
  83. }
  84. // Forward iteration test
  85. for (int i = 0; i < R; i++) {
  86. SkipList<Key, TestComparator>::Iterator iter(&list);
  87. iter.Seek(i);
  88. // Compare against model iterator
  89. std::set<Key>::iterator model_iter = keys.lower_bound(i);
  90. for (int j = 0; j < 3; j++) {
  91. if (model_iter == keys.end()) {
  92. ASSERT_TRUE(!iter.Valid());
  93. break;
  94. } else {
  95. ASSERT_TRUE(iter.Valid());
  96. ASSERT_EQ(*model_iter, iter.key());
  97. ++model_iter;
  98. iter.Next();
  99. }
  100. }
  101. }
  102. // Backward iteration test
  103. for (int i = 0; i < R; i++) {
  104. SkipList<Key, TestComparator>::Iterator iter(&list);
  105. iter.SeekForPrev(i);
  106. // Compare against model iterator
  107. std::set<Key>::iterator model_iter = keys.upper_bound(i);
  108. for (int j = 0; j < 3; j++) {
  109. if (model_iter == keys.begin()) {
  110. ASSERT_TRUE(!iter.Valid());
  111. break;
  112. } else {
  113. ASSERT_TRUE(iter.Valid());
  114. ASSERT_EQ(*--model_iter, iter.key());
  115. iter.Prev();
  116. }
  117. }
  118. }
  119. }
  120. // We want to make sure that with a single writer and multiple
  121. // concurrent readers (with no synchronization other than when a
  122. // reader's iterator is created), the reader always observes all the
  123. // data that was present in the skip list when the iterator was
  124. // constructor. Because insertions are happening concurrently, we may
  125. // also observe new values that were inserted since the iterator was
  126. // constructed, but we should never miss any values that were present
  127. // at iterator construction time.
  128. //
  129. // We generate multi-part keys:
  130. // <key,gen,hash>
  131. // where:
  132. // key is in range [0..K-1]
  133. // gen is a generation number for key
  134. // hash is hash(key,gen)
  135. //
  136. // The insertion code picks a random key, sets gen to be 1 + the last
  137. // generation number inserted for that key, and sets hash to Hash(key,gen).
  138. //
  139. // At the beginning of a read, we snapshot the last inserted
  140. // generation number for each key. We then iterate, including random
  141. // calls to Next() and Seek(). For every key we encounter, we
  142. // check that it is either expected given the initial snapshot or has
  143. // been concurrently added since the iterator started.
  144. class ConcurrentTest {
  145. private:
  146. static const uint32_t K = 4;
  147. static uint64_t key(Key key) { return (key >> 40); }
  148. static uint64_t gen(Key key) { return (key >> 8) & 0xffffffffu; }
  149. static uint64_t hash(Key key) { return key & 0xff; }
  150. static uint64_t HashNumbers(uint64_t k, uint64_t g) {
  151. uint64_t data[2] = { k, g };
  152. return Hash(reinterpret_cast<char*>(data), sizeof(data), 0);
  153. }
  154. static Key MakeKey(uint64_t k, uint64_t g) {
  155. assert(sizeof(Key) == sizeof(uint64_t));
  156. assert(k <= K); // We sometimes pass K to seek to the end of the skiplist
  157. assert(g <= 0xffffffffu);
  158. return ((k << 40) | (g << 8) | (HashNumbers(k, g) & 0xff));
  159. }
  160. static bool IsValidKey(Key k) {
  161. return hash(k) == (HashNumbers(key(k), gen(k)) & 0xff);
  162. }
  163. static Key RandomTarget(Random* rnd) {
  164. switch (rnd->Next() % 10) {
  165. case 0:
  166. // Seek to beginning
  167. return MakeKey(0, 0);
  168. case 1:
  169. // Seek to end
  170. return MakeKey(K, 0);
  171. default:
  172. // Seek to middle
  173. return MakeKey(rnd->Next() % K, 0);
  174. }
  175. }
  176. // Per-key generation
  177. struct State {
  178. std::atomic<int> generation[K];
  179. void Set(int k, int v) {
  180. generation[k].store(v, std::memory_order_release);
  181. }
  182. int Get(int k) { return generation[k].load(std::memory_order_acquire); }
  183. State() {
  184. for (unsigned int k = 0; k < K; k++) {
  185. Set(k, 0);
  186. }
  187. }
  188. };
  189. // Current state of the test
  190. State current_;
  191. Arena arena_;
  192. // SkipList is not protected by mu_. We just use a single writer
  193. // thread to modify it.
  194. SkipList<Key, TestComparator> list_;
  195. public:
  196. ConcurrentTest() : list_(TestComparator(), &arena_) {}
  197. // REQUIRES: External synchronization
  198. void WriteStep(Random* rnd) {
  199. const uint32_t k = rnd->Next() % K;
  200. const int g = current_.Get(k) + 1;
  201. const Key new_key = MakeKey(k, g);
  202. list_.Insert(new_key);
  203. current_.Set(k, g);
  204. }
  205. void ReadStep(Random* rnd) {
  206. // Remember the initial committed state of the skiplist.
  207. State initial_state;
  208. for (unsigned int k = 0; k < K; k++) {
  209. initial_state.Set(k, current_.Get(k));
  210. }
  211. Key pos = RandomTarget(rnd);
  212. SkipList<Key, TestComparator>::Iterator iter(&list_);
  213. iter.Seek(pos);
  214. while (true) {
  215. Key current;
  216. if (!iter.Valid()) {
  217. current = MakeKey(K, 0);
  218. } else {
  219. current = iter.key();
  220. ASSERT_TRUE(IsValidKey(current)) << current;
  221. }
  222. ASSERT_LE(pos, current) << "should not go backwards";
  223. // Verify that everything in [pos,current) was not present in
  224. // initial_state.
  225. while (pos < current) {
  226. ASSERT_LT(key(pos), K) << pos;
  227. // Note that generation 0 is never inserted, so it is ok if
  228. // <*,0,*> is missing.
  229. ASSERT_TRUE((gen(pos) == 0U) ||
  230. (gen(pos) > static_cast<uint64_t>(initial_state.Get(
  231. static_cast<int>(key(pos))))))
  232. << "key: " << key(pos) << "; gen: " << gen(pos)
  233. << "; initgen: " << initial_state.Get(static_cast<int>(key(pos)));
  234. // Advance to next key in the valid key space
  235. if (key(pos) < key(current)) {
  236. pos = MakeKey(key(pos) + 1, 0);
  237. } else {
  238. pos = MakeKey(key(pos), gen(pos) + 1);
  239. }
  240. }
  241. if (!iter.Valid()) {
  242. break;
  243. }
  244. if (rnd->Next() % 2) {
  245. iter.Next();
  246. pos = MakeKey(key(pos), gen(pos) + 1);
  247. } else {
  248. Key new_target = RandomTarget(rnd);
  249. if (new_target > pos) {
  250. pos = new_target;
  251. iter.Seek(new_target);
  252. }
  253. }
  254. }
  255. }
  256. };
  257. const uint32_t ConcurrentTest::K;
  258. // Simple test that does single-threaded testing of the ConcurrentTest
  259. // scaffolding.
  260. TEST_F(SkipTest, ConcurrentWithoutThreads) {
  261. ConcurrentTest test;
  262. Random rnd(test::RandomSeed());
  263. for (int i = 0; i < 10000; i++) {
  264. test.ReadStep(&rnd);
  265. test.WriteStep(&rnd);
  266. }
  267. }
  268. class TestState {
  269. public:
  270. ConcurrentTest t_;
  271. int seed_;
  272. std::atomic<bool> quit_flag_;
  273. enum ReaderState {
  274. STARTING,
  275. RUNNING,
  276. DONE
  277. };
  278. explicit TestState(int s)
  279. : seed_(s), quit_flag_(false), state_(STARTING), state_cv_(&mu_) {}
  280. void Wait(ReaderState s) {
  281. mu_.Lock();
  282. while (state_ != s) {
  283. state_cv_.Wait();
  284. }
  285. mu_.Unlock();
  286. }
  287. void Change(ReaderState s) {
  288. mu_.Lock();
  289. state_ = s;
  290. state_cv_.Signal();
  291. mu_.Unlock();
  292. }
  293. private:
  294. port::Mutex mu_;
  295. ReaderState state_;
  296. port::CondVar state_cv_;
  297. };
  298. static void ConcurrentReader(void* arg) {
  299. TestState* state = reinterpret_cast<TestState*>(arg);
  300. Random rnd(state->seed_);
  301. int64_t reads = 0;
  302. state->Change(TestState::RUNNING);
  303. while (!state->quit_flag_.load(std::memory_order_acquire)) {
  304. state->t_.ReadStep(&rnd);
  305. ++reads;
  306. }
  307. state->Change(TestState::DONE);
  308. }
  309. static void RunConcurrent(int run) {
  310. const int seed = test::RandomSeed() + (run * 100);
  311. Random rnd(seed);
  312. const int N = 1000;
  313. const int kSize = 1000;
  314. for (int i = 0; i < N; i++) {
  315. if ((i % 100) == 0) {
  316. fprintf(stderr, "Run %d of %d\n", i, N);
  317. }
  318. TestState state(seed + 1);
  319. Env::Default()->SetBackgroundThreads(1);
  320. Env::Default()->Schedule(ConcurrentReader, &state);
  321. state.Wait(TestState::RUNNING);
  322. for (int k = 0; k < kSize; k++) {
  323. state.t_.WriteStep(&rnd);
  324. }
  325. state.quit_flag_.store(true, std::memory_order_release);
  326. state.Wait(TestState::DONE);
  327. }
  328. }
  329. TEST_F(SkipTest, Concurrent1) { RunConcurrent(1); }
  330. TEST_F(SkipTest, Concurrent2) { RunConcurrent(2); }
  331. TEST_F(SkipTest, Concurrent3) { RunConcurrent(3); }
  332. TEST_F(SkipTest, Concurrent4) { RunConcurrent(4); }
  333. TEST_F(SkipTest, Concurrent5) { RunConcurrent(5); }
  334. } // namespace ROCKSDB_NAMESPACE
  335. int main(int argc, char** argv) {
  336. ::testing::InitGoogleTest(&argc, argv);
  337. return RUN_ALL_TESTS();
  338. }