lru_cache_test.cc 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732
  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. #include "cache/lru_cache.h"
  6. #include <memory>
  7. #include <string>
  8. #include <vector>
  9. #include "cache/cache_key.h"
  10. #include "cache/clock_cache.h"
  11. #include "cache_helpers.h"
  12. #include "db/db_test_util.h"
  13. #include "file/sst_file_manager_impl.h"
  14. #include "port/port.h"
  15. #include "port/stack_trace.h"
  16. #include "rocksdb/cache.h"
  17. #include "rocksdb/io_status.h"
  18. #include "rocksdb/sst_file_manager.h"
  19. #include "rocksdb/utilities/cache_dump_load.h"
  20. #include "test_util/secondary_cache_test_util.h"
  21. #include "test_util/testharness.h"
  22. #include "typed_cache.h"
  23. #include "util/coding.h"
  24. #include "util/random.h"
  25. #include "utilities/cache_dump_load_impl.h"
  26. #include "utilities/fault_injection_fs.h"
  27. namespace ROCKSDB_NAMESPACE {
  28. class LRUCacheTest : public testing::Test {
  29. public:
  30. LRUCacheTest() = default;
  31. ~LRUCacheTest() override { DeleteCache(); }
  32. void DeleteCache() {
  33. if (cache_ != nullptr) {
  34. cache_->~LRUCacheShard();
  35. port::cacheline_aligned_free(cache_);
  36. cache_ = nullptr;
  37. }
  38. }
  39. void NewCache(size_t capacity, double high_pri_pool_ratio = 0.0,
  40. double low_pri_pool_ratio = 1.0,
  41. bool use_adaptive_mutex = kDefaultToAdaptiveMutex) {
  42. DeleteCache();
  43. cache_ = static_cast<LRUCacheShard*>(
  44. port::cacheline_aligned_alloc(sizeof(LRUCacheShard)));
  45. new (cache_) LRUCacheShard(capacity, /*strict_capacity_limit=*/false,
  46. high_pri_pool_ratio, low_pri_pool_ratio,
  47. use_adaptive_mutex, kDontChargeCacheMetadata,
  48. /*max_upper_hash_bits=*/24,
  49. /*allocator*/ nullptr, &eviction_callback_);
  50. }
  51. void Insert(const std::string& key,
  52. Cache::Priority priority = Cache::Priority::LOW,
  53. size_t charge = 1) {
  54. EXPECT_OK(cache_->Insert(key, 0 /*hash*/, nullptr /*value*/,
  55. &kNoopCacheItemHelper, charge, nullptr /*handle*/,
  56. priority));
  57. }
  58. void Insert(char key, Cache::Priority priority = Cache::Priority::LOW) {
  59. Insert(std::string(1, key), priority);
  60. }
  61. bool Lookup(const std::string& key) {
  62. auto handle = cache_->Lookup(key, 0 /*hash*/, nullptr, nullptr,
  63. Cache::Priority::LOW, nullptr);
  64. if (handle) {
  65. cache_->Release(handle, true /*useful*/, false /*erase*/);
  66. return true;
  67. }
  68. return false;
  69. }
  70. bool Lookup(char key) { return Lookup(std::string(1, key)); }
  71. void Erase(const std::string& key) { cache_->Erase(key, 0 /*hash*/); }
  72. void ValidateLRUList(std::vector<std::string> keys,
  73. size_t num_high_pri_pool_keys = 0,
  74. size_t num_low_pri_pool_keys = 0,
  75. size_t num_bottom_pri_pool_keys = 0) {
  76. LRUHandle* lru;
  77. LRUHandle* lru_low_pri;
  78. LRUHandle* lru_bottom_pri;
  79. cache_->TEST_GetLRUList(&lru, &lru_low_pri, &lru_bottom_pri);
  80. LRUHandle* iter = lru;
  81. bool in_low_pri_pool = false;
  82. bool in_high_pri_pool = false;
  83. size_t high_pri_pool_keys = 0;
  84. size_t low_pri_pool_keys = 0;
  85. size_t bottom_pri_pool_keys = 0;
  86. if (iter == lru_bottom_pri) {
  87. in_low_pri_pool = true;
  88. in_high_pri_pool = false;
  89. }
  90. if (iter == lru_low_pri) {
  91. in_low_pri_pool = false;
  92. in_high_pri_pool = true;
  93. }
  94. for (const auto& key : keys) {
  95. iter = iter->next;
  96. ASSERT_NE(lru, iter);
  97. ASSERT_EQ(key, iter->key().ToString());
  98. ASSERT_EQ(in_high_pri_pool, iter->InHighPriPool());
  99. ASSERT_EQ(in_low_pri_pool, iter->InLowPriPool());
  100. if (in_high_pri_pool) {
  101. ASSERT_FALSE(iter->InLowPriPool());
  102. high_pri_pool_keys++;
  103. } else if (in_low_pri_pool) {
  104. ASSERT_FALSE(iter->InHighPriPool());
  105. low_pri_pool_keys++;
  106. } else {
  107. bottom_pri_pool_keys++;
  108. }
  109. if (iter == lru_bottom_pri) {
  110. ASSERT_FALSE(in_low_pri_pool);
  111. ASSERT_FALSE(in_high_pri_pool);
  112. in_low_pri_pool = true;
  113. in_high_pri_pool = false;
  114. }
  115. if (iter == lru_low_pri) {
  116. ASSERT_TRUE(in_low_pri_pool);
  117. ASSERT_FALSE(in_high_pri_pool);
  118. in_low_pri_pool = false;
  119. in_high_pri_pool = true;
  120. }
  121. }
  122. ASSERT_EQ(lru, iter->next);
  123. ASSERT_FALSE(in_low_pri_pool);
  124. ASSERT_TRUE(in_high_pri_pool);
  125. ASSERT_EQ(num_high_pri_pool_keys, high_pri_pool_keys);
  126. ASSERT_EQ(num_low_pri_pool_keys, low_pri_pool_keys);
  127. ASSERT_EQ(num_bottom_pri_pool_keys, bottom_pri_pool_keys);
  128. }
  129. protected:
  130. LRUCacheShard* cache_ = nullptr;
  131. private:
  132. Cache::EvictionCallback eviction_callback_;
  133. };
  134. TEST_F(LRUCacheTest, BasicLRU) {
  135. NewCache(5);
  136. for (char ch = 'a'; ch <= 'e'; ch++) {
  137. Insert(ch);
  138. }
  139. ValidateLRUList({"a", "b", "c", "d", "e"}, 0, 5);
  140. for (char ch = 'x'; ch <= 'z'; ch++) {
  141. Insert(ch);
  142. }
  143. ValidateLRUList({"d", "e", "x", "y", "z"}, 0, 5);
  144. ASSERT_FALSE(Lookup("b"));
  145. ValidateLRUList({"d", "e", "x", "y", "z"}, 0, 5);
  146. ASSERT_TRUE(Lookup("e"));
  147. ValidateLRUList({"d", "x", "y", "z", "e"}, 0, 5);
  148. ASSERT_TRUE(Lookup("z"));
  149. ValidateLRUList({"d", "x", "y", "e", "z"}, 0, 5);
  150. Erase("x");
  151. ValidateLRUList({"d", "y", "e", "z"}, 0, 4);
  152. ASSERT_TRUE(Lookup("d"));
  153. ValidateLRUList({"y", "e", "z", "d"}, 0, 4);
  154. Insert("u");
  155. ValidateLRUList({"y", "e", "z", "d", "u"}, 0, 5);
  156. Insert("v");
  157. ValidateLRUList({"e", "z", "d", "u", "v"}, 0, 5);
  158. }
  159. TEST_F(LRUCacheTest, LowPriorityMidpointInsertion) {
  160. // Allocate 2 cache entries to high-pri pool and 3 to low-pri pool.
  161. NewCache(5, /* high_pri_pool_ratio */ 0.40, /* low_pri_pool_ratio */ 0.60);
  162. Insert("a", Cache::Priority::LOW);
  163. Insert("b", Cache::Priority::LOW);
  164. Insert("c", Cache::Priority::LOW);
  165. Insert("x", Cache::Priority::HIGH);
  166. Insert("y", Cache::Priority::HIGH);
  167. ValidateLRUList({"a", "b", "c", "x", "y"}, 2, 3);
  168. // Low-pri entries inserted to the tail of low-pri list (the midpoint).
  169. // After lookup, it will move to the tail of the full list.
  170. Insert("d", Cache::Priority::LOW);
  171. ValidateLRUList({"b", "c", "d", "x", "y"}, 2, 3);
  172. ASSERT_TRUE(Lookup("d"));
  173. ValidateLRUList({"b", "c", "x", "y", "d"}, 2, 3);
  174. // High-pri entries will be inserted to the tail of full list.
  175. Insert("z", Cache::Priority::HIGH);
  176. ValidateLRUList({"c", "x", "y", "d", "z"}, 2, 3);
  177. }
  178. TEST_F(LRUCacheTest, BottomPriorityMidpointInsertion) {
  179. // Allocate 2 cache entries to high-pri pool and 2 to low-pri pool.
  180. NewCache(6, /* high_pri_pool_ratio */ 0.35, /* low_pri_pool_ratio */ 0.35);
  181. Insert("a", Cache::Priority::BOTTOM);
  182. Insert("b", Cache::Priority::BOTTOM);
  183. Insert("i", Cache::Priority::LOW);
  184. Insert("j", Cache::Priority::LOW);
  185. Insert("x", Cache::Priority::HIGH);
  186. Insert("y", Cache::Priority::HIGH);
  187. ValidateLRUList({"a", "b", "i", "j", "x", "y"}, 2, 2, 2);
  188. // Low-pri entries will be inserted to the tail of low-pri list (the
  189. // midpoint). After lookup, 'k' will move to the tail of the full list, and
  190. // 'x' will spill over to the low-pri pool.
  191. Insert("k", Cache::Priority::LOW);
  192. ValidateLRUList({"b", "i", "j", "k", "x", "y"}, 2, 2, 2);
  193. ASSERT_TRUE(Lookup("k"));
  194. ValidateLRUList({"b", "i", "j", "x", "y", "k"}, 2, 2, 2);
  195. // High-pri entries will be inserted to the tail of full list. Although y was
  196. // inserted with high priority, it got spilled over to the low-pri pool. As
  197. // a result, j also got spilled over to the bottom-pri pool.
  198. Insert("z", Cache::Priority::HIGH);
  199. ValidateLRUList({"i", "j", "x", "y", "k", "z"}, 2, 2, 2);
  200. Erase("x");
  201. ValidateLRUList({"i", "j", "y", "k", "z"}, 2, 1, 2);
  202. Erase("y");
  203. ValidateLRUList({"i", "j", "k", "z"}, 2, 0, 2);
  204. // Bottom-pri entries will be inserted to the tail of bottom-pri list.
  205. Insert("c", Cache::Priority::BOTTOM);
  206. ValidateLRUList({"i", "j", "c", "k", "z"}, 2, 0, 3);
  207. Insert("d", Cache::Priority::BOTTOM);
  208. ValidateLRUList({"i", "j", "c", "d", "k", "z"}, 2, 0, 4);
  209. Insert("e", Cache::Priority::BOTTOM);
  210. ValidateLRUList({"j", "c", "d", "e", "k", "z"}, 2, 0, 4);
  211. // Low-pri entries will be inserted to the tail of low-pri list (the
  212. // midpoint).
  213. Insert("l", Cache::Priority::LOW);
  214. ValidateLRUList({"c", "d", "e", "l", "k", "z"}, 2, 1, 3);
  215. Insert("m", Cache::Priority::LOW);
  216. ValidateLRUList({"d", "e", "l", "m", "k", "z"}, 2, 2, 2);
  217. Erase("k");
  218. ValidateLRUList({"d", "e", "l", "m", "z"}, 1, 2, 2);
  219. Erase("z");
  220. ValidateLRUList({"d", "e", "l", "m"}, 0, 2, 2);
  221. // Bottom-pri entries will be inserted to the tail of bottom-pri list.
  222. Insert("f", Cache::Priority::BOTTOM);
  223. ValidateLRUList({"d", "e", "f", "l", "m"}, 0, 2, 3);
  224. Insert("g", Cache::Priority::BOTTOM);
  225. ValidateLRUList({"d", "e", "f", "g", "l", "m"}, 0, 2, 4);
  226. // High-pri entries will be inserted to the tail of full list.
  227. Insert("o", Cache::Priority::HIGH);
  228. ValidateLRUList({"e", "f", "g", "l", "m", "o"}, 1, 2, 3);
  229. Insert("p", Cache::Priority::HIGH);
  230. ValidateLRUList({"f", "g", "l", "m", "o", "p"}, 2, 2, 2);
  231. }
  232. TEST_F(LRUCacheTest, EntriesWithPriority) {
  233. // Allocate 2 cache entries to high-pri pool and 2 to low-pri pool.
  234. NewCache(6, /* high_pri_pool_ratio */ 0.35, /* low_pri_pool_ratio */ 0.35);
  235. Insert("a", Cache::Priority::LOW);
  236. Insert("b", Cache::Priority::LOW);
  237. ValidateLRUList({"a", "b"}, 0, 2, 0);
  238. // Low-pri entries can overflow to bottom-pri pool.
  239. Insert("c", Cache::Priority::LOW);
  240. ValidateLRUList({"a", "b", "c"}, 0, 2, 1);
  241. // Bottom-pri entries can take high-pri pool capacity if available
  242. Insert("t", Cache::Priority::LOW);
  243. Insert("u", Cache::Priority::LOW);
  244. ValidateLRUList({"a", "b", "c", "t", "u"}, 0, 2, 3);
  245. Insert("v", Cache::Priority::LOW);
  246. ValidateLRUList({"a", "b", "c", "t", "u", "v"}, 0, 2, 4);
  247. Insert("w", Cache::Priority::LOW);
  248. ValidateLRUList({"b", "c", "t", "u", "v", "w"}, 0, 2, 4);
  249. Insert("X", Cache::Priority::HIGH);
  250. Insert("Y", Cache::Priority::HIGH);
  251. ValidateLRUList({"t", "u", "v", "w", "X", "Y"}, 2, 2, 2);
  252. // After lookup, the high-pri entry 'X' got spilled over to the low-pri pool.
  253. // The low-pri entry 'v' got spilled over to the bottom-pri pool.
  254. Insert("Z", Cache::Priority::HIGH);
  255. ValidateLRUList({"u", "v", "w", "X", "Y", "Z"}, 2, 2, 2);
  256. // Low-pri entries will be inserted to head of low-pri pool.
  257. Insert("a", Cache::Priority::LOW);
  258. ValidateLRUList({"v", "w", "X", "a", "Y", "Z"}, 2, 2, 2);
  259. // After lookup, the high-pri entry 'Y' got spilled over to the low-pri pool.
  260. // The low-pri entry 'X' got spilled over to the bottom-pri pool.
  261. ASSERT_TRUE(Lookup("v"));
  262. ValidateLRUList({"w", "X", "a", "Y", "Z", "v"}, 2, 2, 2);
  263. // After lookup, the high-pri entry 'Z' got spilled over to the low-pri pool.
  264. // The low-pri entry 'a' got spilled over to the bottom-pri pool.
  265. ASSERT_TRUE(Lookup("X"));
  266. ValidateLRUList({"w", "a", "Y", "Z", "v", "X"}, 2, 2, 2);
  267. // After lookup, the low pri entry 'Z' got promoted back to high-pri pool. The
  268. // high-pri entry 'v' got spilled over to the low-pri pool.
  269. ASSERT_TRUE(Lookup("Z"));
  270. ValidateLRUList({"w", "a", "Y", "v", "X", "Z"}, 2, 2, 2);
  271. Erase("Y");
  272. ValidateLRUList({"w", "a", "v", "X", "Z"}, 2, 1, 2);
  273. Erase("X");
  274. ValidateLRUList({"w", "a", "v", "Z"}, 1, 1, 2);
  275. Insert("d", Cache::Priority::LOW);
  276. Insert("e", Cache::Priority::LOW);
  277. ValidateLRUList({"w", "a", "v", "d", "e", "Z"}, 1, 2, 3);
  278. Insert("f", Cache::Priority::LOW);
  279. Insert("g", Cache::Priority::LOW);
  280. ValidateLRUList({"v", "d", "e", "f", "g", "Z"}, 1, 2, 3);
  281. ASSERT_TRUE(Lookup("d"));
  282. ValidateLRUList({"v", "e", "f", "g", "Z", "d"}, 2, 2, 2);
  283. // Erase some entries.
  284. Erase("e");
  285. Erase("f");
  286. Erase("Z");
  287. ValidateLRUList({"v", "g", "d"}, 1, 1, 1);
  288. // Bottom-pri entries can take low- and high-pri pool capacity if available
  289. Insert("o", Cache::Priority::BOTTOM);
  290. ValidateLRUList({"v", "o", "g", "d"}, 1, 1, 2);
  291. Insert("p", Cache::Priority::BOTTOM);
  292. ValidateLRUList({"v", "o", "p", "g", "d"}, 1, 1, 3);
  293. Insert("q", Cache::Priority::BOTTOM);
  294. ValidateLRUList({"v", "o", "p", "q", "g", "d"}, 1, 1, 4);
  295. // High-pri entries can overflow to low-pri pool, and bottom-pri entries will
  296. // be evicted.
  297. Insert("x", Cache::Priority::HIGH);
  298. ValidateLRUList({"o", "p", "q", "g", "d", "x"}, 2, 1, 3);
  299. Insert("y", Cache::Priority::HIGH);
  300. ValidateLRUList({"p", "q", "g", "d", "x", "y"}, 2, 2, 2);
  301. Insert("z", Cache::Priority::HIGH);
  302. ValidateLRUList({"q", "g", "d", "x", "y", "z"}, 2, 2, 2);
  303. // 'g' is bottom-pri before this lookup, it will be inserted to head of
  304. // high-pri pool after lookup.
  305. ASSERT_TRUE(Lookup("g"));
  306. ValidateLRUList({"q", "d", "x", "y", "z", "g"}, 2, 2, 2);
  307. // High-pri entries will be inserted to head of high-pri pool after lookup.
  308. ASSERT_TRUE(Lookup("z"));
  309. ValidateLRUList({"q", "d", "x", "y", "g", "z"}, 2, 2, 2);
  310. // Bottom-pri entries will be inserted to head of high-pri pool after lookup.
  311. ASSERT_TRUE(Lookup("d"));
  312. ValidateLRUList({"q", "x", "y", "g", "z", "d"}, 2, 2, 2);
  313. // Bottom-pri entries will be inserted to the tail of bottom-pri list.
  314. Insert("m", Cache::Priority::BOTTOM);
  315. ValidateLRUList({"x", "m", "y", "g", "z", "d"}, 2, 2, 2);
  316. // Bottom-pri entries will be inserted to head of high-pri pool after lookup.
  317. ASSERT_TRUE(Lookup("m"));
  318. ValidateLRUList({"x", "y", "g", "z", "d", "m"}, 2, 2, 2);
  319. }
  320. namespace clock_cache {
  321. template <class ClockCache>
  322. class ClockCacheTest : public testing::Test {
  323. public:
  324. using Shard = typename ClockCache::Shard;
  325. using Table = typename Shard::Table;
  326. using TableOpts = typename Table::Opts;
  327. ClockCacheTest() = default;
  328. ~ClockCacheTest() override { DeleteShard(); }
  329. void DeleteShard() {
  330. if (shard_ != nullptr) {
  331. shard_->~ClockCacheShard();
  332. port::cacheline_aligned_free(shard_);
  333. shard_ = nullptr;
  334. }
  335. }
  336. void NewShard(size_t capacity, bool strict_capacity_limit = true,
  337. int eviction_effort_cap = 30) {
  338. DeleteShard();
  339. shard_ = static_cast<Shard*>(port::cacheline_aligned_alloc(sizeof(Shard)));
  340. TableOpts opts{1 /*value_size*/, eviction_effort_cap};
  341. new (shard_)
  342. Shard(capacity, strict_capacity_limit, kDontChargeCacheMetadata,
  343. /*allocator*/ nullptr, &eviction_callback_, &hash_seed_, opts);
  344. }
  345. Status Insert(const UniqueId64x2& hashed_key,
  346. Cache::Priority priority = Cache::Priority::LOW) {
  347. return shard_->Insert(TestKey(hashed_key), hashed_key, nullptr /*value*/,
  348. &kNoopCacheItemHelper, 1 /*charge*/,
  349. nullptr /*handle*/, priority);
  350. }
  351. Status Insert(char key, Cache::Priority priority = Cache::Priority::LOW) {
  352. return Insert(TestHashedKey(key), priority);
  353. }
  354. Status InsertWithLen(char key, size_t len) {
  355. std::string skey(len, key);
  356. return shard_->Insert(skey, TestHashedKey(key), nullptr /*value*/,
  357. &kNoopCacheItemHelper, 1 /*charge*/,
  358. nullptr /*handle*/, Cache::Priority::LOW);
  359. }
  360. bool Lookup(const Slice& key, const UniqueId64x2& hashed_key,
  361. bool useful = true) {
  362. auto handle = shard_->Lookup(key, hashed_key);
  363. if (handle) {
  364. shard_->Release(handle, useful, /*erase_if_last_ref=*/false);
  365. return true;
  366. }
  367. return false;
  368. }
  369. bool Lookup(const UniqueId64x2& hashed_key, bool useful = true) {
  370. return Lookup(TestKey(hashed_key), hashed_key, useful);
  371. }
  372. bool Lookup(char key, bool useful = true) {
  373. return Lookup(TestHashedKey(key), useful);
  374. }
  375. void Erase(char key) {
  376. UniqueId64x2 hashed_key = TestHashedKey(key);
  377. shard_->Erase(TestKey(hashed_key), hashed_key);
  378. }
  379. static inline Slice TestKey(const UniqueId64x2& hashed_key) {
  380. return Slice(reinterpret_cast<const char*>(&hashed_key), 16U);
  381. }
  382. // A bad hash function for testing / stressing collision handling
  383. static inline UniqueId64x2 TestHashedKey(char key) {
  384. // For testing hash near-collision behavior, put the variance in
  385. // hashed_key in bits that are unlikely to be used as hash bits.
  386. return {(static_cast<uint64_t>(key) << 56) + 1234U, 5678U};
  387. }
  388. // A reasonable hash function, for testing "typical behavior" etc.
  389. template <typename T>
  390. static inline UniqueId64x2 CheapHash(T i) {
  391. return {static_cast<uint64_t>(i) * uint64_t{0x85EBCA77C2B2AE63},
  392. static_cast<uint64_t>(i) * uint64_t{0xC2B2AE3D27D4EB4F}};
  393. }
  394. Shard* shard_ = nullptr;
  395. private:
  396. Cache::EvictionCallback eviction_callback_;
  397. uint32_t hash_seed_ = 0;
  398. };
  399. using ClockCacheTypes =
  400. ::testing::Types<AutoHyperClockCache, FixedHyperClockCache>;
  401. TYPED_TEST_CASE(ClockCacheTest, ClockCacheTypes);
  402. TYPED_TEST(ClockCacheTest, Misc) {
  403. this->NewShard(3);
  404. // NOTE: templated base class prevents simple naming of inherited members,
  405. // so lots of `this->`
  406. auto& shard = *this->shard_;
  407. // Key size stuff
  408. EXPECT_OK(this->InsertWithLen('a', 16));
  409. EXPECT_NOK(this->InsertWithLen('b', 15));
  410. EXPECT_OK(this->InsertWithLen('b', 16));
  411. EXPECT_NOK(this->InsertWithLen('c', 17));
  412. EXPECT_NOK(this->InsertWithLen('d', 1000));
  413. EXPECT_NOK(this->InsertWithLen('e', 11));
  414. EXPECT_NOK(this->InsertWithLen('f', 0));
  415. // Some of this is motivated by code coverage
  416. std::string wrong_size_key(15, 'x');
  417. EXPECT_FALSE(this->Lookup(wrong_size_key, this->TestHashedKey('x')));
  418. EXPECT_FALSE(shard.Ref(nullptr));
  419. EXPECT_FALSE(shard.Release(nullptr));
  420. shard.Erase(wrong_size_key, this->TestHashedKey('x')); // no-op
  421. }
  422. TYPED_TEST(ClockCacheTest, Limits) {
  423. constexpr size_t kCapacity = 64;
  424. this->NewShard(kCapacity, false /*strict_capacity_limit*/);
  425. auto& shard = *this->shard_;
  426. using HandleImpl = typename ClockCacheTest<TypeParam>::Shard::HandleImpl;
  427. for (bool strict_capacity_limit : {false, true, false}) {
  428. SCOPED_TRACE("strict_capacity_limit = " +
  429. std::to_string(strict_capacity_limit));
  430. // Also tests switching between strict limit and not
  431. shard.SetStrictCapacityLimit(strict_capacity_limit);
  432. UniqueId64x2 hkey = this->TestHashedKey('x');
  433. // Single entry charge beyond capacity
  434. {
  435. Status s = shard.Insert(this->TestKey(hkey), hkey, nullptr /*value*/,
  436. &kNoopCacheItemHelper, kCapacity + 2 /*charge*/,
  437. nullptr /*handle*/, Cache::Priority::LOW);
  438. if (strict_capacity_limit) {
  439. EXPECT_TRUE(s.IsMemoryLimit());
  440. } else {
  441. EXPECT_OK(s);
  442. }
  443. }
  444. // Single entry fills capacity
  445. {
  446. HandleImpl* h;
  447. ASSERT_OK(shard.Insert(this->TestKey(hkey), hkey, nullptr /*value*/,
  448. &kNoopCacheItemHelper, kCapacity /*charge*/, &h,
  449. Cache::Priority::LOW));
  450. // Try to insert more
  451. Status s = this->Insert('a');
  452. if (strict_capacity_limit) {
  453. EXPECT_TRUE(s.IsMemoryLimit());
  454. } else {
  455. EXPECT_OK(s);
  456. }
  457. // Release entry filling capacity.
  458. // Cover useful = false case.
  459. shard.Release(h, false /*useful*/, false /*erase_if_last_ref*/);
  460. }
  461. // Insert more than table size can handle to exceed occupancy limit.
  462. // (Cleverly using mostly zero-charge entries, but some non-zero to
  463. // verify usage tracking on detached entries.)
  464. {
  465. size_t n = kCapacity * 5 + 1;
  466. std::unique_ptr<HandleImpl*[]> ha{new HandleImpl* [n] {}};
  467. Status s;
  468. for (size_t i = 0; i < n && s.ok(); ++i) {
  469. hkey[1] = i;
  470. s = shard.Insert(this->TestKey(hkey), hkey, nullptr /*value*/,
  471. &kNoopCacheItemHelper,
  472. (i + kCapacity < n) ? 0 : 1 /*charge*/, &ha[i],
  473. Cache::Priority::LOW);
  474. if (i == 0) {
  475. EXPECT_OK(s);
  476. }
  477. }
  478. if (strict_capacity_limit) {
  479. EXPECT_TRUE(s.IsMemoryLimit());
  480. } else {
  481. EXPECT_OK(s);
  482. }
  483. // Same result if not keeping a reference
  484. s = this->Insert('a');
  485. if (strict_capacity_limit) {
  486. EXPECT_TRUE(s.IsMemoryLimit());
  487. } else {
  488. EXPECT_OK(s);
  489. }
  490. EXPECT_EQ(shard.GetOccupancyCount(), shard.GetOccupancyLimit());
  491. // Regardless, we didn't allow table to actually get full
  492. EXPECT_LT(shard.GetOccupancyCount(), shard.GetTableAddressCount());
  493. // Release handles
  494. for (size_t i = 0; i < n; ++i) {
  495. if (ha[i]) {
  496. shard.Release(ha[i]);
  497. }
  498. }
  499. }
  500. }
  501. }
  502. TYPED_TEST(ClockCacheTest, ClockEvictionTest) {
  503. for (bool strict_capacity_limit : {false, true}) {
  504. SCOPED_TRACE("strict_capacity_limit = " +
  505. std::to_string(strict_capacity_limit));
  506. this->NewShard(6, strict_capacity_limit);
  507. auto& shard = *this->shard_;
  508. EXPECT_OK(this->Insert('a', Cache::Priority::BOTTOM));
  509. EXPECT_OK(this->Insert('b', Cache::Priority::LOW));
  510. EXPECT_OK(this->Insert('c', Cache::Priority::HIGH));
  511. EXPECT_OK(this->Insert('d', Cache::Priority::BOTTOM));
  512. EXPECT_OK(this->Insert('e', Cache::Priority::LOW));
  513. EXPECT_OK(this->Insert('f', Cache::Priority::HIGH));
  514. EXPECT_TRUE(this->Lookup('a', /*use*/ false));
  515. EXPECT_TRUE(this->Lookup('b', /*use*/ false));
  516. EXPECT_TRUE(this->Lookup('c', /*use*/ false));
  517. EXPECT_TRUE(this->Lookup('d', /*use*/ false));
  518. EXPECT_TRUE(this->Lookup('e', /*use*/ false));
  519. EXPECT_TRUE(this->Lookup('f', /*use*/ false));
  520. // Ensure bottom are evicted first, even if new entries are low
  521. EXPECT_OK(this->Insert('g', Cache::Priority::LOW));
  522. EXPECT_OK(this->Insert('h', Cache::Priority::LOW));
  523. EXPECT_FALSE(this->Lookup('a', /*use*/ false));
  524. EXPECT_TRUE(this->Lookup('b', /*use*/ false));
  525. EXPECT_TRUE(this->Lookup('c', /*use*/ false));
  526. EXPECT_FALSE(this->Lookup('d', /*use*/ false));
  527. EXPECT_TRUE(this->Lookup('e', /*use*/ false));
  528. EXPECT_TRUE(this->Lookup('f', /*use*/ false));
  529. // Mark g & h useful
  530. EXPECT_TRUE(this->Lookup('g', /*use*/ true));
  531. EXPECT_TRUE(this->Lookup('h', /*use*/ true));
  532. // Then old LOW entries
  533. EXPECT_OK(this->Insert('i', Cache::Priority::LOW));
  534. EXPECT_OK(this->Insert('j', Cache::Priority::LOW));
  535. EXPECT_FALSE(this->Lookup('b', /*use*/ false));
  536. EXPECT_TRUE(this->Lookup('c', /*use*/ false));
  537. EXPECT_FALSE(this->Lookup('e', /*use*/ false));
  538. EXPECT_TRUE(this->Lookup('f', /*use*/ false));
  539. // Mark g & h useful once again
  540. EXPECT_TRUE(this->Lookup('g', /*use*/ true));
  541. EXPECT_TRUE(this->Lookup('h', /*use*/ true));
  542. EXPECT_TRUE(this->Lookup('i', /*use*/ false));
  543. EXPECT_TRUE(this->Lookup('j', /*use*/ false));
  544. // Then old HIGH entries
  545. EXPECT_OK(this->Insert('k', Cache::Priority::LOW));
  546. EXPECT_OK(this->Insert('l', Cache::Priority::LOW));
  547. EXPECT_FALSE(this->Lookup('c', /*use*/ false));
  548. EXPECT_FALSE(this->Lookup('f', /*use*/ false));
  549. EXPECT_TRUE(this->Lookup('g', /*use*/ false));
  550. EXPECT_TRUE(this->Lookup('h', /*use*/ false));
  551. EXPECT_TRUE(this->Lookup('i', /*use*/ false));
  552. EXPECT_TRUE(this->Lookup('j', /*use*/ false));
  553. EXPECT_TRUE(this->Lookup('k', /*use*/ false));
  554. EXPECT_TRUE(this->Lookup('l', /*use*/ false));
  555. // Then the (roughly) least recently useful
  556. EXPECT_OK(this->Insert('m', Cache::Priority::HIGH));
  557. EXPECT_OK(this->Insert('n', Cache::Priority::HIGH));
  558. EXPECT_TRUE(this->Lookup('g', /*use*/ false));
  559. EXPECT_TRUE(this->Lookup('h', /*use*/ false));
  560. EXPECT_FALSE(this->Lookup('i', /*use*/ false));
  561. EXPECT_FALSE(this->Lookup('j', /*use*/ false));
  562. EXPECT_TRUE(this->Lookup('k', /*use*/ false));
  563. EXPECT_TRUE(this->Lookup('l', /*use*/ false));
  564. // Now try changing capacity down
  565. shard.SetCapacity(4);
  566. // Insert to ensure evictions happen
  567. EXPECT_OK(this->Insert('o', Cache::Priority::LOW));
  568. EXPECT_OK(this->Insert('p', Cache::Priority::LOW));
  569. EXPECT_FALSE(this->Lookup('g', /*use*/ false));
  570. EXPECT_FALSE(this->Lookup('h', /*use*/ false));
  571. EXPECT_FALSE(this->Lookup('k', /*use*/ false));
  572. EXPECT_FALSE(this->Lookup('l', /*use*/ false));
  573. EXPECT_TRUE(this->Lookup('m', /*use*/ false));
  574. EXPECT_TRUE(this->Lookup('n', /*use*/ false));
  575. EXPECT_TRUE(this->Lookup('o', /*use*/ false));
  576. EXPECT_TRUE(this->Lookup('p', /*use*/ false));
  577. // Now try changing capacity up
  578. EXPECT_TRUE(this->Lookup('m', /*use*/ true));
  579. EXPECT_TRUE(this->Lookup('n', /*use*/ true));
  580. shard.SetCapacity(6);
  581. EXPECT_OK(this->Insert('q', Cache::Priority::HIGH));
  582. EXPECT_OK(this->Insert('r', Cache::Priority::HIGH));
  583. EXPECT_OK(this->Insert('s', Cache::Priority::HIGH));
  584. EXPECT_OK(this->Insert('t', Cache::Priority::HIGH));
  585. EXPECT_FALSE(this->Lookup('o', /*use*/ false));
  586. EXPECT_FALSE(this->Lookup('p', /*use*/ false));
  587. EXPECT_TRUE(this->Lookup('m', /*use*/ false));
  588. EXPECT_TRUE(this->Lookup('n', /*use*/ false));
  589. EXPECT_TRUE(this->Lookup('q', /*use*/ false));
  590. EXPECT_TRUE(this->Lookup('r', /*use*/ false));
  591. EXPECT_TRUE(this->Lookup('s', /*use*/ false));
  592. EXPECT_TRUE(this->Lookup('t', /*use*/ false));
  593. }
  594. }
  595. TYPED_TEST(ClockCacheTest, ClockEvictionEffortCapTest) {
  596. using HandleImpl = typename ClockCacheTest<TypeParam>::Shard::HandleImpl;
  597. for (bool strict_capacity_limit : {true, false}) {
  598. SCOPED_TRACE("strict_capacity_limit = " +
  599. std::to_string(strict_capacity_limit));
  600. for (int eec : {-42, 0, 1, 10, 100, 1000}) {
  601. SCOPED_TRACE("eviction_effort_cap = " + std::to_string(eec));
  602. constexpr size_t kCapacity = 1000;
  603. // Start with much larger capacity to ensure that we can go way over
  604. // capacity without reaching table occupancy limit.
  605. this->NewShard(3 * kCapacity, strict_capacity_limit, eec);
  606. auto& shard = *this->shard_;
  607. shard.SetCapacity(kCapacity);
  608. // Nearly fill the cache with pinned entries, then add a bunch of
  609. // non-pinned entries. eviction_effort_cap should affect how many
  610. // evictable entries are present beyond the cache capacity, despite
  611. // being evictable.
  612. constexpr size_t kCount = kCapacity - 1;
  613. std::unique_ptr<HandleImpl*[]> ha{new HandleImpl* [kCount] {}};
  614. for (size_t i = 0; i < 2 * kCount; ++i) {
  615. UniqueId64x2 hkey = this->CheapHash(i);
  616. ASSERT_OK(shard.Insert(
  617. this->TestKey(hkey), hkey, nullptr /*value*/, &kNoopCacheItemHelper,
  618. 1 /*charge*/, i < kCount ? &ha[i] : nullptr, Cache::Priority::LOW));
  619. }
  620. if (strict_capacity_limit) {
  621. // If strict_capacity_limit is enabled, the cache will never exceed its
  622. // capacity
  623. EXPECT_EQ(shard.GetOccupancyCount(), kCapacity);
  624. } else {
  625. // Rough inverse relationship between cap and possible memory
  626. // explosion, which shows up as increased table occupancy count.
  627. int effective_eec = std::max(int{1}, eec) + 1;
  628. EXPECT_NEAR(shard.GetOccupancyCount() * 1.0,
  629. kCount * (1 + 1.4 / effective_eec),
  630. kCount * (0.6 / effective_eec) + 1.0);
  631. }
  632. for (size_t i = 0; i < kCount; ++i) {
  633. shard.Release(ha[i]);
  634. }
  635. }
  636. }
  637. }
  638. namespace {
  639. struct DeleteCounter {
  640. int deleted = 0;
  641. };
  642. const Cache::CacheItemHelper kDeleteCounterHelper{
  643. CacheEntryRole::kMisc,
  644. [](Cache::ObjectPtr value, MemoryAllocator* /*alloc*/) {
  645. static_cast<DeleteCounter*>(value)->deleted += 1;
  646. }};
  647. } // namespace
  648. // Testing calls to CorrectNearOverflow in Release
  649. TYPED_TEST(ClockCacheTest, ClockCounterOverflowTest) {
  650. this->NewShard(6, /*strict_capacity_limit*/ false);
  651. auto& shard = *this->shard_;
  652. using HandleImpl = typename ClockCacheTest<TypeParam>::Shard::HandleImpl;
  653. HandleImpl* h;
  654. DeleteCounter val;
  655. UniqueId64x2 hkey = this->TestHashedKey('x');
  656. ASSERT_OK(shard.Insert(this->TestKey(hkey), hkey, &val, &kDeleteCounterHelper,
  657. 1, &h, Cache::Priority::HIGH));
  658. // Some large number outstanding
  659. shard.TEST_RefN(h, 123456789);
  660. // Simulate many lookup/ref + release, plenty to overflow counters
  661. for (int i = 0; i < 10000; ++i) {
  662. shard.TEST_RefN(h, 1234567);
  663. shard.TEST_ReleaseN(h, 1234567);
  664. }
  665. // Mark it invisible (to reach a different CorrectNearOverflow() in Release)
  666. shard.Erase(this->TestKey(hkey), hkey);
  667. // Simulate many more lookup/ref + release (one-by-one would be too
  668. // expensive for unit test)
  669. for (int i = 0; i < 10000; ++i) {
  670. shard.TEST_RefN(h, 1234567);
  671. shard.TEST_ReleaseN(h, 1234567);
  672. }
  673. // Free all but last 1
  674. shard.TEST_ReleaseN(h, 123456789);
  675. // Still alive
  676. ASSERT_EQ(val.deleted, 0);
  677. // Free last ref, which will finalize erasure
  678. shard.Release(h);
  679. // Deleted
  680. ASSERT_EQ(val.deleted, 1);
  681. }
  682. TYPED_TEST(ClockCacheTest, ClockTableFull) {
  683. // Force clock cache table to fill up (not usually allowed) in order
  684. // to test full probe sequence that is theoretically possible due to
  685. // parallel operations
  686. this->NewShard(6, /*strict_capacity_limit*/ false);
  687. auto& shard = *this->shard_;
  688. using HandleImpl = typename ClockCacheTest<TypeParam>::Shard::HandleImpl;
  689. size_t size = shard.GetTableAddressCount();
  690. ASSERT_LE(size + 3, 256); // for using char keys
  691. // Modify occupancy and capacity limits to attempt insert on full
  692. shard.TEST_MutableOccupancyLimit() = size + 100;
  693. shard.SetCapacity(size + 100);
  694. DeleteCounter val;
  695. std::vector<HandleImpl*> handles;
  696. // NOTE: the three extra insertions should create standalone entries
  697. for (size_t i = 0; i < size + 3; ++i) {
  698. UniqueId64x2 hkey = this->TestHashedKey(static_cast<char>(i));
  699. ASSERT_OK(shard.Insert(this->TestKey(hkey), hkey, &val,
  700. &kDeleteCounterHelper, 1, &handles.emplace_back(),
  701. Cache::Priority::HIGH));
  702. }
  703. for (size_t i = 0; i < size + 3; ++i) {
  704. UniqueId64x2 hkey = this->TestHashedKey(static_cast<char>(i));
  705. HandleImpl* h = shard.Lookup(this->TestKey(hkey), hkey);
  706. if (i < size) {
  707. ASSERT_NE(h, nullptr);
  708. shard.Release(h);
  709. } else {
  710. // Standalone entries not visible by lookup
  711. ASSERT_EQ(h, nullptr);
  712. }
  713. }
  714. for (size_t i = 0; i < size + 3; ++i) {
  715. ASSERT_NE(handles[i], nullptr);
  716. shard.Release(handles[i]);
  717. if (i < size) {
  718. // Everything still in cache
  719. ASSERT_EQ(val.deleted, 0);
  720. } else {
  721. // Standalone entries freed on release
  722. ASSERT_EQ(val.deleted, i + 1 - size);
  723. }
  724. }
  725. for (size_t i = size + 3; i > 0; --i) {
  726. UniqueId64x2 hkey = this->TestHashedKey(static_cast<char>(i - 1));
  727. shard.Erase(this->TestKey(hkey), hkey);
  728. if (i - 1 > size) {
  729. ASSERT_EQ(val.deleted, 3);
  730. } else {
  731. ASSERT_EQ(val.deleted, 3 + size - (i - 1));
  732. }
  733. }
  734. }
  735. // This test is mostly to exercise some corner case logic, by forcing two
  736. // keys to have the same hash, and more
  737. TYPED_TEST(ClockCacheTest, CollidingInsertEraseTest) {
  738. this->NewShard(6, /*strict_capacity_limit*/ false);
  739. auto& shard = *this->shard_;
  740. using HandleImpl = typename ClockCacheTest<TypeParam>::Shard::HandleImpl;
  741. DeleteCounter val;
  742. UniqueId64x2 hkey1 = this->TestHashedKey('x');
  743. Slice key1 = this->TestKey(hkey1);
  744. UniqueId64x2 hkey2 = this->TestHashedKey('y');
  745. Slice key2 = this->TestKey(hkey2);
  746. UniqueId64x2 hkey3 = this->TestHashedKey('z');
  747. Slice key3 = this->TestKey(hkey3);
  748. HandleImpl* h1;
  749. ASSERT_OK(shard.Insert(key1, hkey1, &val, &kDeleteCounterHelper, 1, &h1,
  750. Cache::Priority::HIGH));
  751. HandleImpl* h2;
  752. ASSERT_OK(shard.Insert(key2, hkey2, &val, &kDeleteCounterHelper, 1, &h2,
  753. Cache::Priority::HIGH));
  754. HandleImpl* h3;
  755. ASSERT_OK(shard.Insert(key3, hkey3, &val, &kDeleteCounterHelper, 1, &h3,
  756. Cache::Priority::HIGH));
  757. // Can repeatedly lookup+release despite the hash collision
  758. HandleImpl* tmp_h;
  759. for (bool erase_if_last_ref : {true, false}) { // but not last ref
  760. tmp_h = shard.Lookup(key1, hkey1);
  761. ASSERT_EQ(h1, tmp_h);
  762. ASSERT_FALSE(shard.Release(tmp_h, erase_if_last_ref));
  763. tmp_h = shard.Lookup(key2, hkey2);
  764. ASSERT_EQ(h2, tmp_h);
  765. ASSERT_FALSE(shard.Release(tmp_h, erase_if_last_ref));
  766. tmp_h = shard.Lookup(key3, hkey3);
  767. ASSERT_EQ(h3, tmp_h);
  768. ASSERT_FALSE(shard.Release(tmp_h, erase_if_last_ref));
  769. }
  770. // Make h1 invisible
  771. shard.Erase(key1, hkey1);
  772. // Redundant erase
  773. shard.Erase(key1, hkey1);
  774. // All still alive
  775. ASSERT_EQ(val.deleted, 0);
  776. // Invisible to Lookup
  777. tmp_h = shard.Lookup(key1, hkey1);
  778. ASSERT_EQ(nullptr, tmp_h);
  779. // Can still find h2, h3
  780. for (bool erase_if_last_ref : {true, false}) { // but not last ref
  781. tmp_h = shard.Lookup(key2, hkey2);
  782. ASSERT_EQ(h2, tmp_h);
  783. ASSERT_FALSE(shard.Release(tmp_h, erase_if_last_ref));
  784. tmp_h = shard.Lookup(key3, hkey3);
  785. ASSERT_EQ(h3, tmp_h);
  786. ASSERT_FALSE(shard.Release(tmp_h, erase_if_last_ref));
  787. }
  788. // Also Insert with invisible entry there
  789. ASSERT_OK(shard.Insert(key1, hkey1, &val, &kDeleteCounterHelper, 1, nullptr,
  790. Cache::Priority::HIGH));
  791. tmp_h = shard.Lookup(key1, hkey1);
  792. // Found but distinct handle
  793. ASSERT_NE(nullptr, tmp_h);
  794. ASSERT_NE(h1, tmp_h);
  795. ASSERT_TRUE(shard.Release(tmp_h, /*erase_if_last_ref*/ true));
  796. // tmp_h deleted
  797. ASSERT_EQ(val.deleted--, 1);
  798. // Release last ref on h1 (already invisible)
  799. ASSERT_TRUE(shard.Release(h1, /*erase_if_last_ref*/ false));
  800. // h1 deleted
  801. ASSERT_EQ(val.deleted--, 1);
  802. h1 = nullptr;
  803. // Can still find h2, h3
  804. for (bool erase_if_last_ref : {true, false}) { // but not last ref
  805. tmp_h = shard.Lookup(key2, hkey2);
  806. ASSERT_EQ(h2, tmp_h);
  807. ASSERT_FALSE(shard.Release(tmp_h, erase_if_last_ref));
  808. tmp_h = shard.Lookup(key3, hkey3);
  809. ASSERT_EQ(h3, tmp_h);
  810. ASSERT_FALSE(shard.Release(tmp_h, erase_if_last_ref));
  811. }
  812. // Release last ref on h2
  813. ASSERT_FALSE(shard.Release(h2, /*erase_if_last_ref*/ false));
  814. // h2 still not deleted (unreferenced in cache)
  815. ASSERT_EQ(val.deleted, 0);
  816. // Can still find it
  817. tmp_h = shard.Lookup(key2, hkey2);
  818. ASSERT_EQ(h2, tmp_h);
  819. // Release last ref on h2, with erase
  820. ASSERT_TRUE(shard.Release(h2, /*erase_if_last_ref*/ true));
  821. // h2 deleted
  822. ASSERT_EQ(val.deleted--, 1);
  823. tmp_h = shard.Lookup(key2, hkey2);
  824. ASSERT_EQ(nullptr, tmp_h);
  825. // Can still find h3
  826. for (bool erase_if_last_ref : {true, false}) { // but not last ref
  827. tmp_h = shard.Lookup(key3, hkey3);
  828. ASSERT_EQ(h3, tmp_h);
  829. ASSERT_FALSE(shard.Release(tmp_h, erase_if_last_ref));
  830. }
  831. // Release last ref on h3, without erase
  832. ASSERT_FALSE(shard.Release(h3, /*erase_if_last_ref*/ false));
  833. // h3 still not deleted (unreferenced in cache)
  834. ASSERT_EQ(val.deleted, 0);
  835. // Explicit erase
  836. shard.Erase(key3, hkey3);
  837. // h3 deleted
  838. ASSERT_EQ(val.deleted--, 1);
  839. tmp_h = shard.Lookup(key3, hkey3);
  840. ASSERT_EQ(nullptr, tmp_h);
  841. }
  842. // This uses the public API to effectively test CalcHashBits etc.
  843. TYPED_TEST(ClockCacheTest, TableSizesTest) {
  844. for (size_t est_val_size : {1U, 5U, 123U, 2345U, 345678U}) {
  845. SCOPED_TRACE("est_val_size = " + std::to_string(est_val_size));
  846. for (double est_count : {1.1, 2.2, 511.9, 512.1, 2345.0}) {
  847. SCOPED_TRACE("est_count = " + std::to_string(est_count));
  848. size_t capacity = static_cast<size_t>(est_val_size * est_count);
  849. // kDontChargeCacheMetadata
  850. auto cache = HyperClockCacheOptions(
  851. capacity, est_val_size, /*num shard_bits*/ -1,
  852. /*strict_capacity_limit*/ false,
  853. /*memory_allocator*/ nullptr, kDontChargeCacheMetadata)
  854. .MakeSharedCache();
  855. // Table sizes are currently only powers of two
  856. EXPECT_GE(cache->GetTableAddressCount(),
  857. est_count / FixedHyperClockTable::kLoadFactor);
  858. EXPECT_LE(cache->GetTableAddressCount(),
  859. est_count / FixedHyperClockTable::kLoadFactor * 2.0);
  860. EXPECT_EQ(cache->GetUsage(), 0);
  861. // kFullChargeMetaData
  862. // Because table sizes are currently only powers of two, sizes get
  863. // really weird when metadata is a huge portion of capacity. For example,
  864. // doubling the table size could cut by 90% the space available to
  865. // values. Therefore, we omit those weird cases for now.
  866. if (est_val_size >= 512) {
  867. cache = HyperClockCacheOptions(
  868. capacity, est_val_size, /*num shard_bits*/ -1,
  869. /*strict_capacity_limit*/ false,
  870. /*memory_allocator*/ nullptr, kFullChargeCacheMetadata)
  871. .MakeSharedCache();
  872. double est_count_after_meta =
  873. (capacity - cache->GetUsage()) * 1.0 / est_val_size;
  874. EXPECT_GE(cache->GetTableAddressCount(),
  875. est_count_after_meta / FixedHyperClockTable::kLoadFactor);
  876. EXPECT_LE(
  877. cache->GetTableAddressCount(),
  878. est_count_after_meta / FixedHyperClockTable::kLoadFactor * 2.0);
  879. }
  880. }
  881. }
  882. }
  883. } // namespace clock_cache
  884. class TestSecondaryCache : public SecondaryCache {
  885. public:
  886. // Specifies what action to take on a lookup for a particular key
  887. enum ResultType {
  888. SUCCESS,
  889. // Fail lookup immediately
  890. FAIL,
  891. // Defer the result. It will returned after Wait/WaitAll is called
  892. DEFER,
  893. // Defer the result and eventually return failure
  894. DEFER_AND_FAIL
  895. };
  896. using ResultMap = std::unordered_map<std::string, ResultType>;
  897. explicit TestSecondaryCache(size_t capacity, bool insert_saved = false)
  898. : cache_(NewLRUCache(capacity, 0, false, 0.5 /* high_pri_pool_ratio */,
  899. nullptr, kDefaultToAdaptiveMutex,
  900. kDontChargeCacheMetadata)),
  901. num_inserts_(0),
  902. num_lookups_(0),
  903. inject_failure_(false),
  904. insert_saved_(insert_saved) {}
  905. const char* Name() const override { return "TestSecondaryCache"; }
  906. void InjectFailure() { inject_failure_ = true; }
  907. void ResetInjectFailure() { inject_failure_ = false; }
  908. Status Insert(const Slice& key, Cache::ObjectPtr value,
  909. const Cache::CacheItemHelper* helper,
  910. bool /*force_insert*/) override {
  911. if (inject_failure_) {
  912. return Status::Corruption("Insertion Data Corrupted");
  913. }
  914. CheckCacheKeyCommonPrefix(key);
  915. size_t size;
  916. char* buf;
  917. Status s;
  918. num_inserts_++;
  919. size = (*helper->size_cb)(value);
  920. buf = new char[size + sizeof(uint64_t)];
  921. EncodeFixed64(buf, size);
  922. s = (*helper->saveto_cb)(value, 0, size, buf + sizeof(uint64_t));
  923. if (!s.ok()) {
  924. delete[] buf;
  925. return s;
  926. }
  927. return cache_.Insert(key, buf, size);
  928. }
  929. Status InsertSaved(const Slice& key, const Slice& saved,
  930. CompressionType /*type*/ = kNoCompression,
  931. CacheTier /*source*/ = CacheTier::kVolatileTier) override {
  932. if (insert_saved_) {
  933. return Insert(key, const_cast<Slice*>(&saved), &kSliceCacheItemHelper,
  934. /*force_insert=*/true);
  935. } else {
  936. return Status::OK();
  937. }
  938. }
  939. std::unique_ptr<SecondaryCacheResultHandle> Lookup(
  940. const Slice& key, const Cache::CacheItemHelper* helper,
  941. Cache::CreateContext* create_context, bool /*wait*/,
  942. bool /*advise_erase*/, Statistics* /*stats*/,
  943. bool& kept_in_sec_cache) override {
  944. std::string key_str = key.ToString();
  945. TEST_SYNC_POINT_CALLBACK("TestSecondaryCache::Lookup", &key_str);
  946. std::unique_ptr<SecondaryCacheResultHandle> secondary_handle;
  947. kept_in_sec_cache = false;
  948. ResultType type = ResultType::SUCCESS;
  949. auto iter = result_map_.find(key.ToString());
  950. if (iter != result_map_.end()) {
  951. type = iter->second;
  952. }
  953. if (type == ResultType::FAIL) {
  954. return secondary_handle;
  955. }
  956. TypedHandle* handle = cache_.Lookup(key);
  957. num_lookups_++;
  958. if (handle) {
  959. Cache::ObjectPtr value = nullptr;
  960. size_t charge = 0;
  961. Status s;
  962. if (type != ResultType::DEFER_AND_FAIL) {
  963. char* ptr = cache_.Value(handle);
  964. size_t size = DecodeFixed64(ptr);
  965. ptr += sizeof(uint64_t);
  966. s = helper->create_cb(Slice(ptr, size), kNoCompression,
  967. CacheTier::kVolatileTier, create_context,
  968. /*alloc*/ nullptr, &value, &charge);
  969. }
  970. if (s.ok()) {
  971. secondary_handle.reset(new TestSecondaryCacheResultHandle(
  972. cache_.get(), handle, value, charge, type));
  973. kept_in_sec_cache = true;
  974. } else {
  975. cache_.Release(handle);
  976. }
  977. }
  978. return secondary_handle;
  979. }
  980. bool SupportForceErase() const override { return false; }
  981. void Erase(const Slice& /*key*/) override {}
  982. void WaitAll(std::vector<SecondaryCacheResultHandle*> handles) override {
  983. for (SecondaryCacheResultHandle* handle : handles) {
  984. TestSecondaryCacheResultHandle* sec_handle =
  985. static_cast<TestSecondaryCacheResultHandle*>(handle);
  986. sec_handle->SetReady();
  987. }
  988. }
  989. std::string GetPrintableOptions() const override { return ""; }
  990. void SetResultMap(ResultMap&& map) { result_map_ = std::move(map); }
  991. uint32_t num_inserts() { return num_inserts_; }
  992. uint32_t num_lookups() { return num_lookups_; }
  993. void CheckCacheKeyCommonPrefix(const Slice& key) {
  994. Slice current_prefix(key.data(), OffsetableCacheKey::kCommonPrefixSize);
  995. if (ckey_prefix_.empty()) {
  996. ckey_prefix_ = current_prefix.ToString();
  997. } else {
  998. EXPECT_EQ(ckey_prefix_, current_prefix.ToString());
  999. }
  1000. }
  1001. private:
  1002. class TestSecondaryCacheResultHandle : public SecondaryCacheResultHandle {
  1003. public:
  1004. TestSecondaryCacheResultHandle(Cache* cache, Cache::Handle* handle,
  1005. Cache::ObjectPtr value, size_t size,
  1006. ResultType type)
  1007. : cache_(cache),
  1008. handle_(handle),
  1009. value_(value),
  1010. size_(size),
  1011. is_ready_(true) {
  1012. if (type != ResultType::SUCCESS) {
  1013. is_ready_ = false;
  1014. }
  1015. }
  1016. ~TestSecondaryCacheResultHandle() override { cache_->Release(handle_); }
  1017. bool IsReady() override { return is_ready_; }
  1018. void Wait() override {}
  1019. Cache::ObjectPtr Value() override {
  1020. assert(is_ready_);
  1021. return value_;
  1022. }
  1023. size_t Size() override { return Value() ? size_ : 0; }
  1024. void SetReady() { is_ready_ = true; }
  1025. private:
  1026. Cache* cache_;
  1027. Cache::Handle* handle_;
  1028. Cache::ObjectPtr value_;
  1029. size_t size_;
  1030. bool is_ready_;
  1031. };
  1032. using SharedCache =
  1033. BasicTypedSharedCacheInterface<char[], CacheEntryRole::kMisc>;
  1034. using TypedHandle = SharedCache::TypedHandle;
  1035. SharedCache cache_;
  1036. uint32_t num_inserts_;
  1037. uint32_t num_lookups_;
  1038. bool inject_failure_;
  1039. bool insert_saved_;
  1040. std::string ckey_prefix_;
  1041. ResultMap result_map_;
  1042. };
  1043. using secondary_cache_test_util::GetTestingCacheTypes;
  1044. using secondary_cache_test_util::WithCacheTypeParam;
  1045. class BasicSecondaryCacheTest : public testing::Test,
  1046. public WithCacheTypeParam {};
  1047. INSTANTIATE_TEST_CASE_P(BasicSecondaryCacheTest, BasicSecondaryCacheTest,
  1048. GetTestingCacheTypes());
  1049. class DBSecondaryCacheTest : public DBTestBase, public WithCacheTypeParam {
  1050. public:
  1051. DBSecondaryCacheTest()
  1052. : DBTestBase("db_secondary_cache_test", /*env_do_fsync=*/true) {
  1053. fault_fs_.reset(new FaultInjectionTestFS(env_->GetFileSystem()));
  1054. fault_env_.reset(new CompositeEnvWrapper(env_, fault_fs_));
  1055. }
  1056. std::shared_ptr<FaultInjectionTestFS> fault_fs_;
  1057. std::unique_ptr<Env> fault_env_;
  1058. };
  1059. INSTANTIATE_TEST_CASE_P(DBSecondaryCacheTest, DBSecondaryCacheTest,
  1060. GetTestingCacheTypes());
  1061. TEST_P(BasicSecondaryCacheTest, BasicTest) {
  1062. std::shared_ptr<TestSecondaryCache> secondary_cache =
  1063. std::make_shared<TestSecondaryCache>(4096, true);
  1064. std::shared_ptr<Cache> cache =
  1065. NewCache(1024 /* capacity */, 0 /* num_shard_bits */,
  1066. false /* strict_capacity_limit */, secondary_cache);
  1067. std::shared_ptr<Statistics> stats = CreateDBStatistics();
  1068. CacheKey k1 = CacheKey::CreateUniqueForCacheLifetime(cache.get());
  1069. CacheKey k2 = CacheKey::CreateUniqueForCacheLifetime(cache.get());
  1070. CacheKey k3 = CacheKey::CreateUniqueForCacheLifetime(cache.get());
  1071. Random rnd(301);
  1072. // Start with warming k3
  1073. std::string str3 = rnd.RandomString(1021);
  1074. ASSERT_OK(secondary_cache->InsertSaved(k3.AsSlice(), str3));
  1075. std::string str1 = rnd.RandomString(1021);
  1076. TestItem* item1 = new TestItem(str1.data(), str1.length());
  1077. ASSERT_OK(cache->Insert(k1.AsSlice(), item1, GetHelper(), str1.length()));
  1078. std::string str2 = rnd.RandomString(1021);
  1079. TestItem* item2 = new TestItem(str2.data(), str2.length());
  1080. // k1 should be demoted to NVM
  1081. ASSERT_OK(cache->Insert(k2.AsSlice(), item2, GetHelper(), str2.length()));
  1082. get_perf_context()->Reset();
  1083. Cache::Handle* handle;
  1084. handle = cache->Lookup(k2.AsSlice(), GetHelper(),
  1085. /*context*/ this, Cache::Priority::LOW, stats.get());
  1086. ASSERT_NE(handle, nullptr);
  1087. ASSERT_EQ(static_cast<TestItem*>(cache->Value(handle))->Size(), str2.size());
  1088. cache->Release(handle);
  1089. // This lookup should promote k1 and demote k2
  1090. handle = cache->Lookup(k1.AsSlice(), GetHelper(),
  1091. /*context*/ this, Cache::Priority::LOW, stats.get());
  1092. ASSERT_NE(handle, nullptr);
  1093. ASSERT_EQ(static_cast<TestItem*>(cache->Value(handle))->Size(), str1.size());
  1094. cache->Release(handle);
  1095. // This lookup should promote k3 and demote k1
  1096. handle = cache->Lookup(k3.AsSlice(), GetHelper(),
  1097. /*context*/ this, Cache::Priority::LOW, stats.get());
  1098. ASSERT_NE(handle, nullptr);
  1099. ASSERT_EQ(static_cast<TestItem*>(cache->Value(handle))->Size(), str3.size());
  1100. cache->Release(handle);
  1101. ASSERT_EQ(secondary_cache->num_inserts(), 3u);
  1102. ASSERT_EQ(secondary_cache->num_lookups(), 2u);
  1103. ASSERT_EQ(stats->getTickerCount(SECONDARY_CACHE_HITS),
  1104. secondary_cache->num_lookups());
  1105. PerfContext perf_ctx = *get_perf_context();
  1106. ASSERT_EQ(perf_ctx.secondary_cache_hit_count, secondary_cache->num_lookups());
  1107. cache.reset();
  1108. secondary_cache.reset();
  1109. }
  1110. TEST_P(BasicSecondaryCacheTest, StatsTest) {
  1111. std::shared_ptr<TestSecondaryCache> secondary_cache =
  1112. std::make_shared<TestSecondaryCache>(4096, true);
  1113. std::shared_ptr<Cache> cache =
  1114. NewCache(1024 /* capacity */, 0 /* num_shard_bits */,
  1115. false /* strict_capacity_limit */, secondary_cache);
  1116. std::shared_ptr<Statistics> stats = CreateDBStatistics();
  1117. CacheKey k1 = CacheKey::CreateUniqueForCacheLifetime(cache.get());
  1118. CacheKey k2 = CacheKey::CreateUniqueForCacheLifetime(cache.get());
  1119. CacheKey k3 = CacheKey::CreateUniqueForCacheLifetime(cache.get());
  1120. Random rnd(301);
  1121. // Start with warming secondary cache
  1122. std::string str1 = rnd.RandomString(1020);
  1123. std::string str2 = rnd.RandomString(1020);
  1124. std::string str3 = rnd.RandomString(1020);
  1125. ASSERT_OK(secondary_cache->InsertSaved(k1.AsSlice(), str1));
  1126. ASSERT_OK(secondary_cache->InsertSaved(k2.AsSlice(), str2));
  1127. ASSERT_OK(secondary_cache->InsertSaved(k3.AsSlice(), str3));
  1128. get_perf_context()->Reset();
  1129. Cache::Handle* handle;
  1130. handle = cache->Lookup(k1.AsSlice(), GetHelper(CacheEntryRole::kFilterBlock),
  1131. /*context*/ this, Cache::Priority::LOW, stats.get());
  1132. ASSERT_NE(handle, nullptr);
  1133. ASSERT_EQ(static_cast<TestItem*>(cache->Value(handle))->Size(), str1.size());
  1134. cache->Release(handle);
  1135. handle = cache->Lookup(k2.AsSlice(), GetHelper(CacheEntryRole::kIndexBlock),
  1136. /*context*/ this, Cache::Priority::LOW, stats.get());
  1137. ASSERT_NE(handle, nullptr);
  1138. ASSERT_EQ(static_cast<TestItem*>(cache->Value(handle))->Size(), str2.size());
  1139. cache->Release(handle);
  1140. handle = cache->Lookup(k3.AsSlice(), GetHelper(CacheEntryRole::kDataBlock),
  1141. /*context*/ this, Cache::Priority::LOW, stats.get());
  1142. ASSERT_NE(handle, nullptr);
  1143. ASSERT_EQ(static_cast<TestItem*>(cache->Value(handle))->Size(), str3.size());
  1144. cache->Release(handle);
  1145. ASSERT_EQ(secondary_cache->num_inserts(), 3u);
  1146. ASSERT_EQ(secondary_cache->num_lookups(), 3u);
  1147. ASSERT_EQ(stats->getTickerCount(SECONDARY_CACHE_HITS),
  1148. secondary_cache->num_lookups());
  1149. ASSERT_EQ(stats->getTickerCount(SECONDARY_CACHE_FILTER_HITS), 1);
  1150. ASSERT_EQ(stats->getTickerCount(SECONDARY_CACHE_INDEX_HITS), 1);
  1151. ASSERT_EQ(stats->getTickerCount(SECONDARY_CACHE_DATA_HITS), 1);
  1152. PerfContext perf_ctx = *get_perf_context();
  1153. ASSERT_EQ(perf_ctx.secondary_cache_hit_count, secondary_cache->num_lookups());
  1154. cache.reset();
  1155. secondary_cache.reset();
  1156. }
  1157. TEST_P(BasicSecondaryCacheTest, BasicFailTest) {
  1158. std::shared_ptr<TestSecondaryCache> secondary_cache =
  1159. std::make_shared<TestSecondaryCache>(2048, true);
  1160. std::shared_ptr<Cache> cache =
  1161. NewCache(1024 /* capacity */, 0 /* num_shard_bits */,
  1162. false /* strict_capacity_limit */, secondary_cache);
  1163. CacheKey k1 = CacheKey::CreateUniqueForCacheLifetime(cache.get());
  1164. CacheKey k2 = CacheKey::CreateUniqueForCacheLifetime(cache.get());
  1165. Random rnd(301);
  1166. std::string str1 = rnd.RandomString(1020);
  1167. auto item1 = std::make_unique<TestItem>(str1.data(), str1.length());
  1168. // NOTE: changed to assert helper != nullptr for efficiency / code size
  1169. // ASSERT_TRUE(cache->Insert(k1.AsSlice(), item1.get(), nullptr,
  1170. // str1.length()).IsInvalidArgument());
  1171. ASSERT_OK(
  1172. cache->Insert(k1.AsSlice(), item1.get(), GetHelper(), str1.length()));
  1173. item1.release(); // Appease clang-analyze "potential memory leak"
  1174. Cache::Handle* handle;
  1175. handle = cache->Lookup(k2.AsSlice(), nullptr, /*context*/ this,
  1176. Cache::Priority::LOW);
  1177. ASSERT_EQ(handle, nullptr);
  1178. handle = cache->Lookup(k2.AsSlice(), GetHelper(),
  1179. /*context*/ this, Cache::Priority::LOW);
  1180. ASSERT_EQ(handle, nullptr);
  1181. Cache::AsyncLookupHandle async_handle;
  1182. async_handle.key = k2.AsSlice();
  1183. async_handle.helper = GetHelper();
  1184. async_handle.create_context = this;
  1185. async_handle.priority = Cache::Priority::LOW;
  1186. cache->StartAsyncLookup(async_handle);
  1187. cache->Wait(async_handle);
  1188. handle = async_handle.Result();
  1189. ASSERT_EQ(handle, nullptr);
  1190. cache.reset();
  1191. secondary_cache.reset();
  1192. }
  1193. TEST_P(BasicSecondaryCacheTest, SaveFailTest) {
  1194. std::shared_ptr<TestSecondaryCache> secondary_cache =
  1195. std::make_shared<TestSecondaryCache>(2048, true);
  1196. std::shared_ptr<Cache> cache =
  1197. NewCache(1024 /* capacity */, 0 /* num_shard_bits */,
  1198. false /* strict_capacity_limit */, secondary_cache);
  1199. CacheKey k1 = CacheKey::CreateUniqueForCacheLifetime(cache.get());
  1200. CacheKey k2 = CacheKey::CreateUniqueForCacheLifetime(cache.get());
  1201. Random rnd(301);
  1202. std::string str1 = rnd.RandomString(1020);
  1203. TestItem* item1 = new TestItem(str1.data(), str1.length());
  1204. ASSERT_OK(cache->Insert(k1.AsSlice(), item1, GetHelperFail(), str1.length()));
  1205. std::string str2 = rnd.RandomString(1020);
  1206. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  1207. TestItem* item2 = new TestItem(str2.data(), str2.length());
  1208. // k1 should be demoted to NVM
  1209. ASSERT_OK(cache->Insert(k2.AsSlice(), item2, GetHelperFail(), str2.length()));
  1210. ASSERT_EQ(secondary_cache->num_inserts(), 1u);
  1211. Cache::Handle* handle;
  1212. handle = cache->Lookup(k2.AsSlice(), GetHelperFail(),
  1213. /*context*/ this, Cache::Priority::LOW);
  1214. ASSERT_NE(handle, nullptr);
  1215. cache->Release(handle);
  1216. // This lookup should fail, since k1 demotion would have failed
  1217. handle = cache->Lookup(k1.AsSlice(), GetHelperFail(),
  1218. /*context*/ this, Cache::Priority::LOW);
  1219. ASSERT_EQ(handle, nullptr);
  1220. // Since k1 didn't get promoted, k2 should still be in cache
  1221. handle = cache->Lookup(k2.AsSlice(), GetHelperFail(),
  1222. /*context*/ this, Cache::Priority::LOW);
  1223. ASSERT_NE(handle, nullptr);
  1224. cache->Release(handle);
  1225. ASSERT_EQ(secondary_cache->num_inserts(), 1u);
  1226. ASSERT_EQ(secondary_cache->num_lookups(), 1u);
  1227. cache.reset();
  1228. secondary_cache.reset();
  1229. }
  1230. TEST_P(BasicSecondaryCacheTest, CreateFailTest) {
  1231. std::shared_ptr<TestSecondaryCache> secondary_cache =
  1232. std::make_shared<TestSecondaryCache>(2048, true);
  1233. std::shared_ptr<Cache> cache =
  1234. NewCache(1024 /* capacity */, 0 /* num_shard_bits */,
  1235. false /* strict_capacity_limit */, secondary_cache);
  1236. CacheKey k1 = CacheKey::CreateUniqueForCacheLifetime(cache.get());
  1237. CacheKey k2 = CacheKey::CreateUniqueForCacheLifetime(cache.get());
  1238. Random rnd(301);
  1239. std::string str1 = rnd.RandomString(1020);
  1240. TestItem* item1 = new TestItem(str1.data(), str1.length());
  1241. ASSERT_OK(cache->Insert(k1.AsSlice(), item1, GetHelper(), str1.length()));
  1242. std::string str2 = rnd.RandomString(1020);
  1243. TestItem* item2 = new TestItem(str2.data(), str2.length());
  1244. // k1 should be demoted to NVM
  1245. ASSERT_OK(cache->Insert(k2.AsSlice(), item2, GetHelper(), str2.length()));
  1246. Cache::Handle* handle;
  1247. SetFailCreate(true);
  1248. handle = cache->Lookup(k2.AsSlice(), GetHelper(),
  1249. /*context*/ this, Cache::Priority::LOW);
  1250. ASSERT_NE(handle, nullptr);
  1251. cache->Release(handle);
  1252. // This lookup should fail, since k1 creation would have failed
  1253. handle = cache->Lookup(k1.AsSlice(), GetHelper(),
  1254. /*context*/ this, Cache::Priority::LOW);
  1255. ASSERT_EQ(handle, nullptr);
  1256. // Since k1 didn't get promoted, k2 should still be in cache
  1257. handle = cache->Lookup(k2.AsSlice(), GetHelper(),
  1258. /*context*/ this, Cache::Priority::LOW);
  1259. ASSERT_NE(handle, nullptr);
  1260. cache->Release(handle);
  1261. ASSERT_EQ(secondary_cache->num_inserts(), 1u);
  1262. ASSERT_EQ(secondary_cache->num_lookups(), 1u);
  1263. cache.reset();
  1264. secondary_cache.reset();
  1265. }
  1266. TEST_P(BasicSecondaryCacheTest, FullCapacityTest) {
  1267. for (bool strict_capacity_limit : {false, true}) {
  1268. std::shared_ptr<TestSecondaryCache> secondary_cache =
  1269. std::make_shared<TestSecondaryCache>(2048, true);
  1270. std::shared_ptr<Cache> cache =
  1271. NewCache(1024 /* capacity */, 0 /* num_shard_bits */,
  1272. strict_capacity_limit, secondary_cache);
  1273. CacheKey k1 = CacheKey::CreateUniqueForCacheLifetime(cache.get());
  1274. CacheKey k2 = CacheKey::CreateUniqueForCacheLifetime(cache.get());
  1275. Random rnd(301);
  1276. std::string str1 = rnd.RandomString(1020);
  1277. TestItem* item1 = new TestItem(str1.data(), str1.length());
  1278. ASSERT_OK(cache->Insert(k1.AsSlice(), item1, GetHelper(), str1.length()));
  1279. std::string str2 = rnd.RandomString(1020);
  1280. TestItem* item2 = new TestItem(str2.data(), str2.length());
  1281. // k1 should be demoted to NVM
  1282. ASSERT_OK(cache->Insert(k2.AsSlice(), item2, GetHelper(), str2.length()));
  1283. Cache::Handle* handle2;
  1284. handle2 = cache->Lookup(k2.AsSlice(), GetHelper(),
  1285. /*context*/ this, Cache::Priority::LOW);
  1286. ASSERT_NE(handle2, nullptr);
  1287. // k1 lookup fails without secondary cache support
  1288. Cache::Handle* handle1;
  1289. handle1 = cache->Lookup(
  1290. k1.AsSlice(),
  1291. GetHelper(CacheEntryRole::kDataBlock, /*secondary_compatible=*/false),
  1292. /*context*/ this, Cache::Priority::LOW);
  1293. ASSERT_EQ(handle1, nullptr);
  1294. // k1 promotion can fail with strict_capacit_limit=true, but Lookup still
  1295. // succeeds using a standalone handle
  1296. handle1 = cache->Lookup(k1.AsSlice(), GetHelper(),
  1297. /*context*/ this, Cache::Priority::LOW);
  1298. ASSERT_NE(handle1, nullptr);
  1299. ASSERT_EQ(secondary_cache->num_inserts(), 1u);
  1300. ASSERT_EQ(secondary_cache->num_lookups(), 1u);
  1301. // Releasing k2's handle first, k2 is evicted from primary iff k1 promotion
  1302. // was charged to the cache (except HCC doesn't erase in Release() over
  1303. // capacity)
  1304. // FIXME: Insert to secondary from Release disabled
  1305. cache->Release(handle2);
  1306. cache->Release(handle1);
  1307. handle2 = cache->Lookup(
  1308. k2.AsSlice(),
  1309. GetHelper(CacheEntryRole::kDataBlock, /*secondary_compatible=*/false),
  1310. /*context*/ this, Cache::Priority::LOW);
  1311. if (strict_capacity_limit || IsHyperClock()) {
  1312. ASSERT_NE(handle2, nullptr);
  1313. cache->Release(handle2);
  1314. ASSERT_EQ(secondary_cache->num_inserts(), 1u);
  1315. } else {
  1316. ASSERT_EQ(handle2, nullptr);
  1317. // FIXME: Insert to secondary from Release disabled
  1318. // ASSERT_EQ(secondary_cache->num_inserts(), 2u);
  1319. ASSERT_EQ(secondary_cache->num_inserts(), 1u);
  1320. }
  1321. cache.reset();
  1322. secondary_cache.reset();
  1323. }
  1324. }
  1325. // In this test, the block cache size is set to 4096, after insert 6 KV-pairs
  1326. // and flush, there are 5 blocks in this SST file, 2 data blocks and 3 meta
  1327. // blocks. block_1 size is 4096 and block_2 size is 2056. The total size
  1328. // of the meta blocks are about 900 to 1000. Therefore, in any situation,
  1329. // if we try to insert block_1 to the block cache, it will always fails. Only
  1330. // block_2 will be successfully inserted into the block cache.
  1331. // CORRECTION: this is not quite right. block_1 can be inserted into the block
  1332. // cache because strict_capacity_limit=false, but it is removed from the cache
  1333. // in Release() because of being over-capacity, without demoting to secondary
  1334. // cache. FixedHyperClockCache doesn't check capacity on release (for
  1335. // efficiency) so can demote the over-capacity item to secondary cache. Also, we
  1336. // intend to add support for demotion in Release, but that currently causes too
  1337. // much unit test churn.
  1338. TEST_P(DBSecondaryCacheTest, TestSecondaryCacheCorrectness1) {
  1339. if (IsHyperClock()) {
  1340. // See CORRECTION above
  1341. ROCKSDB_GTEST_BYPASS("Test depends on LRUCache-specific behaviors");
  1342. return;
  1343. }
  1344. std::shared_ptr<TestSecondaryCache> secondary_cache(
  1345. new TestSecondaryCache(2048 * 1024));
  1346. std::shared_ptr<Cache> cache =
  1347. NewCache(4 * 1024 /* capacity */, 0 /* num_shard_bits */,
  1348. false /* strict_capacity_limit */, secondary_cache);
  1349. BlockBasedTableOptions table_options;
  1350. table_options.block_cache = cache;
  1351. table_options.block_size = 4 * 1024;
  1352. Options options = GetDefaultOptions();
  1353. options.create_if_missing = true;
  1354. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1355. options.env = fault_env_.get();
  1356. fault_fs_->SetFailGetUniqueId(true);
  1357. // Set the file paranoid check, so after flush, the file will be read
  1358. // all the blocks will be accessed.
  1359. options.paranoid_file_checks = true;
  1360. DestroyAndReopen(options);
  1361. Random rnd(301);
  1362. const int N = 6;
  1363. for (int i = 0; i < N; i++) {
  1364. std::string p_v = rnd.RandomString(1007);
  1365. ASSERT_OK(Put(Key(i), p_v));
  1366. }
  1367. ASSERT_OK(Flush());
  1368. // After Flush is successful, RocksDB will do the paranoid check for the new
  1369. // SST file. Meta blocks are always cached in the block cache and they
  1370. // will not be evicted. When block_2 is cache miss and read out, it is
  1371. // inserted to the block cache. Note that, block_1 is never successfully
  1372. // inserted to the block cache. Here are 2 lookups in the secondary cache
  1373. // for block_1 and block_2
  1374. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  1375. ASSERT_EQ(secondary_cache->num_lookups(), 2u);
  1376. Compact("a", "z");
  1377. // Compaction will create the iterator to scan the whole file. So all the
  1378. // blocks are needed. Meta blocks are always cached. When block_1 is read
  1379. // out, block_2 is evicted from block cache and inserted to secondary
  1380. // cache.
  1381. ASSERT_EQ(secondary_cache->num_inserts(), 1u);
  1382. ASSERT_EQ(secondary_cache->num_lookups(), 3u);
  1383. std::string v = Get(Key(0));
  1384. ASSERT_EQ(1007, v.size());
  1385. // The first data block is not in the cache, similarly, trigger the block
  1386. // cache Lookup and secondary cache lookup for block_1. But block_1 will not
  1387. // be inserted successfully due to the size. Currently, cache only has
  1388. // the meta blocks.
  1389. ASSERT_EQ(secondary_cache->num_inserts(), 1u);
  1390. ASSERT_EQ(secondary_cache->num_lookups(), 4u);
  1391. v = Get(Key(5));
  1392. ASSERT_EQ(1007, v.size());
  1393. // The second data block is not in the cache, similarly, trigger the block
  1394. // cache Lookup and secondary cache lookup for block_2 and block_2 is found
  1395. // in the secondary cache. Now block cache has block_2
  1396. ASSERT_EQ(secondary_cache->num_inserts(), 1u);
  1397. ASSERT_EQ(secondary_cache->num_lookups(), 5u);
  1398. v = Get(Key(5));
  1399. ASSERT_EQ(1007, v.size());
  1400. // block_2 is in the block cache. There is a block cache hit. No need to
  1401. // lookup or insert the secondary cache.
  1402. ASSERT_EQ(secondary_cache->num_inserts(), 1u);
  1403. ASSERT_EQ(secondary_cache->num_lookups(), 5u);
  1404. v = Get(Key(0));
  1405. ASSERT_EQ(1007, v.size());
  1406. // Lookup the first data block, not in the block cache, so lookup the
  1407. // secondary cache. Also not in the secondary cache. After Get, still
  1408. // block_1 is will not be cached.
  1409. ASSERT_EQ(secondary_cache->num_inserts(), 1u);
  1410. ASSERT_EQ(secondary_cache->num_lookups(), 6u);
  1411. v = Get(Key(0));
  1412. ASSERT_EQ(1007, v.size());
  1413. // Lookup the first data block, not in the block cache, so lookup the
  1414. // secondary cache. Also not in the secondary cache. After Get, still
  1415. // block_1 is will not be cached.
  1416. ASSERT_EQ(secondary_cache->num_inserts(), 1u);
  1417. ASSERT_EQ(secondary_cache->num_lookups(), 7u);
  1418. Destroy(options);
  1419. }
  1420. // In this test, the block cache size is set to 6100, after insert 6 KV-pairs
  1421. // and flush, there are 5 blocks in this SST file, 2 data blocks and 3 meta
  1422. // blocks. block_1 size is 4096 and block_2 size is 2056. The total size
  1423. // of the meta blocks are about 900 to 1000. Therefore, we can successfully
  1424. // insert and cache block_1 in the block cache (this is the different place
  1425. // from TestSecondaryCacheCorrectness1)
  1426. TEST_P(DBSecondaryCacheTest, TestSecondaryCacheCorrectness2) {
  1427. if (IsHyperClock()) {
  1428. ROCKSDB_GTEST_BYPASS("Test depends on LRUCache-specific behaviors");
  1429. return;
  1430. }
  1431. std::shared_ptr<TestSecondaryCache> secondary_cache(
  1432. new TestSecondaryCache(2048 * 1024));
  1433. std::shared_ptr<Cache> cache =
  1434. NewCache(6100 /* capacity */, 0 /* num_shard_bits */,
  1435. false /* strict_capacity_limit */, secondary_cache);
  1436. BlockBasedTableOptions table_options;
  1437. table_options.block_cache = cache;
  1438. table_options.block_size = 4 * 1024;
  1439. Options options = GetDefaultOptions();
  1440. options.create_if_missing = true;
  1441. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1442. options.paranoid_file_checks = true;
  1443. options.env = fault_env_.get();
  1444. fault_fs_->SetFailGetUniqueId(true);
  1445. DestroyAndReopen(options);
  1446. Random rnd(301);
  1447. const int N = 6;
  1448. for (int i = 0; i < N; i++) {
  1449. std::string p_v = rnd.RandomString(1007);
  1450. ASSERT_OK(Put(Key(i), p_v));
  1451. }
  1452. ASSERT_OK(Flush());
  1453. // After Flush is successful, RocksDB will do the paranoid check for the new
  1454. // SST file. Meta blocks are always cached in the block cache and they
  1455. // will not be evicted. When block_2 is cache miss and read out, it is
  1456. // inserted to the block cache. Thefore, block_1 is evicted from block
  1457. // cache and successfully inserted to the secondary cache. Here are 2
  1458. // lookups in the secondary cache for block_1 and block_2.
  1459. ASSERT_EQ(secondary_cache->num_inserts(), 1u);
  1460. ASSERT_EQ(secondary_cache->num_lookups(), 2u);
  1461. Compact("a", "z");
  1462. // Compaction will create the iterator to scan the whole file. So all the
  1463. // blocks are needed. After Flush, only block_2 is cached in block cache
  1464. // and block_1 is in the secondary cache. So when read block_1, it is
  1465. // read out from secondary cache and inserted to block cache. At the same
  1466. // time, block_2 is inserted to secondary cache. Now, secondary cache has
  1467. // both block_1 and block_2. After compaction, block_1 is in the cache.
  1468. ASSERT_EQ(secondary_cache->num_inserts(), 2u);
  1469. ASSERT_EQ(secondary_cache->num_lookups(), 3u);
  1470. std::string v = Get(Key(0));
  1471. ASSERT_EQ(1007, v.size());
  1472. // This Get needs to access block_1, since block_1 is cached in block cache
  1473. // there is no secondary cache lookup.
  1474. ASSERT_EQ(secondary_cache->num_inserts(), 2u);
  1475. ASSERT_EQ(secondary_cache->num_lookups(), 3u);
  1476. v = Get(Key(5));
  1477. ASSERT_EQ(1007, v.size());
  1478. // This Get needs to access block_2 which is not in the block cache. So
  1479. // it will lookup the secondary cache for block_2 and cache it in the
  1480. // block_cache.
  1481. ASSERT_EQ(secondary_cache->num_inserts(), 2u);
  1482. ASSERT_EQ(secondary_cache->num_lookups(), 4u);
  1483. v = Get(Key(5));
  1484. ASSERT_EQ(1007, v.size());
  1485. // This Get needs to access block_2 which is already in the block cache.
  1486. // No need to lookup secondary cache.
  1487. ASSERT_EQ(secondary_cache->num_inserts(), 2u);
  1488. ASSERT_EQ(secondary_cache->num_lookups(), 4u);
  1489. v = Get(Key(0));
  1490. ASSERT_EQ(1007, v.size());
  1491. // This Get needs to access block_1, since block_1 is not in block cache
  1492. // there is one econdary cache lookup. Then, block_1 is cached in the
  1493. // block cache.
  1494. ASSERT_EQ(secondary_cache->num_inserts(), 2u);
  1495. ASSERT_EQ(secondary_cache->num_lookups(), 5u);
  1496. v = Get(Key(0));
  1497. ASSERT_EQ(1007, v.size());
  1498. // This Get needs to access block_1, since block_1 is cached in block cache
  1499. // there is no secondary cache lookup.
  1500. ASSERT_EQ(secondary_cache->num_inserts(), 2u);
  1501. ASSERT_EQ(secondary_cache->num_lookups(), 5u);
  1502. Destroy(options);
  1503. }
  1504. // The block cache size is set to 1024*1024, after insert 6 KV-pairs
  1505. // and flush, there are 5 blocks in this SST file, 2 data blocks and 3 meta
  1506. // blocks. block_1 size is 4096 and block_2 size is 2056. The total size
  1507. // of the meta blocks are about 900 to 1000. Therefore, we can successfully
  1508. // cache all the blocks in the block cache and there is not secondary cache
  1509. // insertion. 2 lookup is needed for the blocks.
  1510. TEST_P(DBSecondaryCacheTest, NoSecondaryCacheInsertion) {
  1511. std::shared_ptr<TestSecondaryCache> secondary_cache(
  1512. new TestSecondaryCache(2048 * 1024));
  1513. std::shared_ptr<Cache> cache =
  1514. NewCache(1024 * 1024 /* capacity */, 0 /* num_shard_bits */,
  1515. false /* strict_capacity_limit */, secondary_cache);
  1516. BlockBasedTableOptions table_options;
  1517. table_options.block_cache = cache;
  1518. table_options.block_size = 4 * 1024;
  1519. Options options = GetDefaultOptions();
  1520. options.create_if_missing = true;
  1521. options.paranoid_file_checks = true;
  1522. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1523. options.env = fault_env_.get();
  1524. fault_fs_->SetFailGetUniqueId(true);
  1525. DestroyAndReopen(options);
  1526. Random rnd(301);
  1527. const int N = 6;
  1528. for (int i = 0; i < N; i++) {
  1529. std::string p_v = rnd.RandomString(1000);
  1530. ASSERT_OK(Put(Key(i), p_v));
  1531. }
  1532. ASSERT_OK(Flush());
  1533. // After Flush is successful, RocksDB will do the paranoid check for the new
  1534. // SST file. Meta blocks are always cached in the block cache and they
  1535. // will not be evicted. Now, block cache is large enough, it cache
  1536. // both block_1 and block_2. When first time read block_1 and block_2
  1537. // there are cache misses. So 2 secondary cache lookups are needed for
  1538. // the 2 blocks
  1539. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  1540. ASSERT_EQ(secondary_cache->num_lookups(), 2u);
  1541. Compact("a", "z");
  1542. // Compaction will iterate the whole SST file. Since all the data blocks
  1543. // are in the block cache. No need to lookup the secondary cache.
  1544. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  1545. ASSERT_EQ(secondary_cache->num_lookups(), 2u);
  1546. std::string v = Get(Key(0));
  1547. ASSERT_EQ(1000, v.size());
  1548. // Since the block cache is large enough, all the blocks are cached. we
  1549. // do not need to lookup the seondary cache.
  1550. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  1551. ASSERT_EQ(secondary_cache->num_lookups(), 2u);
  1552. Destroy(options);
  1553. }
  1554. TEST_P(DBSecondaryCacheTest, SecondaryCacheIntensiveTesting) {
  1555. std::shared_ptr<TestSecondaryCache> secondary_cache(
  1556. new TestSecondaryCache(2048 * 1024));
  1557. std::shared_ptr<Cache> cache =
  1558. NewCache(8 * 1024 /* capacity */, 0 /* num_shard_bits */,
  1559. false /* strict_capacity_limit */, secondary_cache);
  1560. BlockBasedTableOptions table_options;
  1561. table_options.block_cache = cache;
  1562. table_options.block_size = 4 * 1024;
  1563. Options options = GetDefaultOptions();
  1564. options.create_if_missing = true;
  1565. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1566. options.env = fault_env_.get();
  1567. fault_fs_->SetFailGetUniqueId(true);
  1568. DestroyAndReopen(options);
  1569. Random rnd(301);
  1570. const int N = 256;
  1571. for (int i = 0; i < N; i++) {
  1572. std::string p_v = rnd.RandomString(1000);
  1573. ASSERT_OK(Put(Key(i), p_v));
  1574. }
  1575. ASSERT_OK(Flush());
  1576. Compact("a", "z");
  1577. Random r_index(47);
  1578. std::string v;
  1579. for (int i = 0; i < 1000; i++) {
  1580. uint32_t key_i = r_index.Next() % N;
  1581. v = Get(Key(key_i));
  1582. }
  1583. // We have over 200 data blocks there will be multiple insertion
  1584. // and lookups.
  1585. ASSERT_GE(secondary_cache->num_inserts(), 1u);
  1586. ASSERT_GE(secondary_cache->num_lookups(), 1u);
  1587. Destroy(options);
  1588. }
  1589. // In this test, the block cache size is set to 4096, after insert 6 KV-pairs
  1590. // and flush, there are 5 blocks in this SST file, 2 data blocks and 3 meta
  1591. // blocks. block_1 size is 4096 and block_2 size is 2056. The total size
  1592. // of the meta blocks are about 900 to 1000. Therefore, in any situation,
  1593. // if we try to insert block_1 to the block cache, it will always fails. Only
  1594. // block_2 will be successfully inserted into the block cache.
  1595. TEST_P(DBSecondaryCacheTest, SecondaryCacheFailureTest) {
  1596. if (IsHyperClock()) {
  1597. ROCKSDB_GTEST_BYPASS("Test depends on LRUCache-specific behaviors");
  1598. return;
  1599. }
  1600. std::shared_ptr<TestSecondaryCache> secondary_cache(
  1601. new TestSecondaryCache(2048 * 1024));
  1602. std::shared_ptr<Cache> cache =
  1603. NewCache(4 * 1024 /* capacity */, 0 /* num_shard_bits */,
  1604. false /* strict_capacity_limit */, secondary_cache);
  1605. BlockBasedTableOptions table_options;
  1606. table_options.block_cache = cache;
  1607. table_options.block_size = 4 * 1024;
  1608. Options options = GetDefaultOptions();
  1609. options.create_if_missing = true;
  1610. options.paranoid_file_checks = true;
  1611. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1612. options.env = fault_env_.get();
  1613. fault_fs_->SetFailGetUniqueId(true);
  1614. DestroyAndReopen(options);
  1615. Random rnd(301);
  1616. const int N = 6;
  1617. for (int i = 0; i < N; i++) {
  1618. std::string p_v = rnd.RandomString(1007);
  1619. ASSERT_OK(Put(Key(i), p_v));
  1620. }
  1621. ASSERT_OK(Flush());
  1622. // After Flush is successful, RocksDB will do the paranoid check for the new
  1623. // SST file. Meta blocks are always cached in the block cache and they
  1624. // will not be evicted. When block_2 is cache miss and read out, it is
  1625. // inserted to the block cache. Note that, block_1 is never successfully
  1626. // inserted to the block cache. Here are 2 lookups in the secondary cache
  1627. // for block_1 and block_2
  1628. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  1629. ASSERT_EQ(secondary_cache->num_lookups(), 2u);
  1630. // Fail the insertion, in LRU cache, the secondary insertion returned status
  1631. // is not checked, therefore, the DB will not be influenced.
  1632. secondary_cache->InjectFailure();
  1633. Compact("a", "z");
  1634. // Compaction will create the iterator to scan the whole file. So all the
  1635. // blocks are needed. Meta blocks are always cached. When block_1 is read
  1636. // out, block_2 is evicted from block cache and inserted to secondary
  1637. // cache.
  1638. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  1639. ASSERT_EQ(secondary_cache->num_lookups(), 3u);
  1640. std::string v = Get(Key(0));
  1641. ASSERT_EQ(1007, v.size());
  1642. // The first data block is not in the cache, similarly, trigger the block
  1643. // cache Lookup and secondary cache lookup for block_1. But block_1 will not
  1644. // be inserted successfully due to the size. Currently, cache only has
  1645. // the meta blocks.
  1646. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  1647. ASSERT_EQ(secondary_cache->num_lookups(), 4u);
  1648. v = Get(Key(5));
  1649. ASSERT_EQ(1007, v.size());
  1650. // The second data block is not in the cache, similarly, trigger the block
  1651. // cache Lookup and secondary cache lookup for block_2 and block_2 is found
  1652. // in the secondary cache. Now block cache has block_2
  1653. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  1654. ASSERT_EQ(secondary_cache->num_lookups(), 5u);
  1655. v = Get(Key(5));
  1656. ASSERT_EQ(1007, v.size());
  1657. // block_2 is in the block cache. There is a block cache hit. No need to
  1658. // lookup or insert the secondary cache.
  1659. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  1660. ASSERT_EQ(secondary_cache->num_lookups(), 5u);
  1661. v = Get(Key(0));
  1662. ASSERT_EQ(1007, v.size());
  1663. // Lookup the first data block, not in the block cache, so lookup the
  1664. // secondary cache. Also not in the secondary cache. After Get, still
  1665. // block_1 is will not be cached.
  1666. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  1667. ASSERT_EQ(secondary_cache->num_lookups(), 6u);
  1668. v = Get(Key(0));
  1669. ASSERT_EQ(1007, v.size());
  1670. // Lookup the first data block, not in the block cache, so lookup the
  1671. // secondary cache. Also not in the secondary cache. After Get, still
  1672. // block_1 is will not be cached.
  1673. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  1674. ASSERT_EQ(secondary_cache->num_lookups(), 7u);
  1675. secondary_cache->ResetInjectFailure();
  1676. Destroy(options);
  1677. }
  1678. TEST_P(BasicSecondaryCacheTest, BasicWaitAllTest) {
  1679. std::shared_ptr<TestSecondaryCache> secondary_cache =
  1680. std::make_shared<TestSecondaryCache>(32 * 1024);
  1681. std::shared_ptr<Cache> cache =
  1682. NewCache(1024 /* capacity */, 2 /* num_shard_bits */,
  1683. false /* strict_capacity_limit */, secondary_cache);
  1684. const int num_keys = 32;
  1685. OffsetableCacheKey ock{"foo", "bar", 1};
  1686. Random rnd(301);
  1687. std::vector<std::string> values;
  1688. for (int i = 0; i < num_keys; ++i) {
  1689. std::string str = rnd.RandomString(1020);
  1690. values.emplace_back(str);
  1691. TestItem* item = new TestItem(str.data(), str.length());
  1692. ASSERT_OK(cache->Insert(ock.WithOffset(i).AsSlice(), item, GetHelper(),
  1693. str.length()));
  1694. }
  1695. // Force all entries to be evicted to the secondary cache
  1696. if (IsHyperClock()) {
  1697. // HCC doesn't respond immediately to SetCapacity
  1698. for (int i = 9000; i < 9030; ++i) {
  1699. ASSERT_OK(cache->Insert(ock.WithOffset(i).AsSlice(), nullptr,
  1700. &kNoopCacheItemHelper, 256));
  1701. }
  1702. } else {
  1703. cache->SetCapacity(0);
  1704. }
  1705. ASSERT_EQ(secondary_cache->num_inserts(), 32u);
  1706. cache->SetCapacity(32 * 1024);
  1707. secondary_cache->SetResultMap(
  1708. {{ock.WithOffset(3).AsSlice().ToString(),
  1709. TestSecondaryCache::ResultType::DEFER},
  1710. {ock.WithOffset(4).AsSlice().ToString(),
  1711. TestSecondaryCache::ResultType::DEFER_AND_FAIL},
  1712. {ock.WithOffset(5).AsSlice().ToString(),
  1713. TestSecondaryCache::ResultType::FAIL}});
  1714. std::array<Cache::AsyncLookupHandle, 6> async_handles;
  1715. std::array<CacheKey, 6> cache_keys;
  1716. for (size_t i = 0; i < async_handles.size(); ++i) {
  1717. auto& ah = async_handles[i];
  1718. cache_keys[i] = ock.WithOffset(i);
  1719. ah.key = cache_keys[i].AsSlice();
  1720. ah.helper = GetHelper();
  1721. ah.create_context = this;
  1722. ah.priority = Cache::Priority::LOW;
  1723. cache->StartAsyncLookup(ah);
  1724. }
  1725. cache->WaitAll(async_handles.data(), async_handles.size());
  1726. for (size_t i = 0; i < async_handles.size(); ++i) {
  1727. SCOPED_TRACE("i = " + std::to_string(i));
  1728. Cache::Handle* result = async_handles[i].Result();
  1729. if (i == 4 || i == 5) {
  1730. ASSERT_EQ(result, nullptr);
  1731. continue;
  1732. } else {
  1733. ASSERT_NE(result, nullptr);
  1734. TestItem* item = static_cast<TestItem*>(cache->Value(result));
  1735. ASSERT_EQ(item->ToString(), values[i]);
  1736. }
  1737. cache->Release(result);
  1738. }
  1739. cache.reset();
  1740. secondary_cache.reset();
  1741. }
  1742. // In this test, we have one KV pair per data block. We indirectly determine
  1743. // the cache key associated with each data block (and thus each KV) by using
  1744. // a sync point callback in TestSecondaryCache::Lookup. We then control the
  1745. // lookup result by setting the ResultMap.
  1746. TEST_P(DBSecondaryCacheTest, TestSecondaryCacheMultiGet) {
  1747. if (IsHyperClock()) {
  1748. ROCKSDB_GTEST_BYPASS("Test depends on LRUCache-specific behaviors");
  1749. return;
  1750. }
  1751. std::shared_ptr<TestSecondaryCache> secondary_cache(
  1752. new TestSecondaryCache(2048 * 1024));
  1753. std::shared_ptr<Cache> cache =
  1754. NewCache(1 << 20 /* capacity */, 0 /* num_shard_bits */,
  1755. false /* strict_capacity_limit */, secondary_cache);
  1756. BlockBasedTableOptions table_options;
  1757. table_options.block_cache = cache;
  1758. table_options.block_size = 4 * 1024;
  1759. table_options.cache_index_and_filter_blocks = false;
  1760. Options options = GetDefaultOptions();
  1761. options.create_if_missing = true;
  1762. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1763. options.paranoid_file_checks = true;
  1764. DestroyAndReopen(options);
  1765. Random rnd(301);
  1766. const int N = 8;
  1767. std::vector<std::string> keys;
  1768. for (int i = 0; i < N; i++) {
  1769. std::string p_v = rnd.RandomString(4000);
  1770. keys.emplace_back(p_v);
  1771. ASSERT_OK(Put(Key(i), p_v));
  1772. }
  1773. ASSERT_OK(Flush());
  1774. // After Flush is successful, RocksDB does the paranoid check for the new
  1775. // SST file. This will try to lookup all data blocks in the secondary
  1776. // cache.
  1777. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  1778. ASSERT_EQ(secondary_cache->num_lookups(), 8u);
  1779. cache->SetCapacity(0);
  1780. ASSERT_EQ(secondary_cache->num_inserts(), 8u);
  1781. cache->SetCapacity(1 << 20);
  1782. std::vector<std::string> cache_keys;
  1783. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1784. "TestSecondaryCache::Lookup", [&cache_keys](void* key) -> void {
  1785. cache_keys.emplace_back(*(static_cast<std::string*>(key)));
  1786. });
  1787. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  1788. for (int i = 0; i < N; ++i) {
  1789. std::string v = Get(Key(i));
  1790. ASSERT_EQ(4000, v.size());
  1791. ASSERT_EQ(v, keys[i]);
  1792. }
  1793. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  1794. ASSERT_EQ(secondary_cache->num_lookups(), 16u);
  1795. cache->SetCapacity(0);
  1796. cache->SetCapacity(1 << 20);
  1797. ASSERT_EQ(Get(Key(2)), keys[2]);
  1798. ASSERT_EQ(Get(Key(7)), keys[7]);
  1799. secondary_cache->SetResultMap(
  1800. {{cache_keys[3], TestSecondaryCache::ResultType::DEFER},
  1801. {cache_keys[4], TestSecondaryCache::ResultType::DEFER_AND_FAIL},
  1802. {cache_keys[5], TestSecondaryCache::ResultType::FAIL}});
  1803. std::vector<std::string> mget_keys(
  1804. {Key(0), Key(1), Key(2), Key(3), Key(4), Key(5), Key(6), Key(7)});
  1805. std::vector<PinnableSlice> values(mget_keys.size());
  1806. std::vector<Status> s(keys.size());
  1807. std::vector<Slice> key_slices;
  1808. for (const std::string& key : mget_keys) {
  1809. key_slices.emplace_back(key);
  1810. }
  1811. uint32_t num_lookups = secondary_cache->num_lookups();
  1812. dbfull()->MultiGet(ReadOptions(), dbfull()->DefaultColumnFamily(),
  1813. key_slices.size(), key_slices.data(), values.data(),
  1814. s.data(), false);
  1815. ASSERT_EQ(secondary_cache->num_lookups(), num_lookups + 5);
  1816. for (int i = 0; i < N; ++i) {
  1817. ASSERT_OK(s[i]);
  1818. ASSERT_EQ(values[i].ToString(), keys[i]);
  1819. values[i].Reset();
  1820. }
  1821. Destroy(options);
  1822. }
  1823. class CacheWithStats : public CacheWrapper {
  1824. public:
  1825. using CacheWrapper::CacheWrapper;
  1826. static const char* kClassName() { return "CacheWithStats"; }
  1827. const char* Name() const override { return kClassName(); }
  1828. Status Insert(const Slice& key, Cache::ObjectPtr value,
  1829. const CacheItemHelper* helper, size_t charge,
  1830. Handle** handle = nullptr, Priority priority = Priority::LOW,
  1831. const Slice& /*compressed*/ = Slice(),
  1832. CompressionType /*type*/ = kNoCompression) override {
  1833. insert_count_++;
  1834. return target_->Insert(key, value, helper, charge, handle, priority);
  1835. }
  1836. Handle* Lookup(const Slice& key, const CacheItemHelper* helper,
  1837. CreateContext* create_context, Priority priority,
  1838. Statistics* stats = nullptr) override {
  1839. lookup_count_++;
  1840. return target_->Lookup(key, helper, create_context, priority, stats);
  1841. }
  1842. uint32_t GetInsertCount() { return insert_count_; }
  1843. uint32_t GetLookupcount() { return lookup_count_; }
  1844. void ResetCount() {
  1845. insert_count_ = 0;
  1846. lookup_count_ = 0;
  1847. }
  1848. private:
  1849. uint32_t insert_count_ = 0;
  1850. uint32_t lookup_count_ = 0;
  1851. };
  1852. TEST_P(DBSecondaryCacheTest, LRUCacheDumpLoadBasic) {
  1853. std::shared_ptr<Cache> base_cache =
  1854. NewCache(1024 * 1024 /* capacity */, 0 /* num_shard_bits */,
  1855. false /* strict_capacity_limit */);
  1856. std::shared_ptr<CacheWithStats> cache =
  1857. std::make_shared<CacheWithStats>(base_cache);
  1858. BlockBasedTableOptions table_options;
  1859. table_options.block_cache = cache;
  1860. table_options.block_size = 4 * 1024;
  1861. Options options = GetDefaultOptions();
  1862. options.create_if_missing = true;
  1863. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1864. options.env = fault_env_.get();
  1865. DestroyAndReopen(options);
  1866. fault_fs_->SetFailGetUniqueId(true);
  1867. Random rnd(301);
  1868. const int N = 256;
  1869. std::vector<std::string> value;
  1870. char buf[1000];
  1871. memset(buf, 'a', 1000);
  1872. value.resize(N);
  1873. for (int i = 0; i < N; i++) {
  1874. // std::string p_v = rnd.RandomString(1000);
  1875. std::string p_v(buf, 1000);
  1876. value[i] = p_v;
  1877. ASSERT_OK(Put(Key(i), p_v));
  1878. }
  1879. ASSERT_OK(Flush());
  1880. Compact("a", "z");
  1881. // do th eread for all the key value pairs, so all the blocks should be in
  1882. // cache
  1883. uint32_t start_insert = cache->GetInsertCount();
  1884. uint32_t start_lookup = cache->GetLookupcount();
  1885. std::string v;
  1886. for (int i = 0; i < N; i++) {
  1887. v = Get(Key(i));
  1888. ASSERT_EQ(v, value[i]);
  1889. }
  1890. uint32_t dump_insert = cache->GetInsertCount() - start_insert;
  1891. uint32_t dump_lookup = cache->GetLookupcount() - start_lookup;
  1892. ASSERT_EQ(63,
  1893. static_cast<int>(dump_insert)); // the insert in the block cache
  1894. ASSERT_EQ(256,
  1895. static_cast<int>(dump_lookup)); // the lookup in the block cache
  1896. // We have enough blocks in the block cache
  1897. CacheDumpOptions cd_options;
  1898. cd_options.clock = fault_env_->GetSystemClock().get();
  1899. std::string dump_path = db_->GetName() + "/cache_dump";
  1900. std::unique_ptr<CacheDumpWriter> dump_writer;
  1901. Status s = NewToFileCacheDumpWriter(fault_fs_, FileOptions(), dump_path,
  1902. &dump_writer);
  1903. ASSERT_OK(s);
  1904. std::unique_ptr<CacheDumper> cache_dumper;
  1905. s = NewDefaultCacheDumper(cd_options, cache, std::move(dump_writer),
  1906. &cache_dumper);
  1907. ASSERT_OK(s);
  1908. std::vector<DB*> db_list;
  1909. db_list.push_back(db_);
  1910. s = cache_dumper->SetDumpFilter(db_list);
  1911. ASSERT_OK(s);
  1912. s = cache_dumper->DumpCacheEntriesToWriter();
  1913. ASSERT_OK(s);
  1914. cache_dumper.reset();
  1915. // we have a new cache it is empty, then, before we do the Get, we do the
  1916. // dumpload
  1917. std::shared_ptr<TestSecondaryCache> secondary_cache =
  1918. std::make_shared<TestSecondaryCache>(2048 * 1024, true);
  1919. // This time with secondary cache
  1920. base_cache = NewCache(1024 * 1024 /* capacity */, 0 /* num_shard_bits */,
  1921. false /* strict_capacity_limit */, secondary_cache);
  1922. cache = std::make_shared<CacheWithStats>(base_cache);
  1923. table_options.block_cache = cache;
  1924. table_options.block_size = 4 * 1024;
  1925. options.create_if_missing = true;
  1926. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1927. options.env = fault_env_.get();
  1928. // start to load the data to new block cache
  1929. start_insert = secondary_cache->num_inserts();
  1930. start_lookup = secondary_cache->num_lookups();
  1931. std::unique_ptr<CacheDumpReader> dump_reader;
  1932. s = NewFromFileCacheDumpReader(fault_fs_, FileOptions(), dump_path,
  1933. &dump_reader);
  1934. ASSERT_OK(s);
  1935. std::unique_ptr<CacheDumpedLoader> cache_loader;
  1936. s = NewDefaultCacheDumpedLoader(cd_options, table_options, secondary_cache,
  1937. std::move(dump_reader), &cache_loader);
  1938. ASSERT_OK(s);
  1939. s = cache_loader->RestoreCacheEntriesToSecondaryCache();
  1940. ASSERT_OK(s);
  1941. uint32_t load_insert = secondary_cache->num_inserts() - start_insert;
  1942. uint32_t load_lookup = secondary_cache->num_lookups() - start_lookup;
  1943. // check the number we inserted
  1944. ASSERT_EQ(64, static_cast<int>(load_insert));
  1945. ASSERT_EQ(0, static_cast<int>(load_lookup));
  1946. ASSERT_OK(s);
  1947. Reopen(options);
  1948. // After load, we do the Get again
  1949. start_insert = secondary_cache->num_inserts();
  1950. start_lookup = secondary_cache->num_lookups();
  1951. uint32_t cache_insert = cache->GetInsertCount();
  1952. uint32_t cache_lookup = cache->GetLookupcount();
  1953. for (int i = 0; i < N; i++) {
  1954. v = Get(Key(i));
  1955. ASSERT_EQ(v, value[i]);
  1956. }
  1957. uint32_t final_insert = secondary_cache->num_inserts() - start_insert;
  1958. uint32_t final_lookup = secondary_cache->num_lookups() - start_lookup;
  1959. // no insert to secondary cache
  1960. ASSERT_EQ(0, static_cast<int>(final_insert));
  1961. // lookup the secondary to get all blocks
  1962. ASSERT_EQ(64, static_cast<int>(final_lookup));
  1963. uint32_t block_insert = cache->GetInsertCount() - cache_insert;
  1964. uint32_t block_lookup = cache->GetLookupcount() - cache_lookup;
  1965. // Check the new block cache insert and lookup, should be no insert since all
  1966. // blocks are from the secondary cache.
  1967. ASSERT_EQ(0, static_cast<int>(block_insert));
  1968. ASSERT_EQ(256, static_cast<int>(block_lookup));
  1969. fault_fs_->SetFailGetUniqueId(false);
  1970. Destroy(options);
  1971. }
  1972. TEST_P(DBSecondaryCacheTest, LRUCacheDumpLoadWithFilter) {
  1973. std::shared_ptr<Cache> base_cache =
  1974. NewCache(1024 * 1024 /* capacity */, 0 /* num_shard_bits */,
  1975. false /* strict_capacity_limit */);
  1976. std::shared_ptr<CacheWithStats> cache =
  1977. std::make_shared<CacheWithStats>(base_cache);
  1978. BlockBasedTableOptions table_options;
  1979. table_options.block_cache = cache;
  1980. table_options.block_size = 4 * 1024;
  1981. Options options = GetDefaultOptions();
  1982. options.create_if_missing = true;
  1983. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1984. options.env = fault_env_.get();
  1985. std::string dbname1 = test::PerThreadDBPath("db_1");
  1986. ASSERT_OK(DestroyDB(dbname1, options));
  1987. DB* db1 = nullptr;
  1988. ASSERT_OK(DB::Open(options, dbname1, &db1));
  1989. std::string dbname2 = test::PerThreadDBPath("db_2");
  1990. ASSERT_OK(DestroyDB(dbname2, options));
  1991. DB* db2 = nullptr;
  1992. ASSERT_OK(DB::Open(options, dbname2, &db2));
  1993. fault_fs_->SetFailGetUniqueId(true);
  1994. // write the KVs to db1
  1995. Random rnd(301);
  1996. const int N = 256;
  1997. std::vector<std::string> value1;
  1998. WriteOptions wo;
  1999. char buf[1000];
  2000. memset(buf, 'a', 1000);
  2001. value1.resize(N);
  2002. for (int i = 0; i < N; i++) {
  2003. std::string p_v(buf, 1000);
  2004. value1[i] = p_v;
  2005. ASSERT_OK(db1->Put(wo, Key(i), p_v));
  2006. }
  2007. ASSERT_OK(db1->Flush(FlushOptions()));
  2008. Slice bg("a");
  2009. Slice ed("b");
  2010. ASSERT_OK(db1->CompactRange(CompactRangeOptions(), &bg, &ed));
  2011. // Write the KVs to DB2
  2012. std::vector<std::string> value2;
  2013. memset(buf, 'b', 1000);
  2014. value2.resize(N);
  2015. for (int i = 0; i < N; i++) {
  2016. std::string p_v(buf, 1000);
  2017. value2[i] = p_v;
  2018. ASSERT_OK(db2->Put(wo, Key(i), p_v));
  2019. }
  2020. ASSERT_OK(db2->Flush(FlushOptions()));
  2021. ASSERT_OK(db2->CompactRange(CompactRangeOptions(), &bg, &ed));
  2022. // do th eread for all the key value pairs, so all the blocks should be in
  2023. // cache
  2024. uint32_t start_insert = cache->GetInsertCount();
  2025. uint32_t start_lookup = cache->GetLookupcount();
  2026. ReadOptions ro;
  2027. std::string v;
  2028. for (int i = 0; i < N; i++) {
  2029. ASSERT_OK(db1->Get(ro, Key(i), &v));
  2030. ASSERT_EQ(v, value1[i]);
  2031. }
  2032. for (int i = 0; i < N; i++) {
  2033. ASSERT_OK(db2->Get(ro, Key(i), &v));
  2034. ASSERT_EQ(v, value2[i]);
  2035. }
  2036. uint32_t dump_insert = cache->GetInsertCount() - start_insert;
  2037. uint32_t dump_lookup = cache->GetLookupcount() - start_lookup;
  2038. ASSERT_EQ(128,
  2039. static_cast<int>(dump_insert)); // the insert in the block cache
  2040. ASSERT_EQ(512,
  2041. static_cast<int>(dump_lookup)); // the lookup in the block cache
  2042. // We have enough blocks in the block cache
  2043. CacheDumpOptions cd_options;
  2044. cd_options.clock = fault_env_->GetSystemClock().get();
  2045. std::string dump_path = db1->GetName() + "/cache_dump";
  2046. std::unique_ptr<CacheDumpWriter> dump_writer;
  2047. Status s = NewToFileCacheDumpWriter(fault_fs_, FileOptions(), dump_path,
  2048. &dump_writer);
  2049. ASSERT_OK(s);
  2050. std::unique_ptr<CacheDumper> cache_dumper;
  2051. s = NewDefaultCacheDumper(cd_options, cache, std::move(dump_writer),
  2052. &cache_dumper);
  2053. ASSERT_OK(s);
  2054. std::vector<DB*> db_list;
  2055. db_list.push_back(db1);
  2056. s = cache_dumper->SetDumpFilter(db_list);
  2057. ASSERT_OK(s);
  2058. s = cache_dumper->DumpCacheEntriesToWriter();
  2059. ASSERT_OK(s);
  2060. cache_dumper.reset();
  2061. // we have a new cache it is empty, then, before we do the Get, we do the
  2062. // dumpload
  2063. std::shared_ptr<TestSecondaryCache> secondary_cache =
  2064. std::make_shared<TestSecondaryCache>(2048 * 1024, true);
  2065. // This time with secondary_cache
  2066. base_cache = NewCache(1024 * 1024 /* capacity */, 0 /* num_shard_bits */,
  2067. false /* strict_capacity_limit */, secondary_cache);
  2068. cache = std::make_shared<CacheWithStats>(base_cache);
  2069. table_options.block_cache = cache;
  2070. table_options.block_size = 4 * 1024;
  2071. options.create_if_missing = true;
  2072. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2073. options.env = fault_env_.get();
  2074. // Start the cache loading process
  2075. start_insert = secondary_cache->num_inserts();
  2076. start_lookup = secondary_cache->num_lookups();
  2077. std::unique_ptr<CacheDumpReader> dump_reader;
  2078. s = NewFromFileCacheDumpReader(fault_fs_, FileOptions(), dump_path,
  2079. &dump_reader);
  2080. ASSERT_OK(s);
  2081. std::unique_ptr<CacheDumpedLoader> cache_loader;
  2082. s = NewDefaultCacheDumpedLoader(cd_options, table_options, secondary_cache,
  2083. std::move(dump_reader), &cache_loader);
  2084. ASSERT_OK(s);
  2085. s = cache_loader->RestoreCacheEntriesToSecondaryCache();
  2086. ASSERT_OK(s);
  2087. uint32_t load_insert = secondary_cache->num_inserts() - start_insert;
  2088. uint32_t load_lookup = secondary_cache->num_lookups() - start_lookup;
  2089. // check the number we inserted
  2090. ASSERT_EQ(64, static_cast<int>(load_insert));
  2091. ASSERT_EQ(0, static_cast<int>(load_lookup));
  2092. ASSERT_OK(s);
  2093. ASSERT_OK(db1->Close());
  2094. delete db1;
  2095. ASSERT_OK(DB::Open(options, dbname1, &db1));
  2096. // After load, we do the Get again. To validate the cache, we do not allow any
  2097. // I/O, so we set the file system to false.
  2098. IOStatus error_msg = IOStatus::IOError("Retryable IO Error");
  2099. fault_fs_->SetFilesystemActive(false, error_msg);
  2100. start_insert = secondary_cache->num_inserts();
  2101. start_lookup = secondary_cache->num_lookups();
  2102. uint32_t cache_insert = cache->GetInsertCount();
  2103. uint32_t cache_lookup = cache->GetLookupcount();
  2104. for (int i = 0; i < N; i++) {
  2105. ASSERT_OK(db1->Get(ro, Key(i), &v));
  2106. ASSERT_EQ(v, value1[i]);
  2107. }
  2108. uint32_t final_insert = secondary_cache->num_inserts() - start_insert;
  2109. uint32_t final_lookup = secondary_cache->num_lookups() - start_lookup;
  2110. // no insert to secondary cache
  2111. ASSERT_EQ(0, static_cast<int>(final_insert));
  2112. // lookup the secondary to get all blocks
  2113. ASSERT_EQ(64, static_cast<int>(final_lookup));
  2114. uint32_t block_insert = cache->GetInsertCount() - cache_insert;
  2115. uint32_t block_lookup = cache->GetLookupcount() - cache_lookup;
  2116. // Check the new block cache insert and lookup, should be no insert since all
  2117. // blocks are from the secondary cache.
  2118. ASSERT_EQ(0, static_cast<int>(block_insert));
  2119. ASSERT_EQ(256, static_cast<int>(block_lookup));
  2120. fault_fs_->SetFailGetUniqueId(false);
  2121. fault_fs_->SetFilesystemActive(true);
  2122. delete db1;
  2123. delete db2;
  2124. ASSERT_OK(DestroyDB(dbname1, options));
  2125. ASSERT_OK(DestroyDB(dbname2, options));
  2126. }
  2127. // Test the option not to use the secondary cache in a certain DB.
  2128. TEST_P(DBSecondaryCacheTest, TestSecondaryCacheOptionBasic) {
  2129. std::shared_ptr<TestSecondaryCache> secondary_cache(
  2130. new TestSecondaryCache(2048 * 1024));
  2131. std::shared_ptr<Cache> cache =
  2132. NewCache(4 * 1024 /* capacity */, 0 /* num_shard_bits */,
  2133. false /* strict_capacity_limit */, secondary_cache);
  2134. BlockBasedTableOptions table_options;
  2135. table_options.block_cache = cache;
  2136. table_options.block_size = 4 * 1024;
  2137. Options options = GetDefaultOptions();
  2138. options.create_if_missing = true;
  2139. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2140. options.env = fault_env_.get();
  2141. fault_fs_->SetFailGetUniqueId(true);
  2142. options.lowest_used_cache_tier = CacheTier::kVolatileTier;
  2143. // Set the file paranoid check, so after flush, the file will be read
  2144. // all the blocks will be accessed.
  2145. options.paranoid_file_checks = true;
  2146. DestroyAndReopen(options);
  2147. Random rnd(301);
  2148. const int N = 6;
  2149. for (int i = 0; i < N; i++) {
  2150. std::string p_v = rnd.RandomString(1007);
  2151. ASSERT_OK(Put(Key(i), p_v));
  2152. }
  2153. ASSERT_OK(Flush());
  2154. for (int i = 0; i < N; i++) {
  2155. std::string p_v = rnd.RandomString(1007);
  2156. ASSERT_OK(Put(Key(i + 70), p_v));
  2157. }
  2158. ASSERT_OK(Flush());
  2159. // Flush will trigger the paranoid check and read blocks. But only block cache
  2160. // will be read. No operations for secondary cache.
  2161. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  2162. ASSERT_EQ(secondary_cache->num_lookups(), 0u);
  2163. Compact("a", "z");
  2164. // Compaction will also insert and evict blocks, no operations to the block
  2165. // cache. No operations for secondary cache.
  2166. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  2167. ASSERT_EQ(secondary_cache->num_lookups(), 0u);
  2168. std::string v = Get(Key(0));
  2169. ASSERT_EQ(1007, v.size());
  2170. // Check the data in first block. Cache miss, direclty read from SST file.
  2171. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  2172. ASSERT_EQ(secondary_cache->num_lookups(), 0u);
  2173. v = Get(Key(5));
  2174. ASSERT_EQ(1007, v.size());
  2175. // Check the second block.
  2176. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  2177. ASSERT_EQ(secondary_cache->num_lookups(), 0u);
  2178. v = Get(Key(5));
  2179. ASSERT_EQ(1007, v.size());
  2180. // block cache hit
  2181. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  2182. ASSERT_EQ(secondary_cache->num_lookups(), 0u);
  2183. v = Get(Key(70));
  2184. ASSERT_EQ(1007, v.size());
  2185. // Check the first block in the second SST file. Cache miss and trigger SST
  2186. // file read. No operations for secondary cache.
  2187. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  2188. ASSERT_EQ(secondary_cache->num_lookups(), 0u);
  2189. v = Get(Key(75));
  2190. ASSERT_EQ(1007, v.size());
  2191. // Check the second block in the second SST file. Cache miss and trigger SST
  2192. // file read. No operations for secondary cache.
  2193. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  2194. ASSERT_EQ(secondary_cache->num_lookups(), 0u);
  2195. Destroy(options);
  2196. }
  2197. // We disable the secondary cache in DBOptions at first. Close and reopen the DB
  2198. // with new options, which set the lowest_used_cache_tier to
  2199. // kNonVolatileBlockTier. So secondary cache will be used.
  2200. TEST_P(DBSecondaryCacheTest, TestSecondaryCacheOptionChange) {
  2201. if (IsHyperClock()) {
  2202. ROCKSDB_GTEST_BYPASS("Test depends on LRUCache-specific behaviors");
  2203. return;
  2204. }
  2205. std::shared_ptr<TestSecondaryCache> secondary_cache(
  2206. new TestSecondaryCache(2048 * 1024));
  2207. std::shared_ptr<Cache> cache =
  2208. NewCache(4 * 1024 /* capacity */, 0 /* num_shard_bits */,
  2209. false /* strict_capacity_limit */, secondary_cache);
  2210. BlockBasedTableOptions table_options;
  2211. table_options.block_cache = cache;
  2212. table_options.block_size = 4 * 1024;
  2213. Options options = GetDefaultOptions();
  2214. options.create_if_missing = true;
  2215. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2216. options.env = fault_env_.get();
  2217. fault_fs_->SetFailGetUniqueId(true);
  2218. options.lowest_used_cache_tier = CacheTier::kVolatileTier;
  2219. // Set the file paranoid check, so after flush, the file will be read
  2220. // all the blocks will be accessed.
  2221. options.paranoid_file_checks = true;
  2222. DestroyAndReopen(options);
  2223. Random rnd(301);
  2224. const int N = 6;
  2225. for (int i = 0; i < N; i++) {
  2226. std::string p_v = rnd.RandomString(1007);
  2227. ASSERT_OK(Put(Key(i), p_v));
  2228. }
  2229. ASSERT_OK(Flush());
  2230. for (int i = 0; i < N; i++) {
  2231. std::string p_v = rnd.RandomString(1007);
  2232. ASSERT_OK(Put(Key(i + 70), p_v));
  2233. }
  2234. ASSERT_OK(Flush());
  2235. // Flush will trigger the paranoid check and read blocks. But only block cache
  2236. // will be read.
  2237. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  2238. ASSERT_EQ(secondary_cache->num_lookups(), 0u);
  2239. Compact("a", "z");
  2240. // Compaction will also insert and evict blocks, no operations to the block
  2241. // cache.
  2242. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  2243. ASSERT_EQ(secondary_cache->num_lookups(), 0u);
  2244. std::string v = Get(Key(0));
  2245. ASSERT_EQ(1007, v.size());
  2246. // Check the data in first block. Cache miss, direclty read from SST file.
  2247. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  2248. ASSERT_EQ(secondary_cache->num_lookups(), 0u);
  2249. v = Get(Key(5));
  2250. ASSERT_EQ(1007, v.size());
  2251. // Check the second block.
  2252. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  2253. ASSERT_EQ(secondary_cache->num_lookups(), 0u);
  2254. v = Get(Key(5));
  2255. ASSERT_EQ(1007, v.size());
  2256. // block cache hit
  2257. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  2258. ASSERT_EQ(secondary_cache->num_lookups(), 0u);
  2259. // Change the option to enable secondary cache after we Reopen the DB
  2260. options.lowest_used_cache_tier = CacheTier::kNonVolatileBlockTier;
  2261. Reopen(options);
  2262. v = Get(Key(70));
  2263. ASSERT_EQ(1007, v.size());
  2264. // Enable the secondary cache, trigger lookup of the first block in second SST
  2265. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  2266. ASSERT_EQ(secondary_cache->num_lookups(), 1u);
  2267. v = Get(Key(75));
  2268. ASSERT_EQ(1007, v.size());
  2269. // trigger lookup of the second block in second SST
  2270. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  2271. ASSERT_EQ(secondary_cache->num_lookups(), 2u);
  2272. Destroy(options);
  2273. }
  2274. // Two DB test. We create 2 DBs sharing the same block cache and secondary
  2275. // cache. We diable the secondary cache option for DB2.
  2276. TEST_P(DBSecondaryCacheTest, TestSecondaryCacheOptionTwoDB) {
  2277. if (IsHyperClock()) {
  2278. ROCKSDB_GTEST_BYPASS("Test depends on LRUCache-specific behaviors");
  2279. return;
  2280. }
  2281. std::shared_ptr<TestSecondaryCache> secondary_cache(
  2282. new TestSecondaryCache(2048 * 1024));
  2283. std::shared_ptr<Cache> cache =
  2284. NewCache(4 * 1024 /* capacity */, 0 /* num_shard_bits */,
  2285. false /* strict_capacity_limit */, secondary_cache);
  2286. BlockBasedTableOptions table_options;
  2287. table_options.block_cache = cache;
  2288. table_options.block_size = 4 * 1024;
  2289. Options options = GetDefaultOptions();
  2290. options.create_if_missing = true;
  2291. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2292. options.env = fault_env_.get();
  2293. options.paranoid_file_checks = true;
  2294. std::string dbname1 = test::PerThreadDBPath("db_t_1");
  2295. ASSERT_OK(DestroyDB(dbname1, options));
  2296. DB* db1 = nullptr;
  2297. ASSERT_OK(DB::Open(options, dbname1, &db1));
  2298. std::string dbname2 = test::PerThreadDBPath("db_t_2");
  2299. ASSERT_OK(DestroyDB(dbname2, options));
  2300. DB* db2 = nullptr;
  2301. Options options2 = options;
  2302. options2.lowest_used_cache_tier = CacheTier::kVolatileTier;
  2303. ASSERT_OK(DB::Open(options2, dbname2, &db2));
  2304. fault_fs_->SetFailGetUniqueId(true);
  2305. WriteOptions wo;
  2306. Random rnd(301);
  2307. const int N = 6;
  2308. for (int i = 0; i < N; i++) {
  2309. std::string p_v = rnd.RandomString(1007);
  2310. ASSERT_OK(db1->Put(wo, Key(i), p_v));
  2311. }
  2312. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  2313. ASSERT_EQ(secondary_cache->num_lookups(), 0u);
  2314. ASSERT_OK(db1->Flush(FlushOptions()));
  2315. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  2316. ASSERT_EQ(secondary_cache->num_lookups(), 2u);
  2317. for (int i = 0; i < N; i++) {
  2318. std::string p_v = rnd.RandomString(1007);
  2319. ASSERT_OK(db2->Put(wo, Key(i), p_v));
  2320. }
  2321. // No change in the secondary cache, since it is disabled in DB2
  2322. ASSERT_EQ(secondary_cache->num_inserts(), 0u);
  2323. ASSERT_EQ(secondary_cache->num_lookups(), 2u);
  2324. ASSERT_OK(db2->Flush(FlushOptions()));
  2325. ASSERT_EQ(secondary_cache->num_inserts(), 1u);
  2326. ASSERT_EQ(secondary_cache->num_lookups(), 2u);
  2327. Slice bg("a");
  2328. Slice ed("b");
  2329. ASSERT_OK(db1->CompactRange(CompactRangeOptions(), &bg, &ed));
  2330. ASSERT_OK(db2->CompactRange(CompactRangeOptions(), &bg, &ed));
  2331. ASSERT_EQ(secondary_cache->num_inserts(), 1u);
  2332. ASSERT_EQ(secondary_cache->num_lookups(), 2u);
  2333. ReadOptions ro;
  2334. std::string v;
  2335. ASSERT_OK(db1->Get(ro, Key(0), &v));
  2336. ASSERT_EQ(1007, v.size());
  2337. // DB 1 has lookup block 1 and it is miss in block cache, trigger secondary
  2338. // cache lookup
  2339. ASSERT_EQ(secondary_cache->num_inserts(), 1u);
  2340. ASSERT_EQ(secondary_cache->num_lookups(), 3u);
  2341. ASSERT_OK(db1->Get(ro, Key(5), &v));
  2342. ASSERT_EQ(1007, v.size());
  2343. // DB 1 lookup the second block and it is miss in block cache, trigger
  2344. // secondary cache lookup
  2345. ASSERT_EQ(secondary_cache->num_inserts(), 1u);
  2346. ASSERT_EQ(secondary_cache->num_lookups(), 4u);
  2347. ASSERT_OK(db2->Get(ro, Key(0), &v));
  2348. ASSERT_EQ(1007, v.size());
  2349. // For db2, it is not enabled with secondary cache, so no search in the
  2350. // secondary cache
  2351. ASSERT_EQ(secondary_cache->num_inserts(), 1u);
  2352. ASSERT_EQ(secondary_cache->num_lookups(), 4u);
  2353. ASSERT_OK(db2->Get(ro, Key(5), &v));
  2354. ASSERT_EQ(1007, v.size());
  2355. // For db2, it is not enabled with secondary cache, so no search in the
  2356. // secondary cache
  2357. ASSERT_EQ(secondary_cache->num_inserts(), 1u);
  2358. ASSERT_EQ(secondary_cache->num_lookups(), 4u);
  2359. fault_fs_->SetFailGetUniqueId(false);
  2360. fault_fs_->SetFilesystemActive(true);
  2361. delete db1;
  2362. delete db2;
  2363. ASSERT_OK(DestroyDB(dbname1, options));
  2364. ASSERT_OK(DestroyDB(dbname2, options));
  2365. }
  2366. TEST_F(LRUCacheTest, InsertAfterReducingCapacity) {
  2367. // Fix a bug in LRU cache where it may try to remove a low pri entry's
  2368. // charge from high pri pool. It causes
  2369. // Assertion failed: (high_pri_pool_usage_ >= lru_low_pri_->total_charge),
  2370. // function MaintainPoolSize, file lru_cache.cc
  2371. NewCache(/*capacity=*/10, /*high_pri_pool_ratio=*/0.2,
  2372. /*low_pri_pool_ratio=*/0.8);
  2373. // high pri pool size and usage are both 2
  2374. Insert("x", Cache::Priority::HIGH);
  2375. Insert("y", Cache::Priority::HIGH);
  2376. cache_->SetCapacity(5);
  2377. // high_pri_pool_size is 1, the next time we try to maintain pool size,
  2378. // we will move entries from high pri pool to low pri pool
  2379. // The bug was deducting this entry's charge from high pri pool usage.
  2380. Insert("aaa", Cache::Priority::LOW, /*charge=*/3);
  2381. }
  2382. } // namespace ROCKSDB_NAMESPACE
  2383. int main(int argc, char** argv) {
  2384. ROCKSDB_NAMESPACE::port::InstallStackTraceHandler();
  2385. ::testing::InitGoogleTest(&argc, argv);
  2386. return RUN_ALL_TESTS();
  2387. }