db_test2.cc 162 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  7. // Use of this source code is governed by a BSD-style license that can be
  8. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  9. #include <atomic>
  10. #include <cstdlib>
  11. #include <functional>
  12. #include "db/db_test_util.h"
  13. #include "db/read_callback.h"
  14. #include "port/port.h"
  15. #include "port/stack_trace.h"
  16. #include "rocksdb/persistent_cache.h"
  17. #include "rocksdb/wal_filter.h"
  18. #include "test_util/fault_injection_test_env.h"
  19. namespace ROCKSDB_NAMESPACE {
  20. class DBTest2 : public DBTestBase {
  21. public:
  22. DBTest2() : DBTestBase("/db_test2") {}
  23. };
  24. class PrefixFullBloomWithReverseComparator
  25. : public DBTestBase,
  26. public ::testing::WithParamInterface<bool> {
  27. public:
  28. PrefixFullBloomWithReverseComparator()
  29. : DBTestBase("/prefix_bloom_reverse") {}
  30. void SetUp() override { if_cache_filter_ = GetParam(); }
  31. bool if_cache_filter_;
  32. };
  33. TEST_P(PrefixFullBloomWithReverseComparator,
  34. PrefixFullBloomWithReverseComparator) {
  35. Options options = last_options_;
  36. options.comparator = ReverseBytewiseComparator();
  37. options.prefix_extractor.reset(NewCappedPrefixTransform(3));
  38. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  39. BlockBasedTableOptions bbto;
  40. if (if_cache_filter_) {
  41. bbto.no_block_cache = false;
  42. bbto.cache_index_and_filter_blocks = true;
  43. bbto.block_cache = NewLRUCache(1);
  44. }
  45. bbto.filter_policy.reset(NewBloomFilterPolicy(10, false));
  46. bbto.whole_key_filtering = false;
  47. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  48. DestroyAndReopen(options);
  49. ASSERT_OK(dbfull()->Put(WriteOptions(), "bar123", "foo"));
  50. ASSERT_OK(dbfull()->Put(WriteOptions(), "bar234", "foo2"));
  51. ASSERT_OK(dbfull()->Put(WriteOptions(), "foo123", "foo3"));
  52. dbfull()->Flush(FlushOptions());
  53. if (bbto.block_cache) {
  54. bbto.block_cache->EraseUnRefEntries();
  55. }
  56. std::unique_ptr<Iterator> iter(db_->NewIterator(ReadOptions()));
  57. iter->Seek("bar345");
  58. ASSERT_OK(iter->status());
  59. ASSERT_TRUE(iter->Valid());
  60. ASSERT_EQ("bar234", iter->key().ToString());
  61. ASSERT_EQ("foo2", iter->value().ToString());
  62. iter->Next();
  63. ASSERT_TRUE(iter->Valid());
  64. ASSERT_EQ("bar123", iter->key().ToString());
  65. ASSERT_EQ("foo", iter->value().ToString());
  66. iter->Seek("foo234");
  67. ASSERT_OK(iter->status());
  68. ASSERT_TRUE(iter->Valid());
  69. ASSERT_EQ("foo123", iter->key().ToString());
  70. ASSERT_EQ("foo3", iter->value().ToString());
  71. iter->Seek("bar");
  72. ASSERT_OK(iter->status());
  73. ASSERT_TRUE(!iter->Valid());
  74. }
  75. INSTANTIATE_TEST_CASE_P(PrefixFullBloomWithReverseComparator,
  76. PrefixFullBloomWithReverseComparator, testing::Bool());
  77. TEST_F(DBTest2, IteratorPropertyVersionNumber) {
  78. Put("", "");
  79. Iterator* iter1 = db_->NewIterator(ReadOptions());
  80. std::string prop_value;
  81. ASSERT_OK(
  82. iter1->GetProperty("rocksdb.iterator.super-version-number", &prop_value));
  83. uint64_t version_number1 =
  84. static_cast<uint64_t>(std::atoi(prop_value.c_str()));
  85. Put("", "");
  86. Flush();
  87. Iterator* iter2 = db_->NewIterator(ReadOptions());
  88. ASSERT_OK(
  89. iter2->GetProperty("rocksdb.iterator.super-version-number", &prop_value));
  90. uint64_t version_number2 =
  91. static_cast<uint64_t>(std::atoi(prop_value.c_str()));
  92. ASSERT_GT(version_number2, version_number1);
  93. Put("", "");
  94. Iterator* iter3 = db_->NewIterator(ReadOptions());
  95. ASSERT_OK(
  96. iter3->GetProperty("rocksdb.iterator.super-version-number", &prop_value));
  97. uint64_t version_number3 =
  98. static_cast<uint64_t>(std::atoi(prop_value.c_str()));
  99. ASSERT_EQ(version_number2, version_number3);
  100. iter1->SeekToFirst();
  101. ASSERT_OK(
  102. iter1->GetProperty("rocksdb.iterator.super-version-number", &prop_value));
  103. uint64_t version_number1_new =
  104. static_cast<uint64_t>(std::atoi(prop_value.c_str()));
  105. ASSERT_EQ(version_number1, version_number1_new);
  106. delete iter1;
  107. delete iter2;
  108. delete iter3;
  109. }
  110. TEST_F(DBTest2, CacheIndexAndFilterWithDBRestart) {
  111. Options options = CurrentOptions();
  112. options.create_if_missing = true;
  113. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  114. BlockBasedTableOptions table_options;
  115. table_options.cache_index_and_filter_blocks = true;
  116. table_options.filter_policy.reset(NewBloomFilterPolicy(20));
  117. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  118. CreateAndReopenWithCF({"pikachu"}, options);
  119. Put(1, "a", "begin");
  120. Put(1, "z", "end");
  121. ASSERT_OK(Flush(1));
  122. TryReopenWithColumnFamilies({"default", "pikachu"}, options);
  123. std::string value;
  124. value = Get(1, "a");
  125. }
  126. TEST_F(DBTest2, MaxSuccessiveMergesChangeWithDBRecovery) {
  127. Options options = CurrentOptions();
  128. options.create_if_missing = true;
  129. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  130. options.max_successive_merges = 3;
  131. options.merge_operator = MergeOperators::CreatePutOperator();
  132. options.disable_auto_compactions = true;
  133. DestroyAndReopen(options);
  134. Put("poi", "Finch");
  135. db_->Merge(WriteOptions(), "poi", "Reese");
  136. db_->Merge(WriteOptions(), "poi", "Shaw");
  137. db_->Merge(WriteOptions(), "poi", "Root");
  138. options.max_successive_merges = 2;
  139. Reopen(options);
  140. }
  141. #ifndef ROCKSDB_LITE
  142. class DBTestSharedWriteBufferAcrossCFs
  143. : public DBTestBase,
  144. public testing::WithParamInterface<std::tuple<bool, bool>> {
  145. public:
  146. DBTestSharedWriteBufferAcrossCFs()
  147. : DBTestBase("/db_test_shared_write_buffer") {}
  148. void SetUp() override {
  149. use_old_interface_ = std::get<0>(GetParam());
  150. cost_cache_ = std::get<1>(GetParam());
  151. }
  152. bool use_old_interface_;
  153. bool cost_cache_;
  154. };
  155. TEST_P(DBTestSharedWriteBufferAcrossCFs, SharedWriteBufferAcrossCFs) {
  156. Options options = CurrentOptions();
  157. options.arena_block_size = 4096;
  158. // Avoid undeterministic value by malloc_usable_size();
  159. // Force arena block size to 1
  160. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  161. "Arena::Arena:0", [&](void* arg) {
  162. size_t* block_size = static_cast<size_t*>(arg);
  163. *block_size = 1;
  164. });
  165. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  166. "Arena::AllocateNewBlock:0", [&](void* arg) {
  167. std::pair<size_t*, size_t*>* pair =
  168. static_cast<std::pair<size_t*, size_t*>*>(arg);
  169. *std::get<0>(*pair) = *std::get<1>(*pair);
  170. });
  171. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  172. // The total soft write buffer size is about 105000
  173. std::shared_ptr<Cache> cache = NewLRUCache(4 * 1024 * 1024, 2);
  174. ASSERT_LT(cache->GetUsage(), 256 * 1024);
  175. if (use_old_interface_) {
  176. options.db_write_buffer_size = 120000; // this is the real limit
  177. } else if (!cost_cache_) {
  178. options.write_buffer_manager.reset(new WriteBufferManager(114285));
  179. } else {
  180. options.write_buffer_manager.reset(new WriteBufferManager(114285, cache));
  181. }
  182. options.write_buffer_size = 500000; // this is never hit
  183. CreateAndReopenWithCF({"pikachu", "dobrynia", "nikitich"}, options);
  184. WriteOptions wo;
  185. wo.disableWAL = true;
  186. std::function<void()> wait_flush = [&]() {
  187. dbfull()->TEST_WaitForFlushMemTable(handles_[0]);
  188. dbfull()->TEST_WaitForFlushMemTable(handles_[1]);
  189. dbfull()->TEST_WaitForFlushMemTable(handles_[2]);
  190. dbfull()->TEST_WaitForFlushMemTable(handles_[3]);
  191. };
  192. // Create some data and flush "default" and "nikitich" so that they
  193. // are newer CFs created.
  194. ASSERT_OK(Put(3, Key(1), DummyString(1), wo));
  195. Flush(3);
  196. ASSERT_OK(Put(3, Key(1), DummyString(1), wo));
  197. ASSERT_OK(Put(0, Key(1), DummyString(1), wo));
  198. Flush(0);
  199. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "default"),
  200. static_cast<uint64_t>(1));
  201. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "nikitich"),
  202. static_cast<uint64_t>(1));
  203. ASSERT_OK(Put(3, Key(1), DummyString(30000), wo));
  204. if (cost_cache_) {
  205. ASSERT_GE(cache->GetUsage(), 256 * 1024);
  206. ASSERT_LE(cache->GetUsage(), 2 * 256 * 1024);
  207. }
  208. wait_flush();
  209. ASSERT_OK(Put(0, Key(1), DummyString(60000), wo));
  210. if (cost_cache_) {
  211. ASSERT_GE(cache->GetUsage(), 256 * 1024);
  212. ASSERT_LE(cache->GetUsage(), 2 * 256 * 1024);
  213. }
  214. wait_flush();
  215. ASSERT_OK(Put(2, Key(1), DummyString(1), wo));
  216. // No flush should trigger
  217. wait_flush();
  218. {
  219. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "default"),
  220. static_cast<uint64_t>(1));
  221. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "pikachu"),
  222. static_cast<uint64_t>(0));
  223. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "dobrynia"),
  224. static_cast<uint64_t>(0));
  225. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "nikitich"),
  226. static_cast<uint64_t>(1));
  227. }
  228. // Trigger a flush. Flushing "nikitich".
  229. ASSERT_OK(Put(3, Key(2), DummyString(30000), wo));
  230. wait_flush();
  231. ASSERT_OK(Put(0, Key(1), DummyString(1), wo));
  232. wait_flush();
  233. {
  234. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "default"),
  235. static_cast<uint64_t>(1));
  236. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "pikachu"),
  237. static_cast<uint64_t>(0));
  238. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "dobrynia"),
  239. static_cast<uint64_t>(0));
  240. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "nikitich"),
  241. static_cast<uint64_t>(2));
  242. }
  243. // Without hitting the threshold, no flush should trigger.
  244. ASSERT_OK(Put(2, Key(1), DummyString(30000), wo));
  245. wait_flush();
  246. ASSERT_OK(Put(2, Key(1), DummyString(1), wo));
  247. wait_flush();
  248. ASSERT_OK(Put(2, Key(1), DummyString(1), wo));
  249. wait_flush();
  250. {
  251. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "default"),
  252. static_cast<uint64_t>(1));
  253. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "pikachu"),
  254. static_cast<uint64_t>(0));
  255. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "dobrynia"),
  256. static_cast<uint64_t>(0));
  257. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "nikitich"),
  258. static_cast<uint64_t>(2));
  259. }
  260. // Hit the write buffer limit again. "default"
  261. // will have been flushed.
  262. ASSERT_OK(Put(2, Key(2), DummyString(10000), wo));
  263. wait_flush();
  264. ASSERT_OK(Put(3, Key(1), DummyString(1), wo));
  265. wait_flush();
  266. ASSERT_OK(Put(0, Key(1), DummyString(1), wo));
  267. wait_flush();
  268. ASSERT_OK(Put(0, Key(1), DummyString(1), wo));
  269. wait_flush();
  270. ASSERT_OK(Put(0, Key(1), DummyString(1), wo));
  271. wait_flush();
  272. {
  273. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "default"),
  274. static_cast<uint64_t>(2));
  275. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "pikachu"),
  276. static_cast<uint64_t>(0));
  277. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "dobrynia"),
  278. static_cast<uint64_t>(0));
  279. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "nikitich"),
  280. static_cast<uint64_t>(2));
  281. }
  282. // Trigger another flush. This time "dobrynia". "pikachu" should not
  283. // be flushed, althrough it was never flushed.
  284. ASSERT_OK(Put(1, Key(1), DummyString(1), wo));
  285. wait_flush();
  286. ASSERT_OK(Put(2, Key(1), DummyString(80000), wo));
  287. wait_flush();
  288. ASSERT_OK(Put(1, Key(1), DummyString(1), wo));
  289. wait_flush();
  290. ASSERT_OK(Put(2, Key(1), DummyString(1), wo));
  291. wait_flush();
  292. {
  293. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "default"),
  294. static_cast<uint64_t>(2));
  295. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "pikachu"),
  296. static_cast<uint64_t>(0));
  297. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "dobrynia"),
  298. static_cast<uint64_t>(1));
  299. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "nikitich"),
  300. static_cast<uint64_t>(2));
  301. }
  302. if (cost_cache_) {
  303. ASSERT_GE(cache->GetUsage(), 256 * 1024);
  304. Close();
  305. options.write_buffer_manager.reset();
  306. last_options_.write_buffer_manager.reset();
  307. ASSERT_LT(cache->GetUsage(), 256 * 1024);
  308. }
  309. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  310. }
  311. INSTANTIATE_TEST_CASE_P(DBTestSharedWriteBufferAcrossCFs,
  312. DBTestSharedWriteBufferAcrossCFs,
  313. ::testing::Values(std::make_tuple(true, false),
  314. std::make_tuple(false, false),
  315. std::make_tuple(false, true)));
  316. TEST_F(DBTest2, SharedWriteBufferLimitAcrossDB) {
  317. std::string dbname2 = test::PerThreadDBPath("db_shared_wb_db2");
  318. Options options = CurrentOptions();
  319. options.arena_block_size = 4096;
  320. // Avoid undeterministic value by malloc_usable_size();
  321. // Force arena block size to 1
  322. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  323. "Arena::Arena:0", [&](void* arg) {
  324. size_t* block_size = static_cast<size_t*>(arg);
  325. *block_size = 1;
  326. });
  327. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  328. "Arena::AllocateNewBlock:0", [&](void* arg) {
  329. std::pair<size_t*, size_t*>* pair =
  330. static_cast<std::pair<size_t*, size_t*>*>(arg);
  331. *std::get<0>(*pair) = *std::get<1>(*pair);
  332. });
  333. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  334. options.write_buffer_size = 500000; // this is never hit
  335. // Use a write buffer total size so that the soft limit is about
  336. // 105000.
  337. options.write_buffer_manager.reset(new WriteBufferManager(120000));
  338. CreateAndReopenWithCF({"cf1", "cf2"}, options);
  339. ASSERT_OK(DestroyDB(dbname2, options));
  340. DB* db2 = nullptr;
  341. ASSERT_OK(DB::Open(options, dbname2, &db2));
  342. WriteOptions wo;
  343. wo.disableWAL = true;
  344. std::function<void()> wait_flush = [&]() {
  345. dbfull()->TEST_WaitForFlushMemTable(handles_[0]);
  346. dbfull()->TEST_WaitForFlushMemTable(handles_[1]);
  347. dbfull()->TEST_WaitForFlushMemTable(handles_[2]);
  348. static_cast<DBImpl*>(db2)->TEST_WaitForFlushMemTable();
  349. };
  350. // Trigger a flush on cf2
  351. ASSERT_OK(Put(2, Key(1), DummyString(70000), wo));
  352. wait_flush();
  353. ASSERT_OK(Put(0, Key(1), DummyString(20000), wo));
  354. wait_flush();
  355. // Insert to DB2
  356. ASSERT_OK(db2->Put(wo, Key(2), DummyString(20000)));
  357. wait_flush();
  358. ASSERT_OK(Put(2, Key(1), DummyString(1), wo));
  359. wait_flush();
  360. static_cast<DBImpl*>(db2)->TEST_WaitForFlushMemTable();
  361. {
  362. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "default") +
  363. GetNumberOfSstFilesForColumnFamily(db_, "cf1") +
  364. GetNumberOfSstFilesForColumnFamily(db_, "cf2"),
  365. static_cast<uint64_t>(1));
  366. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db2, "default"),
  367. static_cast<uint64_t>(0));
  368. }
  369. // Triggering to flush another CF in DB1
  370. ASSERT_OK(db2->Put(wo, Key(2), DummyString(70000)));
  371. wait_flush();
  372. ASSERT_OK(Put(2, Key(1), DummyString(1), wo));
  373. wait_flush();
  374. {
  375. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "default"),
  376. static_cast<uint64_t>(1));
  377. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "cf1"),
  378. static_cast<uint64_t>(0));
  379. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "cf2"),
  380. static_cast<uint64_t>(1));
  381. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db2, "default"),
  382. static_cast<uint64_t>(0));
  383. }
  384. // Triggering flush in DB2.
  385. ASSERT_OK(db2->Put(wo, Key(3), DummyString(40000)));
  386. wait_flush();
  387. ASSERT_OK(db2->Put(wo, Key(1), DummyString(1)));
  388. wait_flush();
  389. static_cast<DBImpl*>(db2)->TEST_WaitForFlushMemTable();
  390. {
  391. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "default"),
  392. static_cast<uint64_t>(1));
  393. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "cf1"),
  394. static_cast<uint64_t>(0));
  395. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db_, "cf2"),
  396. static_cast<uint64_t>(1));
  397. ASSERT_EQ(GetNumberOfSstFilesForColumnFamily(db2, "default"),
  398. static_cast<uint64_t>(1));
  399. }
  400. delete db2;
  401. ASSERT_OK(DestroyDB(dbname2, options));
  402. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  403. }
  404. TEST_F(DBTest2, TestWriteBufferNoLimitWithCache) {
  405. Options options = CurrentOptions();
  406. options.arena_block_size = 4096;
  407. std::shared_ptr<Cache> cache =
  408. NewLRUCache(LRUCacheOptions(10000000, 1, false, 0.0));
  409. options.write_buffer_size = 50000; // this is never hit
  410. // Use a write buffer total size so that the soft limit is about
  411. // 105000.
  412. options.write_buffer_manager.reset(new WriteBufferManager(0, cache));
  413. Reopen(options);
  414. ASSERT_OK(Put("foo", "bar"));
  415. // One dummy entry is 256KB.
  416. ASSERT_GT(cache->GetUsage(), 128000);
  417. }
  418. namespace {
  419. void ValidateKeyExistence(DB* db, const std::vector<Slice>& keys_must_exist,
  420. const std::vector<Slice>& keys_must_not_exist) {
  421. // Ensure that expected keys exist
  422. std::vector<std::string> values;
  423. if (keys_must_exist.size() > 0) {
  424. std::vector<Status> status_list =
  425. db->MultiGet(ReadOptions(), keys_must_exist, &values);
  426. for (size_t i = 0; i < keys_must_exist.size(); i++) {
  427. ASSERT_OK(status_list[i]);
  428. }
  429. }
  430. // Ensure that given keys don't exist
  431. if (keys_must_not_exist.size() > 0) {
  432. std::vector<Status> status_list =
  433. db->MultiGet(ReadOptions(), keys_must_not_exist, &values);
  434. for (size_t i = 0; i < keys_must_not_exist.size(); i++) {
  435. ASSERT_TRUE(status_list[i].IsNotFound());
  436. }
  437. }
  438. }
  439. } // namespace
  440. TEST_F(DBTest2, WalFilterTest) {
  441. class TestWalFilter : public WalFilter {
  442. private:
  443. // Processing option that is requested to be applied at the given index
  444. WalFilter::WalProcessingOption wal_processing_option_;
  445. // Index at which to apply wal_processing_option_
  446. // At other indexes default wal_processing_option::kContinueProcessing is
  447. // returned.
  448. size_t apply_option_at_record_index_;
  449. // Current record index, incremented with each record encountered.
  450. size_t current_record_index_;
  451. public:
  452. TestWalFilter(WalFilter::WalProcessingOption wal_processing_option,
  453. size_t apply_option_for_record_index)
  454. : wal_processing_option_(wal_processing_option),
  455. apply_option_at_record_index_(apply_option_for_record_index),
  456. current_record_index_(0) {}
  457. WalProcessingOption LogRecord(const WriteBatch& /*batch*/,
  458. WriteBatch* /*new_batch*/,
  459. bool* /*batch_changed*/) const override {
  460. WalFilter::WalProcessingOption option_to_return;
  461. if (current_record_index_ == apply_option_at_record_index_) {
  462. option_to_return = wal_processing_option_;
  463. }
  464. else {
  465. option_to_return = WalProcessingOption::kContinueProcessing;
  466. }
  467. // Filter is passed as a const object for RocksDB to not modify the
  468. // object, however we modify it for our own purpose here and hence
  469. // cast the constness away.
  470. (const_cast<TestWalFilter*>(this)->current_record_index_)++;
  471. return option_to_return;
  472. }
  473. const char* Name() const override { return "TestWalFilter"; }
  474. };
  475. // Create 3 batches with two keys each
  476. std::vector<std::vector<std::string>> batch_keys(3);
  477. batch_keys[0].push_back("key1");
  478. batch_keys[0].push_back("key2");
  479. batch_keys[1].push_back("key3");
  480. batch_keys[1].push_back("key4");
  481. batch_keys[2].push_back("key5");
  482. batch_keys[2].push_back("key6");
  483. // Test with all WAL processing options
  484. for (int option = 0;
  485. option < static_cast<int>(
  486. WalFilter::WalProcessingOption::kWalProcessingOptionMax);
  487. option++) {
  488. Options options = OptionsForLogIterTest();
  489. DestroyAndReopen(options);
  490. CreateAndReopenWithCF({ "pikachu" }, options);
  491. // Write given keys in given batches
  492. for (size_t i = 0; i < batch_keys.size(); i++) {
  493. WriteBatch batch;
  494. for (size_t j = 0; j < batch_keys[i].size(); j++) {
  495. batch.Put(handles_[0], batch_keys[i][j], DummyString(1024));
  496. }
  497. dbfull()->Write(WriteOptions(), &batch);
  498. }
  499. WalFilter::WalProcessingOption wal_processing_option =
  500. static_cast<WalFilter::WalProcessingOption>(option);
  501. // Create a test filter that would apply wal_processing_option at the first
  502. // record
  503. size_t apply_option_for_record_index = 1;
  504. TestWalFilter test_wal_filter(wal_processing_option,
  505. apply_option_for_record_index);
  506. // Reopen database with option to use WAL filter
  507. options = OptionsForLogIterTest();
  508. options.wal_filter = &test_wal_filter;
  509. Status status =
  510. TryReopenWithColumnFamilies({ "default", "pikachu" }, options);
  511. if (wal_processing_option ==
  512. WalFilter::WalProcessingOption::kCorruptedRecord) {
  513. assert(!status.ok());
  514. // In case of corruption we can turn off paranoid_checks to reopen
  515. // databse
  516. options.paranoid_checks = false;
  517. ReopenWithColumnFamilies({ "default", "pikachu" }, options);
  518. }
  519. else {
  520. assert(status.ok());
  521. }
  522. // Compute which keys we expect to be found
  523. // and which we expect not to be found after recovery.
  524. std::vector<Slice> keys_must_exist;
  525. std::vector<Slice> keys_must_not_exist;
  526. switch (wal_processing_option) {
  527. case WalFilter::WalProcessingOption::kCorruptedRecord:
  528. case WalFilter::WalProcessingOption::kContinueProcessing: {
  529. fprintf(stderr, "Testing with complete WAL processing\n");
  530. // we expect all records to be processed
  531. for (size_t i = 0; i < batch_keys.size(); i++) {
  532. for (size_t j = 0; j < batch_keys[i].size(); j++) {
  533. keys_must_exist.push_back(Slice(batch_keys[i][j]));
  534. }
  535. }
  536. break;
  537. }
  538. case WalFilter::WalProcessingOption::kIgnoreCurrentRecord: {
  539. fprintf(stderr,
  540. "Testing with ignoring record %" ROCKSDB_PRIszt " only\n",
  541. apply_option_for_record_index);
  542. // We expect the record with apply_option_for_record_index to be not
  543. // found.
  544. for (size_t i = 0; i < batch_keys.size(); i++) {
  545. for (size_t j = 0; j < batch_keys[i].size(); j++) {
  546. if (i == apply_option_for_record_index) {
  547. keys_must_not_exist.push_back(Slice(batch_keys[i][j]));
  548. }
  549. else {
  550. keys_must_exist.push_back(Slice(batch_keys[i][j]));
  551. }
  552. }
  553. }
  554. break;
  555. }
  556. case WalFilter::WalProcessingOption::kStopReplay: {
  557. fprintf(stderr,
  558. "Testing with stopping replay from record %" ROCKSDB_PRIszt
  559. "\n",
  560. apply_option_for_record_index);
  561. // We expect records beyond apply_option_for_record_index to be not
  562. // found.
  563. for (size_t i = 0; i < batch_keys.size(); i++) {
  564. for (size_t j = 0; j < batch_keys[i].size(); j++) {
  565. if (i >= apply_option_for_record_index) {
  566. keys_must_not_exist.push_back(Slice(batch_keys[i][j]));
  567. }
  568. else {
  569. keys_must_exist.push_back(Slice(batch_keys[i][j]));
  570. }
  571. }
  572. }
  573. break;
  574. }
  575. default:
  576. assert(false); // unhandled case
  577. }
  578. bool checked_after_reopen = false;
  579. while (true) {
  580. // Ensure that expected keys exists
  581. // and not expected keys don't exist after recovery
  582. ValidateKeyExistence(db_, keys_must_exist, keys_must_not_exist);
  583. if (checked_after_reopen) {
  584. break;
  585. }
  586. // reopen database again to make sure previous log(s) are not used
  587. //(even if they were skipped)
  588. // reopn database with option to use WAL filter
  589. options = OptionsForLogIterTest();
  590. ReopenWithColumnFamilies({ "default", "pikachu" }, options);
  591. checked_after_reopen = true;
  592. }
  593. }
  594. }
  595. TEST_F(DBTest2, WalFilterTestWithChangeBatch) {
  596. class ChangeBatchHandler : public WriteBatch::Handler {
  597. private:
  598. // Batch to insert keys in
  599. WriteBatch* new_write_batch_;
  600. // Number of keys to add in the new batch
  601. size_t num_keys_to_add_in_new_batch_;
  602. // Number of keys added to new batch
  603. size_t num_keys_added_;
  604. public:
  605. ChangeBatchHandler(WriteBatch* new_write_batch,
  606. size_t num_keys_to_add_in_new_batch)
  607. : new_write_batch_(new_write_batch),
  608. num_keys_to_add_in_new_batch_(num_keys_to_add_in_new_batch),
  609. num_keys_added_(0) {}
  610. void Put(const Slice& key, const Slice& value) override {
  611. if (num_keys_added_ < num_keys_to_add_in_new_batch_) {
  612. new_write_batch_->Put(key, value);
  613. ++num_keys_added_;
  614. }
  615. }
  616. };
  617. class TestWalFilterWithChangeBatch : public WalFilter {
  618. private:
  619. // Index at which to start changing records
  620. size_t change_records_from_index_;
  621. // Number of keys to add in the new batch
  622. size_t num_keys_to_add_in_new_batch_;
  623. // Current record index, incremented with each record encountered.
  624. size_t current_record_index_;
  625. public:
  626. TestWalFilterWithChangeBatch(size_t change_records_from_index,
  627. size_t num_keys_to_add_in_new_batch)
  628. : change_records_from_index_(change_records_from_index),
  629. num_keys_to_add_in_new_batch_(num_keys_to_add_in_new_batch),
  630. current_record_index_(0) {}
  631. WalProcessingOption LogRecord(const WriteBatch& batch,
  632. WriteBatch* new_batch,
  633. bool* batch_changed) const override {
  634. if (current_record_index_ >= change_records_from_index_) {
  635. ChangeBatchHandler handler(new_batch, num_keys_to_add_in_new_batch_);
  636. batch.Iterate(&handler);
  637. *batch_changed = true;
  638. }
  639. // Filter is passed as a const object for RocksDB to not modify the
  640. // object, however we modify it for our own purpose here and hence
  641. // cast the constness away.
  642. (const_cast<TestWalFilterWithChangeBatch*>(this)
  643. ->current_record_index_)++;
  644. return WalProcessingOption::kContinueProcessing;
  645. }
  646. const char* Name() const override { return "TestWalFilterWithChangeBatch"; }
  647. };
  648. std::vector<std::vector<std::string>> batch_keys(3);
  649. batch_keys[0].push_back("key1");
  650. batch_keys[0].push_back("key2");
  651. batch_keys[1].push_back("key3");
  652. batch_keys[1].push_back("key4");
  653. batch_keys[2].push_back("key5");
  654. batch_keys[2].push_back("key6");
  655. Options options = OptionsForLogIterTest();
  656. DestroyAndReopen(options);
  657. CreateAndReopenWithCF({ "pikachu" }, options);
  658. // Write given keys in given batches
  659. for (size_t i = 0; i < batch_keys.size(); i++) {
  660. WriteBatch batch;
  661. for (size_t j = 0; j < batch_keys[i].size(); j++) {
  662. batch.Put(handles_[0], batch_keys[i][j], DummyString(1024));
  663. }
  664. dbfull()->Write(WriteOptions(), &batch);
  665. }
  666. // Create a test filter that would apply wal_processing_option at the first
  667. // record
  668. size_t change_records_from_index = 1;
  669. size_t num_keys_to_add_in_new_batch = 1;
  670. TestWalFilterWithChangeBatch test_wal_filter_with_change_batch(
  671. change_records_from_index, num_keys_to_add_in_new_batch);
  672. // Reopen database with option to use WAL filter
  673. options = OptionsForLogIterTest();
  674. options.wal_filter = &test_wal_filter_with_change_batch;
  675. ReopenWithColumnFamilies({ "default", "pikachu" }, options);
  676. // Ensure that all keys exist before change_records_from_index_
  677. // And after that index only single key exists
  678. // as our filter adds only single key for each batch
  679. std::vector<Slice> keys_must_exist;
  680. std::vector<Slice> keys_must_not_exist;
  681. for (size_t i = 0; i < batch_keys.size(); i++) {
  682. for (size_t j = 0; j < batch_keys[i].size(); j++) {
  683. if (i >= change_records_from_index && j >= num_keys_to_add_in_new_batch) {
  684. keys_must_not_exist.push_back(Slice(batch_keys[i][j]));
  685. }
  686. else {
  687. keys_must_exist.push_back(Slice(batch_keys[i][j]));
  688. }
  689. }
  690. }
  691. bool checked_after_reopen = false;
  692. while (true) {
  693. // Ensure that expected keys exists
  694. // and not expected keys don't exist after recovery
  695. ValidateKeyExistence(db_, keys_must_exist, keys_must_not_exist);
  696. if (checked_after_reopen) {
  697. break;
  698. }
  699. // reopen database again to make sure previous log(s) are not used
  700. //(even if they were skipped)
  701. // reopn database with option to use WAL filter
  702. options = OptionsForLogIterTest();
  703. ReopenWithColumnFamilies({ "default", "pikachu" }, options);
  704. checked_after_reopen = true;
  705. }
  706. }
  707. TEST_F(DBTest2, WalFilterTestWithChangeBatchExtraKeys) {
  708. class TestWalFilterWithChangeBatchAddExtraKeys : public WalFilter {
  709. public:
  710. WalProcessingOption LogRecord(const WriteBatch& batch, WriteBatch* new_batch,
  711. bool* batch_changed) const override {
  712. *new_batch = batch;
  713. new_batch->Put("key_extra", "value_extra");
  714. *batch_changed = true;
  715. return WalProcessingOption::kContinueProcessing;
  716. }
  717. const char* Name() const override {
  718. return "WalFilterTestWithChangeBatchExtraKeys";
  719. }
  720. };
  721. std::vector<std::vector<std::string>> batch_keys(3);
  722. batch_keys[0].push_back("key1");
  723. batch_keys[0].push_back("key2");
  724. batch_keys[1].push_back("key3");
  725. batch_keys[1].push_back("key4");
  726. batch_keys[2].push_back("key5");
  727. batch_keys[2].push_back("key6");
  728. Options options = OptionsForLogIterTest();
  729. DestroyAndReopen(options);
  730. CreateAndReopenWithCF({ "pikachu" }, options);
  731. // Write given keys in given batches
  732. for (size_t i = 0; i < batch_keys.size(); i++) {
  733. WriteBatch batch;
  734. for (size_t j = 0; j < batch_keys[i].size(); j++) {
  735. batch.Put(handles_[0], batch_keys[i][j], DummyString(1024));
  736. }
  737. dbfull()->Write(WriteOptions(), &batch);
  738. }
  739. // Create a test filter that would add extra keys
  740. TestWalFilterWithChangeBatchAddExtraKeys test_wal_filter_extra_keys;
  741. // Reopen database with option to use WAL filter
  742. options = OptionsForLogIterTest();
  743. options.wal_filter = &test_wal_filter_extra_keys;
  744. Status status = TryReopenWithColumnFamilies({"default", "pikachu"}, options);
  745. ASSERT_TRUE(status.IsNotSupported());
  746. // Reopen without filter, now reopen should succeed - previous
  747. // attempt to open must not have altered the db.
  748. options = OptionsForLogIterTest();
  749. ReopenWithColumnFamilies({ "default", "pikachu" }, options);
  750. std::vector<Slice> keys_must_exist;
  751. std::vector<Slice> keys_must_not_exist; // empty vector
  752. for (size_t i = 0; i < batch_keys.size(); i++) {
  753. for (size_t j = 0; j < batch_keys[i].size(); j++) {
  754. keys_must_exist.push_back(Slice(batch_keys[i][j]));
  755. }
  756. }
  757. ValidateKeyExistence(db_, keys_must_exist, keys_must_not_exist);
  758. }
  759. TEST_F(DBTest2, WalFilterTestWithColumnFamilies) {
  760. class TestWalFilterWithColumnFamilies : public WalFilter {
  761. private:
  762. // column_family_id -> log_number map (provided to WALFilter)
  763. std::map<uint32_t, uint64_t> cf_log_number_map_;
  764. // column_family_name -> column_family_id map (provided to WALFilter)
  765. std::map<std::string, uint32_t> cf_name_id_map_;
  766. // column_family_name -> keys_found_in_wal map
  767. // We store keys that are applicable to the column_family
  768. // during recovery (i.e. aren't already flushed to SST file(s))
  769. // for verification against the keys we expect.
  770. std::map<uint32_t, std::vector<std::string>> cf_wal_keys_;
  771. public:
  772. void ColumnFamilyLogNumberMap(
  773. const std::map<uint32_t, uint64_t>& cf_lognumber_map,
  774. const std::map<std::string, uint32_t>& cf_name_id_map) override {
  775. cf_log_number_map_ = cf_lognumber_map;
  776. cf_name_id_map_ = cf_name_id_map;
  777. }
  778. WalProcessingOption LogRecordFound(unsigned long long log_number,
  779. const std::string& /*log_file_name*/,
  780. const WriteBatch& batch,
  781. WriteBatch* /*new_batch*/,
  782. bool* /*batch_changed*/) override {
  783. class LogRecordBatchHandler : public WriteBatch::Handler {
  784. private:
  785. const std::map<uint32_t, uint64_t> & cf_log_number_map_;
  786. std::map<uint32_t, std::vector<std::string>> & cf_wal_keys_;
  787. unsigned long long log_number_;
  788. public:
  789. LogRecordBatchHandler(unsigned long long current_log_number,
  790. const std::map<uint32_t, uint64_t> & cf_log_number_map,
  791. std::map<uint32_t, std::vector<std::string>> & cf_wal_keys) :
  792. cf_log_number_map_(cf_log_number_map),
  793. cf_wal_keys_(cf_wal_keys),
  794. log_number_(current_log_number){}
  795. Status PutCF(uint32_t column_family_id, const Slice& key,
  796. const Slice& /*value*/) override {
  797. auto it = cf_log_number_map_.find(column_family_id);
  798. assert(it != cf_log_number_map_.end());
  799. unsigned long long log_number_for_cf = it->second;
  800. // If the current record is applicable for column_family_id
  801. // (i.e. isn't flushed to SST file(s) for column_family_id)
  802. // add it to the cf_wal_keys_ map for verification.
  803. if (log_number_ >= log_number_for_cf) {
  804. cf_wal_keys_[column_family_id].push_back(std::string(key.data(),
  805. key.size()));
  806. }
  807. return Status::OK();
  808. }
  809. } handler(log_number, cf_log_number_map_, cf_wal_keys_);
  810. batch.Iterate(&handler);
  811. return WalProcessingOption::kContinueProcessing;
  812. }
  813. const char* Name() const override {
  814. return "WalFilterTestWithColumnFamilies";
  815. }
  816. const std::map<uint32_t, std::vector<std::string>>& GetColumnFamilyKeys() {
  817. return cf_wal_keys_;
  818. }
  819. const std::map<std::string, uint32_t> & GetColumnFamilyNameIdMap() {
  820. return cf_name_id_map_;
  821. }
  822. };
  823. std::vector<std::vector<std::string>> batch_keys_pre_flush(3);
  824. batch_keys_pre_flush[0].push_back("key1");
  825. batch_keys_pre_flush[0].push_back("key2");
  826. batch_keys_pre_flush[1].push_back("key3");
  827. batch_keys_pre_flush[1].push_back("key4");
  828. batch_keys_pre_flush[2].push_back("key5");
  829. batch_keys_pre_flush[2].push_back("key6");
  830. Options options = OptionsForLogIterTest();
  831. DestroyAndReopen(options);
  832. CreateAndReopenWithCF({ "pikachu" }, options);
  833. // Write given keys in given batches
  834. for (size_t i = 0; i < batch_keys_pre_flush.size(); i++) {
  835. WriteBatch batch;
  836. for (size_t j = 0; j < batch_keys_pre_flush[i].size(); j++) {
  837. batch.Put(handles_[0], batch_keys_pre_flush[i][j], DummyString(1024));
  838. batch.Put(handles_[1], batch_keys_pre_flush[i][j], DummyString(1024));
  839. }
  840. dbfull()->Write(WriteOptions(), &batch);
  841. }
  842. //Flush default column-family
  843. db_->Flush(FlushOptions(), handles_[0]);
  844. // Do some more writes
  845. std::vector<std::vector<std::string>> batch_keys_post_flush(3);
  846. batch_keys_post_flush[0].push_back("key7");
  847. batch_keys_post_flush[0].push_back("key8");
  848. batch_keys_post_flush[1].push_back("key9");
  849. batch_keys_post_flush[1].push_back("key10");
  850. batch_keys_post_flush[2].push_back("key11");
  851. batch_keys_post_flush[2].push_back("key12");
  852. // Write given keys in given batches
  853. for (size_t i = 0; i < batch_keys_post_flush.size(); i++) {
  854. WriteBatch batch;
  855. for (size_t j = 0; j < batch_keys_post_flush[i].size(); j++) {
  856. batch.Put(handles_[0], batch_keys_post_flush[i][j], DummyString(1024));
  857. batch.Put(handles_[1], batch_keys_post_flush[i][j], DummyString(1024));
  858. }
  859. dbfull()->Write(WriteOptions(), &batch);
  860. }
  861. // On Recovery we should only find the second batch applicable to default CF
  862. // But both batches applicable to pikachu CF
  863. // Create a test filter that would add extra keys
  864. TestWalFilterWithColumnFamilies test_wal_filter_column_families;
  865. // Reopen database with option to use WAL filter
  866. options = OptionsForLogIterTest();
  867. options.wal_filter = &test_wal_filter_column_families;
  868. Status status =
  869. TryReopenWithColumnFamilies({ "default", "pikachu" }, options);
  870. ASSERT_TRUE(status.ok());
  871. // verify that handles_[0] only has post_flush keys
  872. // while handles_[1] has pre and post flush keys
  873. auto cf_wal_keys = test_wal_filter_column_families.GetColumnFamilyKeys();
  874. auto name_id_map = test_wal_filter_column_families.GetColumnFamilyNameIdMap();
  875. size_t index = 0;
  876. auto keys_cf = cf_wal_keys[name_id_map[kDefaultColumnFamilyName]];
  877. //default column-family, only post_flush keys are expected
  878. for (size_t i = 0; i < batch_keys_post_flush.size(); i++) {
  879. for (size_t j = 0; j < batch_keys_post_flush[i].size(); j++) {
  880. Slice key_from_the_log(keys_cf[index++]);
  881. Slice batch_key(batch_keys_post_flush[i][j]);
  882. ASSERT_TRUE(key_from_the_log.compare(batch_key) == 0);
  883. }
  884. }
  885. ASSERT_TRUE(index == keys_cf.size());
  886. index = 0;
  887. keys_cf = cf_wal_keys[name_id_map["pikachu"]];
  888. //pikachu column-family, all keys are expected
  889. for (size_t i = 0; i < batch_keys_pre_flush.size(); i++) {
  890. for (size_t j = 0; j < batch_keys_pre_flush[i].size(); j++) {
  891. Slice key_from_the_log(keys_cf[index++]);
  892. Slice batch_key(batch_keys_pre_flush[i][j]);
  893. ASSERT_TRUE(key_from_the_log.compare(batch_key) == 0);
  894. }
  895. }
  896. for (size_t i = 0; i < batch_keys_post_flush.size(); i++) {
  897. for (size_t j = 0; j < batch_keys_post_flush[i].size(); j++) {
  898. Slice key_from_the_log(keys_cf[index++]);
  899. Slice batch_key(batch_keys_post_flush[i][j]);
  900. ASSERT_TRUE(key_from_the_log.compare(batch_key) == 0);
  901. }
  902. }
  903. ASSERT_TRUE(index == keys_cf.size());
  904. }
  905. TEST_F(DBTest2, PresetCompressionDict) {
  906. // Verifies that compression ratio improves when dictionary is enabled, and
  907. // improves even further when the dictionary is trained by ZSTD.
  908. const size_t kBlockSizeBytes = 4 << 10;
  909. const size_t kL0FileBytes = 128 << 10;
  910. const size_t kApproxPerBlockOverheadBytes = 50;
  911. const int kNumL0Files = 5;
  912. Options options;
  913. // Make sure to use any custom env that the test is configured with.
  914. options.env = CurrentOptions().env;
  915. options.allow_concurrent_memtable_write = false;
  916. options.arena_block_size = kBlockSizeBytes;
  917. options.create_if_missing = true;
  918. options.disable_auto_compactions = true;
  919. options.level0_file_num_compaction_trigger = kNumL0Files;
  920. options.memtable_factory.reset(
  921. new SpecialSkipListFactory(kL0FileBytes / kBlockSizeBytes));
  922. options.num_levels = 2;
  923. options.target_file_size_base = kL0FileBytes;
  924. options.target_file_size_multiplier = 2;
  925. options.write_buffer_size = kL0FileBytes;
  926. BlockBasedTableOptions table_options;
  927. table_options.block_size = kBlockSizeBytes;
  928. std::vector<CompressionType> compression_types;
  929. if (Zlib_Supported()) {
  930. compression_types.push_back(kZlibCompression);
  931. }
  932. #if LZ4_VERSION_NUMBER >= 10400 // r124+
  933. compression_types.push_back(kLZ4Compression);
  934. compression_types.push_back(kLZ4HCCompression);
  935. #endif // LZ4_VERSION_NUMBER >= 10400
  936. if (ZSTD_Supported()) {
  937. compression_types.push_back(kZSTD);
  938. }
  939. enum DictionaryTypes : int {
  940. kWithoutDict,
  941. kWithDict,
  942. kWithZSTDTrainedDict,
  943. kDictEnd,
  944. };
  945. for (auto compression_type : compression_types) {
  946. options.compression = compression_type;
  947. size_t bytes_without_dict = 0;
  948. size_t bytes_with_dict = 0;
  949. size_t bytes_with_zstd_trained_dict = 0;
  950. for (int i = kWithoutDict; i < kDictEnd; i++) {
  951. // First iteration: compress without preset dictionary
  952. // Second iteration: compress with preset dictionary
  953. // Third iteration (zstd only): compress with zstd-trained dictionary
  954. //
  955. // To make sure the compression dictionary has the intended effect, we
  956. // verify the compressed size is smaller in successive iterations. Also in
  957. // the non-first iterations, verify the data we get out is the same data
  958. // we put in.
  959. switch (i) {
  960. case kWithoutDict:
  961. options.compression_opts.max_dict_bytes = 0;
  962. options.compression_opts.zstd_max_train_bytes = 0;
  963. break;
  964. case kWithDict:
  965. options.compression_opts.max_dict_bytes = kBlockSizeBytes;
  966. options.compression_opts.zstd_max_train_bytes = 0;
  967. break;
  968. case kWithZSTDTrainedDict:
  969. if (compression_type != kZSTD) {
  970. continue;
  971. }
  972. options.compression_opts.max_dict_bytes = kBlockSizeBytes;
  973. options.compression_opts.zstd_max_train_bytes = kL0FileBytes;
  974. break;
  975. default:
  976. assert(false);
  977. }
  978. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  979. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  980. CreateAndReopenWithCF({"pikachu"}, options);
  981. Random rnd(301);
  982. std::string seq_datas[10];
  983. for (int j = 0; j < 10; ++j) {
  984. seq_datas[j] =
  985. RandomString(&rnd, kBlockSizeBytes - kApproxPerBlockOverheadBytes);
  986. }
  987. ASSERT_EQ(0, NumTableFilesAtLevel(0, 1));
  988. for (int j = 0; j < kNumL0Files; ++j) {
  989. for (size_t k = 0; k < kL0FileBytes / kBlockSizeBytes + 1; ++k) {
  990. auto key_num = j * (kL0FileBytes / kBlockSizeBytes) + k;
  991. ASSERT_OK(Put(1, Key(static_cast<int>(key_num)),
  992. seq_datas[(key_num / 10) % 10]));
  993. }
  994. dbfull()->TEST_WaitForFlushMemTable(handles_[1]);
  995. ASSERT_EQ(j + 1, NumTableFilesAtLevel(0, 1));
  996. }
  997. dbfull()->TEST_CompactRange(0, nullptr, nullptr, handles_[1],
  998. true /* disallow_trivial_move */);
  999. ASSERT_EQ(0, NumTableFilesAtLevel(0, 1));
  1000. ASSERT_GT(NumTableFilesAtLevel(1, 1), 0);
  1001. // Get the live sst files size
  1002. size_t total_sst_bytes = TotalSize(1);
  1003. if (i == kWithoutDict) {
  1004. bytes_without_dict = total_sst_bytes;
  1005. } else if (i == kWithDict) {
  1006. bytes_with_dict = total_sst_bytes;
  1007. } else if (i == kWithZSTDTrainedDict) {
  1008. bytes_with_zstd_trained_dict = total_sst_bytes;
  1009. }
  1010. for (size_t j = 0; j < kNumL0Files * (kL0FileBytes / kBlockSizeBytes);
  1011. j++) {
  1012. ASSERT_EQ(seq_datas[(j / 10) % 10], Get(1, Key(static_cast<int>(j))));
  1013. }
  1014. if (i == kWithDict) {
  1015. ASSERT_GT(bytes_without_dict, bytes_with_dict);
  1016. } else if (i == kWithZSTDTrainedDict) {
  1017. // In zstd compression, it is sometimes possible that using a trained
  1018. // dictionary does not get as good a compression ratio as without
  1019. // training.
  1020. // But using a dictionary (with or without training) should always get
  1021. // better compression ratio than not using one.
  1022. ASSERT_TRUE(bytes_with_dict > bytes_with_zstd_trained_dict ||
  1023. bytes_without_dict > bytes_with_zstd_trained_dict);
  1024. }
  1025. DestroyAndReopen(options);
  1026. }
  1027. }
  1028. }
  1029. TEST_F(DBTest2, PresetCompressionDictLocality) {
  1030. if (!ZSTD_Supported()) {
  1031. return;
  1032. }
  1033. // Verifies that compression dictionary is generated from local data. The
  1034. // verification simply checks all output SSTs have different compression
  1035. // dictionaries. We do not verify effectiveness as that'd likely be flaky in
  1036. // the future.
  1037. const int kNumEntriesPerFile = 1 << 10; // 1KB
  1038. const int kNumBytesPerEntry = 1 << 10; // 1KB
  1039. const int kNumFiles = 4;
  1040. Options options = CurrentOptions();
  1041. options.compression = kZSTD;
  1042. options.compression_opts.max_dict_bytes = 1 << 14; // 16KB
  1043. options.compression_opts.zstd_max_train_bytes = 1 << 18; // 256KB
  1044. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  1045. options.target_file_size_base = kNumEntriesPerFile * kNumBytesPerEntry;
  1046. BlockBasedTableOptions table_options;
  1047. table_options.cache_index_and_filter_blocks = true;
  1048. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  1049. Reopen(options);
  1050. Random rnd(301);
  1051. for (int i = 0; i < kNumFiles; ++i) {
  1052. for (int j = 0; j < kNumEntriesPerFile; ++j) {
  1053. ASSERT_OK(Put(Key(i * kNumEntriesPerFile + j),
  1054. RandomString(&rnd, kNumBytesPerEntry)));
  1055. }
  1056. ASSERT_OK(Flush());
  1057. MoveFilesToLevel(1);
  1058. ASSERT_EQ(NumTableFilesAtLevel(1), i + 1);
  1059. }
  1060. // Store all the dictionaries generated during a full compaction.
  1061. std::vector<std::string> compression_dicts;
  1062. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1063. "BlockBasedTableBuilder::WriteCompressionDictBlock:RawDict",
  1064. [&](void* arg) {
  1065. compression_dicts.emplace_back(static_cast<Slice*>(arg)->ToString());
  1066. });
  1067. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  1068. CompactRangeOptions compact_range_opts;
  1069. compact_range_opts.bottommost_level_compaction =
  1070. BottommostLevelCompaction::kForceOptimized;
  1071. ASSERT_OK(db_->CompactRange(compact_range_opts, nullptr, nullptr));
  1072. // Dictionary compression should not be so good as to compress four totally
  1073. // random files into one. If it does then there's probably something wrong
  1074. // with the test.
  1075. ASSERT_GT(NumTableFilesAtLevel(1), 1);
  1076. // Furthermore, there should be one compression dictionary generated per file.
  1077. // And they should all be different from each other.
  1078. ASSERT_EQ(NumTableFilesAtLevel(1),
  1079. static_cast<int>(compression_dicts.size()));
  1080. for (size_t i = 1; i < compression_dicts.size(); ++i) {
  1081. std::string& a = compression_dicts[i - 1];
  1082. std::string& b = compression_dicts[i];
  1083. size_t alen = a.size();
  1084. size_t blen = b.size();
  1085. ASSERT_TRUE(alen != blen || memcmp(a.data(), b.data(), alen) != 0);
  1086. }
  1087. }
  1088. class CompactionCompressionListener : public EventListener {
  1089. public:
  1090. explicit CompactionCompressionListener(Options* db_options)
  1091. : db_options_(db_options) {}
  1092. void OnCompactionCompleted(DB* db, const CompactionJobInfo& ci) override {
  1093. // Figure out last level with files
  1094. int bottommost_level = 0;
  1095. for (int level = 0; level < db->NumberLevels(); level++) {
  1096. std::string files_at_level;
  1097. ASSERT_TRUE(
  1098. db->GetProperty("rocksdb.num-files-at-level" + NumberToString(level),
  1099. &files_at_level));
  1100. if (files_at_level != "0") {
  1101. bottommost_level = level;
  1102. }
  1103. }
  1104. if (db_options_->bottommost_compression != kDisableCompressionOption &&
  1105. ci.output_level == bottommost_level) {
  1106. ASSERT_EQ(ci.compression, db_options_->bottommost_compression);
  1107. } else if (db_options_->compression_per_level.size() != 0) {
  1108. ASSERT_EQ(ci.compression,
  1109. db_options_->compression_per_level[ci.output_level]);
  1110. } else {
  1111. ASSERT_EQ(ci.compression, db_options_->compression);
  1112. }
  1113. max_level_checked = std::max(max_level_checked, ci.output_level);
  1114. }
  1115. int max_level_checked = 0;
  1116. const Options* db_options_;
  1117. };
  1118. TEST_F(DBTest2, CompressionOptions) {
  1119. if (!Zlib_Supported() || !Snappy_Supported()) {
  1120. return;
  1121. }
  1122. Options options = CurrentOptions();
  1123. options.level0_file_num_compaction_trigger = 2;
  1124. options.max_bytes_for_level_base = 100;
  1125. options.max_bytes_for_level_multiplier = 2;
  1126. options.num_levels = 7;
  1127. options.max_background_compactions = 1;
  1128. CompactionCompressionListener* listener =
  1129. new CompactionCompressionListener(&options);
  1130. options.listeners.emplace_back(listener);
  1131. const int kKeySize = 5;
  1132. const int kValSize = 20;
  1133. Random rnd(301);
  1134. for (int iter = 0; iter <= 2; iter++) {
  1135. listener->max_level_checked = 0;
  1136. if (iter == 0) {
  1137. // Use different compression algorithms for different levels but
  1138. // always use Zlib for bottommost level
  1139. options.compression_per_level = {kNoCompression, kNoCompression,
  1140. kNoCompression, kSnappyCompression,
  1141. kSnappyCompression, kSnappyCompression,
  1142. kZlibCompression};
  1143. options.compression = kNoCompression;
  1144. options.bottommost_compression = kZlibCompression;
  1145. } else if (iter == 1) {
  1146. // Use Snappy except for bottommost level use ZLib
  1147. options.compression_per_level = {};
  1148. options.compression = kSnappyCompression;
  1149. options.bottommost_compression = kZlibCompression;
  1150. } else if (iter == 2) {
  1151. // Use Snappy everywhere
  1152. options.compression_per_level = {};
  1153. options.compression = kSnappyCompression;
  1154. options.bottommost_compression = kDisableCompressionOption;
  1155. }
  1156. DestroyAndReopen(options);
  1157. // Write 10 random files
  1158. for (int i = 0; i < 10; i++) {
  1159. for (int j = 0; j < 5; j++) {
  1160. ASSERT_OK(
  1161. Put(RandomString(&rnd, kKeySize), RandomString(&rnd, kValSize)));
  1162. }
  1163. ASSERT_OK(Flush());
  1164. dbfull()->TEST_WaitForCompact();
  1165. }
  1166. // Make sure that we wrote enough to check all 7 levels
  1167. ASSERT_EQ(listener->max_level_checked, 6);
  1168. }
  1169. }
  1170. class CompactionStallTestListener : public EventListener {
  1171. public:
  1172. CompactionStallTestListener() : compacting_files_cnt_(0), compacted_files_cnt_(0) {}
  1173. void OnCompactionBegin(DB* /*db*/, const CompactionJobInfo& ci) override {
  1174. ASSERT_EQ(ci.cf_name, "default");
  1175. ASSERT_EQ(ci.base_input_level, 0);
  1176. ASSERT_EQ(ci.compaction_reason, CompactionReason::kLevelL0FilesNum);
  1177. compacting_files_cnt_ += ci.input_files.size();
  1178. }
  1179. void OnCompactionCompleted(DB* /*db*/, const CompactionJobInfo& ci) override {
  1180. ASSERT_EQ(ci.cf_name, "default");
  1181. ASSERT_EQ(ci.base_input_level, 0);
  1182. ASSERT_EQ(ci.compaction_reason, CompactionReason::kLevelL0FilesNum);
  1183. compacted_files_cnt_ += ci.input_files.size();
  1184. }
  1185. std::atomic<size_t> compacting_files_cnt_;
  1186. std::atomic<size_t> compacted_files_cnt_;
  1187. };
  1188. TEST_F(DBTest2, CompactionStall) {
  1189. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
  1190. {{"DBImpl::BGWorkCompaction", "DBTest2::CompactionStall:0"},
  1191. {"DBImpl::BGWorkCompaction", "DBTest2::CompactionStall:1"},
  1192. {"DBTest2::CompactionStall:2",
  1193. "DBImpl::NotifyOnCompactionBegin::UnlockMutex"},
  1194. {"DBTest2::CompactionStall:3",
  1195. "DBImpl::NotifyOnCompactionCompleted::UnlockMutex"}});
  1196. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  1197. Options options = CurrentOptions();
  1198. options.level0_file_num_compaction_trigger = 4;
  1199. options.max_background_compactions = 40;
  1200. CompactionStallTestListener* listener = new CompactionStallTestListener();
  1201. options.listeners.emplace_back(listener);
  1202. DestroyAndReopen(options);
  1203. // make sure all background compaction jobs can be scheduled
  1204. auto stop_token =
  1205. dbfull()->TEST_write_controler().GetCompactionPressureToken();
  1206. Random rnd(301);
  1207. // 4 Files in L0
  1208. for (int i = 0; i < 4; i++) {
  1209. for (int j = 0; j < 10; j++) {
  1210. ASSERT_OK(Put(RandomString(&rnd, 10), RandomString(&rnd, 10)));
  1211. }
  1212. ASSERT_OK(Flush());
  1213. }
  1214. // Wait for compaction to be triggered
  1215. TEST_SYNC_POINT("DBTest2::CompactionStall:0");
  1216. // Clear "DBImpl::BGWorkCompaction" SYNC_POINT since we want to hold it again
  1217. // at DBTest2::CompactionStall::1
  1218. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearTrace();
  1219. // Another 6 L0 files to trigger compaction again
  1220. for (int i = 0; i < 6; i++) {
  1221. for (int j = 0; j < 10; j++) {
  1222. ASSERT_OK(Put(RandomString(&rnd, 10), RandomString(&rnd, 10)));
  1223. }
  1224. ASSERT_OK(Flush());
  1225. }
  1226. // Wait for another compaction to be triggered
  1227. TEST_SYNC_POINT("DBTest2::CompactionStall:1");
  1228. // Hold NotifyOnCompactionBegin in the unlock mutex section
  1229. TEST_SYNC_POINT("DBTest2::CompactionStall:2");
  1230. // Hold NotifyOnCompactionCompleted in the unlock mutex section
  1231. TEST_SYNC_POINT("DBTest2::CompactionStall:3");
  1232. dbfull()->TEST_WaitForCompact();
  1233. ASSERT_LT(NumTableFilesAtLevel(0),
  1234. options.level0_file_num_compaction_trigger);
  1235. ASSERT_GT(listener->compacted_files_cnt_.load(),
  1236. 10 - options.level0_file_num_compaction_trigger);
  1237. ASSERT_EQ(listener->compacting_files_cnt_.load(), listener->compacted_files_cnt_.load());
  1238. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  1239. }
  1240. #endif // ROCKSDB_LITE
  1241. TEST_F(DBTest2, FirstSnapshotTest) {
  1242. Options options;
  1243. options.write_buffer_size = 100000; // Small write buffer
  1244. options = CurrentOptions(options);
  1245. CreateAndReopenWithCF({"pikachu"}, options);
  1246. // This snapshot will have sequence number 0 what is expected behaviour.
  1247. const Snapshot* s1 = db_->GetSnapshot();
  1248. Put(1, "k1", std::string(100000, 'x')); // Fill memtable
  1249. Put(1, "k2", std::string(100000, 'y')); // Trigger flush
  1250. db_->ReleaseSnapshot(s1);
  1251. }
  1252. #ifndef ROCKSDB_LITE
  1253. TEST_F(DBTest2, DuplicateSnapshot) {
  1254. Options options;
  1255. options = CurrentOptions(options);
  1256. std::vector<const Snapshot*> snapshots;
  1257. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  1258. SequenceNumber oldest_ww_snap, first_ww_snap;
  1259. Put("k", "v"); // inc seq
  1260. snapshots.push_back(db_->GetSnapshot());
  1261. snapshots.push_back(db_->GetSnapshot());
  1262. Put("k", "v"); // inc seq
  1263. snapshots.push_back(db_->GetSnapshot());
  1264. snapshots.push_back(dbi->GetSnapshotForWriteConflictBoundary());
  1265. first_ww_snap = snapshots.back()->GetSequenceNumber();
  1266. Put("k", "v"); // inc seq
  1267. snapshots.push_back(dbi->GetSnapshotForWriteConflictBoundary());
  1268. snapshots.push_back(db_->GetSnapshot());
  1269. Put("k", "v"); // inc seq
  1270. snapshots.push_back(db_->GetSnapshot());
  1271. {
  1272. InstrumentedMutexLock l(dbi->mutex());
  1273. auto seqs = dbi->snapshots().GetAll(&oldest_ww_snap);
  1274. ASSERT_EQ(seqs.size(), 4); // duplicates are not counted
  1275. ASSERT_EQ(oldest_ww_snap, first_ww_snap);
  1276. }
  1277. for (auto s : snapshots) {
  1278. db_->ReleaseSnapshot(s);
  1279. }
  1280. }
  1281. #endif // ROCKSDB_LITE
  1282. class PinL0IndexAndFilterBlocksTest
  1283. : public DBTestBase,
  1284. public testing::WithParamInterface<std::tuple<bool, bool>> {
  1285. public:
  1286. PinL0IndexAndFilterBlocksTest() : DBTestBase("/db_pin_l0_index_bloom_test") {}
  1287. void SetUp() override {
  1288. infinite_max_files_ = std::get<0>(GetParam());
  1289. disallow_preload_ = std::get<1>(GetParam());
  1290. }
  1291. void CreateTwoLevels(Options* options, bool close_afterwards) {
  1292. if (infinite_max_files_) {
  1293. options->max_open_files = -1;
  1294. }
  1295. options->create_if_missing = true;
  1296. options->statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  1297. BlockBasedTableOptions table_options;
  1298. table_options.cache_index_and_filter_blocks = true;
  1299. table_options.pin_l0_filter_and_index_blocks_in_cache = true;
  1300. table_options.filter_policy.reset(NewBloomFilterPolicy(20));
  1301. options->table_factory.reset(new BlockBasedTableFactory(table_options));
  1302. CreateAndReopenWithCF({"pikachu"}, *options);
  1303. Put(1, "a", "begin");
  1304. Put(1, "z", "end");
  1305. ASSERT_OK(Flush(1));
  1306. // move this table to L1
  1307. dbfull()->TEST_CompactRange(0, nullptr, nullptr, handles_[1]);
  1308. // reset block cache
  1309. table_options.block_cache = NewLRUCache(64 * 1024);
  1310. options->table_factory.reset(NewBlockBasedTableFactory(table_options));
  1311. TryReopenWithColumnFamilies({"default", "pikachu"}, *options);
  1312. // create new table at L0
  1313. Put(1, "a2", "begin2");
  1314. Put(1, "z2", "end2");
  1315. ASSERT_OK(Flush(1));
  1316. if (close_afterwards) {
  1317. Close(); // This ensures that there is no ref to block cache entries
  1318. }
  1319. table_options.block_cache->EraseUnRefEntries();
  1320. }
  1321. bool infinite_max_files_;
  1322. bool disallow_preload_;
  1323. };
  1324. TEST_P(PinL0IndexAndFilterBlocksTest,
  1325. IndexAndFilterBlocksOfNewTableAddedToCacheWithPinning) {
  1326. Options options = CurrentOptions();
  1327. if (infinite_max_files_) {
  1328. options.max_open_files = -1;
  1329. }
  1330. options.create_if_missing = true;
  1331. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  1332. BlockBasedTableOptions table_options;
  1333. table_options.cache_index_and_filter_blocks = true;
  1334. table_options.pin_l0_filter_and_index_blocks_in_cache = true;
  1335. table_options.filter_policy.reset(NewBloomFilterPolicy(20));
  1336. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  1337. CreateAndReopenWithCF({"pikachu"}, options);
  1338. ASSERT_OK(Put(1, "key", "val"));
  1339. // Create a new table.
  1340. ASSERT_OK(Flush(1));
  1341. // index/filter blocks added to block cache right after table creation.
  1342. ASSERT_EQ(1, TestGetTickerCount(options, BLOCK_CACHE_FILTER_MISS));
  1343. ASSERT_EQ(0, TestGetTickerCount(options, BLOCK_CACHE_FILTER_HIT));
  1344. ASSERT_EQ(1, TestGetTickerCount(options, BLOCK_CACHE_INDEX_MISS));
  1345. ASSERT_EQ(0, TestGetTickerCount(options, BLOCK_CACHE_INDEX_HIT));
  1346. // only index/filter were added
  1347. ASSERT_EQ(2, TestGetTickerCount(options, BLOCK_CACHE_ADD));
  1348. ASSERT_EQ(0, TestGetTickerCount(options, BLOCK_CACHE_DATA_MISS));
  1349. std::string value;
  1350. // Miss and hit count should remain the same, they're all pinned.
  1351. db_->KeyMayExist(ReadOptions(), handles_[1], "key", &value);
  1352. ASSERT_EQ(1, TestGetTickerCount(options, BLOCK_CACHE_FILTER_MISS));
  1353. ASSERT_EQ(0, TestGetTickerCount(options, BLOCK_CACHE_FILTER_HIT));
  1354. ASSERT_EQ(1, TestGetTickerCount(options, BLOCK_CACHE_INDEX_MISS));
  1355. ASSERT_EQ(0, TestGetTickerCount(options, BLOCK_CACHE_INDEX_HIT));
  1356. // Miss and hit count should remain the same, they're all pinned.
  1357. value = Get(1, "key");
  1358. ASSERT_EQ(1, TestGetTickerCount(options, BLOCK_CACHE_FILTER_MISS));
  1359. ASSERT_EQ(0, TestGetTickerCount(options, BLOCK_CACHE_FILTER_HIT));
  1360. ASSERT_EQ(1, TestGetTickerCount(options, BLOCK_CACHE_INDEX_MISS));
  1361. ASSERT_EQ(0, TestGetTickerCount(options, BLOCK_CACHE_INDEX_HIT));
  1362. }
  1363. TEST_P(PinL0IndexAndFilterBlocksTest,
  1364. MultiLevelIndexAndFilterBlocksCachedWithPinning) {
  1365. Options options = CurrentOptions();
  1366. PinL0IndexAndFilterBlocksTest::CreateTwoLevels(&options, false);
  1367. // get base cache values
  1368. uint64_t fm = TestGetTickerCount(options, BLOCK_CACHE_FILTER_MISS);
  1369. uint64_t fh = TestGetTickerCount(options, BLOCK_CACHE_FILTER_HIT);
  1370. uint64_t im = TestGetTickerCount(options, BLOCK_CACHE_INDEX_MISS);
  1371. uint64_t ih = TestGetTickerCount(options, BLOCK_CACHE_INDEX_HIT);
  1372. std::string value;
  1373. // this should be read from L0
  1374. // so cache values don't change
  1375. value = Get(1, "a2");
  1376. ASSERT_EQ(fm, TestGetTickerCount(options, BLOCK_CACHE_FILTER_MISS));
  1377. ASSERT_EQ(fh, TestGetTickerCount(options, BLOCK_CACHE_FILTER_HIT));
  1378. ASSERT_EQ(im, TestGetTickerCount(options, BLOCK_CACHE_INDEX_MISS));
  1379. ASSERT_EQ(ih, TestGetTickerCount(options, BLOCK_CACHE_INDEX_HIT));
  1380. // this should be read from L1
  1381. // the file is opened, prefetching results in a cache filter miss
  1382. // the block is loaded and added to the cache,
  1383. // then the get results in a cache hit for L1
  1384. // When we have inifinite max_files, there is still cache miss because we have
  1385. // reset the block cache
  1386. value = Get(1, "a");
  1387. ASSERT_EQ(fm + 1, TestGetTickerCount(options, BLOCK_CACHE_FILTER_MISS));
  1388. ASSERT_EQ(im + 1, TestGetTickerCount(options, BLOCK_CACHE_INDEX_MISS));
  1389. }
  1390. TEST_P(PinL0IndexAndFilterBlocksTest, DisablePrefetchingNonL0IndexAndFilter) {
  1391. Options options = CurrentOptions();
  1392. // This ensures that db does not ref anything in the block cache, so
  1393. // EraseUnRefEntries could clear them up.
  1394. bool close_afterwards = true;
  1395. PinL0IndexAndFilterBlocksTest::CreateTwoLevels(&options, close_afterwards);
  1396. // Get base cache values
  1397. uint64_t fm = TestGetTickerCount(options, BLOCK_CACHE_FILTER_MISS);
  1398. uint64_t fh = TestGetTickerCount(options, BLOCK_CACHE_FILTER_HIT);
  1399. uint64_t im = TestGetTickerCount(options, BLOCK_CACHE_INDEX_MISS);
  1400. uint64_t ih = TestGetTickerCount(options, BLOCK_CACHE_INDEX_HIT);
  1401. if (disallow_preload_) {
  1402. // Now we have two files. We narrow the max open files to allow 3 entries
  1403. // so that preloading SST files won't happen.
  1404. options.max_open_files = 13;
  1405. // RocksDB sanitize max open files to at least 20. Modify it back.
  1406. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1407. "SanitizeOptions::AfterChangeMaxOpenFiles", [&](void* arg) {
  1408. int* max_open_files = static_cast<int*>(arg);
  1409. *max_open_files = 13;
  1410. });
  1411. }
  1412. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  1413. // Reopen database. If max_open_files is set as -1, table readers will be
  1414. // preloaded. This will trigger a BlockBasedTable::Open() and prefetch
  1415. // L0 index and filter. Level 1's prefetching is disabled in DB::Open()
  1416. TryReopenWithColumnFamilies({"default", "pikachu"}, options);
  1417. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  1418. if (!disallow_preload_) {
  1419. // After reopen, cache miss are increased by one because we read (and only
  1420. // read) filter and index on L0
  1421. ASSERT_EQ(fm + 1, TestGetTickerCount(options, BLOCK_CACHE_FILTER_MISS));
  1422. ASSERT_EQ(fh, TestGetTickerCount(options, BLOCK_CACHE_FILTER_HIT));
  1423. ASSERT_EQ(im + 1, TestGetTickerCount(options, BLOCK_CACHE_INDEX_MISS));
  1424. ASSERT_EQ(ih, TestGetTickerCount(options, BLOCK_CACHE_INDEX_HIT));
  1425. } else {
  1426. // If max_open_files is not -1, we do not preload table readers, so there is
  1427. // no change.
  1428. ASSERT_EQ(fm, TestGetTickerCount(options, BLOCK_CACHE_FILTER_MISS));
  1429. ASSERT_EQ(fh, TestGetTickerCount(options, BLOCK_CACHE_FILTER_HIT));
  1430. ASSERT_EQ(im, TestGetTickerCount(options, BLOCK_CACHE_INDEX_MISS));
  1431. ASSERT_EQ(ih, TestGetTickerCount(options, BLOCK_CACHE_INDEX_HIT));
  1432. }
  1433. std::string value;
  1434. // this should be read from L0
  1435. value = Get(1, "a2");
  1436. // If max_open_files is -1, we have pinned index and filter in Rep, so there
  1437. // will not be changes in index and filter misses or hits. If max_open_files
  1438. // is not -1, Get() will open a TableReader and prefetch index and filter.
  1439. ASSERT_EQ(fm + 1, TestGetTickerCount(options, BLOCK_CACHE_FILTER_MISS));
  1440. ASSERT_EQ(fh, TestGetTickerCount(options, BLOCK_CACHE_FILTER_HIT));
  1441. ASSERT_EQ(im + 1, TestGetTickerCount(options, BLOCK_CACHE_INDEX_MISS));
  1442. ASSERT_EQ(ih, TestGetTickerCount(options, BLOCK_CACHE_INDEX_HIT));
  1443. // this should be read from L1
  1444. value = Get(1, "a");
  1445. if (!disallow_preload_) {
  1446. // In inifinite max files case, there's a cache miss in executing Get()
  1447. // because index and filter are not prefetched before.
  1448. ASSERT_EQ(fm + 2, TestGetTickerCount(options, BLOCK_CACHE_FILTER_MISS));
  1449. ASSERT_EQ(fh, TestGetTickerCount(options, BLOCK_CACHE_FILTER_HIT));
  1450. ASSERT_EQ(im + 2, TestGetTickerCount(options, BLOCK_CACHE_INDEX_MISS));
  1451. ASSERT_EQ(ih, TestGetTickerCount(options, BLOCK_CACHE_INDEX_HIT));
  1452. } else {
  1453. // In this case, cache miss will be increased by one in
  1454. // BlockBasedTable::Open() because this is not in DB::Open() code path so we
  1455. // will prefetch L1's index and filter. Cache hit will also be increased by
  1456. // one because Get() will read index and filter from the block cache
  1457. // prefetched in previous Open() call.
  1458. ASSERT_EQ(fm + 2, TestGetTickerCount(options, BLOCK_CACHE_FILTER_MISS));
  1459. ASSERT_EQ(fh + 1, TestGetTickerCount(options, BLOCK_CACHE_FILTER_HIT));
  1460. ASSERT_EQ(im + 2, TestGetTickerCount(options, BLOCK_CACHE_INDEX_MISS));
  1461. ASSERT_EQ(ih + 1, TestGetTickerCount(options, BLOCK_CACHE_INDEX_HIT));
  1462. }
  1463. // Force a full compaction to one single file. There will be a block
  1464. // cache read for both of index and filter. If prefetch doesn't explicitly
  1465. // happen, it will happen when verifying the file.
  1466. Compact(1, "a", "zzzzz");
  1467. dbfull()->TEST_WaitForCompact();
  1468. if (!disallow_preload_) {
  1469. ASSERT_EQ(fm + 3, TestGetTickerCount(options, BLOCK_CACHE_FILTER_MISS));
  1470. ASSERT_EQ(fh, TestGetTickerCount(options, BLOCK_CACHE_FILTER_HIT));
  1471. ASSERT_EQ(im + 3, TestGetTickerCount(options, BLOCK_CACHE_INDEX_MISS));
  1472. ASSERT_EQ(ih + 2, TestGetTickerCount(options, BLOCK_CACHE_INDEX_HIT));
  1473. } else {
  1474. ASSERT_EQ(fm + 3, TestGetTickerCount(options, BLOCK_CACHE_FILTER_MISS));
  1475. ASSERT_EQ(fh + 1, TestGetTickerCount(options, BLOCK_CACHE_FILTER_HIT));
  1476. ASSERT_EQ(im + 3, TestGetTickerCount(options, BLOCK_CACHE_INDEX_MISS));
  1477. ASSERT_EQ(ih + 3, TestGetTickerCount(options, BLOCK_CACHE_INDEX_HIT));
  1478. }
  1479. // Bloom and index hit will happen when a Get() happens.
  1480. value = Get(1, "a");
  1481. if (!disallow_preload_) {
  1482. ASSERT_EQ(fm + 3, TestGetTickerCount(options, BLOCK_CACHE_FILTER_MISS));
  1483. ASSERT_EQ(fh + 1, TestGetTickerCount(options, BLOCK_CACHE_FILTER_HIT));
  1484. ASSERT_EQ(im + 3, TestGetTickerCount(options, BLOCK_CACHE_INDEX_MISS));
  1485. ASSERT_EQ(ih + 3, TestGetTickerCount(options, BLOCK_CACHE_INDEX_HIT));
  1486. } else {
  1487. ASSERT_EQ(fm + 3, TestGetTickerCount(options, BLOCK_CACHE_FILTER_MISS));
  1488. ASSERT_EQ(fh + 2, TestGetTickerCount(options, BLOCK_CACHE_FILTER_HIT));
  1489. ASSERT_EQ(im + 3, TestGetTickerCount(options, BLOCK_CACHE_INDEX_MISS));
  1490. ASSERT_EQ(ih + 4, TestGetTickerCount(options, BLOCK_CACHE_INDEX_HIT));
  1491. }
  1492. }
  1493. INSTANTIATE_TEST_CASE_P(PinL0IndexAndFilterBlocksTest,
  1494. PinL0IndexAndFilterBlocksTest,
  1495. ::testing::Values(std::make_tuple(true, false),
  1496. std::make_tuple(false, false),
  1497. std::make_tuple(false, true)));
  1498. #ifndef ROCKSDB_LITE
  1499. TEST_F(DBTest2, MaxCompactionBytesTest) {
  1500. Options options = CurrentOptions();
  1501. options.memtable_factory.reset(
  1502. new SpecialSkipListFactory(DBTestBase::kNumKeysByGenerateNewRandomFile));
  1503. options.compaction_style = kCompactionStyleLevel;
  1504. options.write_buffer_size = 200 << 10;
  1505. options.arena_block_size = 4 << 10;
  1506. options.level0_file_num_compaction_trigger = 4;
  1507. options.num_levels = 4;
  1508. options.compression = kNoCompression;
  1509. options.max_bytes_for_level_base = 450 << 10;
  1510. options.target_file_size_base = 100 << 10;
  1511. // Infinite for full compaction.
  1512. options.max_compaction_bytes = options.target_file_size_base * 100;
  1513. Reopen(options);
  1514. Random rnd(301);
  1515. for (int num = 0; num < 8; num++) {
  1516. GenerateNewRandomFile(&rnd);
  1517. }
  1518. CompactRangeOptions cro;
  1519. cro.bottommost_level_compaction = BottommostLevelCompaction::kForceOptimized;
  1520. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  1521. ASSERT_EQ("0,0,8", FilesPerLevel(0));
  1522. // When compact from Ln -> Ln+1, cut a file if the file overlaps with
  1523. // more than three files in Ln+1.
  1524. options.max_compaction_bytes = options.target_file_size_base * 3;
  1525. Reopen(options);
  1526. GenerateNewRandomFile(&rnd);
  1527. // Add three more small files that overlap with the previous file
  1528. for (int i = 0; i < 3; i++) {
  1529. Put("a", "z");
  1530. ASSERT_OK(Flush());
  1531. }
  1532. dbfull()->TEST_WaitForCompact();
  1533. // Output files to L1 are cut to three pieces, according to
  1534. // options.max_compaction_bytes
  1535. ASSERT_EQ("0,3,8", FilesPerLevel(0));
  1536. }
  1537. static void UniqueIdCallback(void* arg) {
  1538. int* result = reinterpret_cast<int*>(arg);
  1539. if (*result == -1) {
  1540. *result = 0;
  1541. }
  1542. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearTrace();
  1543. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1544. "GetUniqueIdFromFile:FS_IOC_GETVERSION", UniqueIdCallback);
  1545. }
  1546. class MockPersistentCache : public PersistentCache {
  1547. public:
  1548. explicit MockPersistentCache(const bool is_compressed, const size_t max_size)
  1549. : is_compressed_(is_compressed), max_size_(max_size) {
  1550. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  1551. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1552. "GetUniqueIdFromFile:FS_IOC_GETVERSION", UniqueIdCallback);
  1553. }
  1554. ~MockPersistentCache() override {}
  1555. PersistentCache::StatsType Stats() override {
  1556. return PersistentCache::StatsType();
  1557. }
  1558. Status Insert(const Slice& page_key, const char* data,
  1559. const size_t size) override {
  1560. MutexLock _(&lock_);
  1561. if (size_ > max_size_) {
  1562. size_ -= data_.begin()->second.size();
  1563. data_.erase(data_.begin());
  1564. }
  1565. data_.insert(std::make_pair(page_key.ToString(), std::string(data, size)));
  1566. size_ += size;
  1567. return Status::OK();
  1568. }
  1569. Status Lookup(const Slice& page_key, std::unique_ptr<char[]>* data,
  1570. size_t* size) override {
  1571. MutexLock _(&lock_);
  1572. auto it = data_.find(page_key.ToString());
  1573. if (it == data_.end()) {
  1574. return Status::NotFound();
  1575. }
  1576. assert(page_key.ToString() == it->first);
  1577. data->reset(new char[it->second.size()]);
  1578. memcpy(data->get(), it->second.c_str(), it->second.size());
  1579. *size = it->second.size();
  1580. return Status::OK();
  1581. }
  1582. bool IsCompressed() override { return is_compressed_; }
  1583. std::string GetPrintableOptions() const override {
  1584. return "MockPersistentCache";
  1585. }
  1586. port::Mutex lock_;
  1587. std::map<std::string, std::string> data_;
  1588. const bool is_compressed_ = true;
  1589. size_t size_ = 0;
  1590. const size_t max_size_ = 10 * 1024; // 10KiB
  1591. };
  1592. #ifdef OS_LINUX
  1593. // Make sure that in CPU time perf context counters, Env::NowCPUNanos()
  1594. // is used, rather than Env::CPUNanos();
  1595. TEST_F(DBTest2, TestPerfContextGetCpuTime) {
  1596. // force resizing table cache so table handle is not preloaded so that
  1597. // we can measure find_table_nanos during Get().
  1598. dbfull()->TEST_table_cache()->SetCapacity(0);
  1599. ASSERT_OK(Put("foo", "bar"));
  1600. ASSERT_OK(Flush());
  1601. env_->now_cpu_count_.store(0);
  1602. // CPU timing is not enabled with kEnableTimeExceptForMutex
  1603. SetPerfLevel(PerfLevel::kEnableTimeExceptForMutex);
  1604. ASSERT_EQ("bar", Get("foo"));
  1605. ASSERT_EQ(0, get_perf_context()->get_cpu_nanos);
  1606. ASSERT_EQ(0, env_->now_cpu_count_.load());
  1607. uint64_t kDummyAddonTime = uint64_t{1000000000000};
  1608. // Add time to NowNanos() reading.
  1609. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1610. "TableCache::FindTable:0",
  1611. [&](void* /*arg*/) { env_->addon_time_.fetch_add(kDummyAddonTime); });
  1612. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  1613. SetPerfLevel(PerfLevel::kEnableTimeAndCPUTimeExceptForMutex);
  1614. ASSERT_EQ("bar", Get("foo"));
  1615. ASSERT_GT(env_->now_cpu_count_.load(), 2);
  1616. ASSERT_LT(get_perf_context()->get_cpu_nanos, kDummyAddonTime);
  1617. ASSERT_GT(get_perf_context()->find_table_nanos, kDummyAddonTime);
  1618. SetPerfLevel(PerfLevel::kDisable);
  1619. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  1620. }
  1621. TEST_F(DBTest2, TestPerfContextIterCpuTime) {
  1622. DestroyAndReopen(CurrentOptions());
  1623. // force resizing table cache so table handle is not preloaded so that
  1624. // we can measure find_table_nanos during iteration
  1625. dbfull()->TEST_table_cache()->SetCapacity(0);
  1626. const size_t kNumEntries = 10;
  1627. for (size_t i = 0; i < kNumEntries; ++i) {
  1628. ASSERT_OK(Put("k" + ToString(i), "v" + ToString(i)));
  1629. }
  1630. ASSERT_OK(Flush());
  1631. for (size_t i = 0; i < kNumEntries; ++i) {
  1632. ASSERT_EQ("v" + ToString(i), Get("k" + ToString(i)));
  1633. }
  1634. std::string last_key = "k" + ToString(kNumEntries - 1);
  1635. std::string last_value = "v" + ToString(kNumEntries - 1);
  1636. env_->now_cpu_count_.store(0);
  1637. // CPU timing is not enabled with kEnableTimeExceptForMutex
  1638. SetPerfLevel(PerfLevel::kEnableTimeExceptForMutex);
  1639. Iterator* iter = db_->NewIterator(ReadOptions());
  1640. iter->Seek("k0");
  1641. ASSERT_TRUE(iter->Valid());
  1642. ASSERT_EQ("v0", iter->value().ToString());
  1643. iter->SeekForPrev(last_key);
  1644. ASSERT_TRUE(iter->Valid());
  1645. iter->SeekToLast();
  1646. ASSERT_TRUE(iter->Valid());
  1647. ASSERT_EQ(last_value, iter->value().ToString());
  1648. iter->SeekToFirst();
  1649. ASSERT_TRUE(iter->Valid());
  1650. ASSERT_EQ("v0", iter->value().ToString());
  1651. ASSERT_EQ(0, get_perf_context()->iter_seek_cpu_nanos);
  1652. iter->Next();
  1653. ASSERT_TRUE(iter->Valid());
  1654. ASSERT_EQ("v1", iter->value().ToString());
  1655. ASSERT_EQ(0, get_perf_context()->iter_next_cpu_nanos);
  1656. iter->Prev();
  1657. ASSERT_TRUE(iter->Valid());
  1658. ASSERT_EQ("v0", iter->value().ToString());
  1659. ASSERT_EQ(0, get_perf_context()->iter_prev_cpu_nanos);
  1660. ASSERT_EQ(0, env_->now_cpu_count_.load());
  1661. delete iter;
  1662. uint64_t kDummyAddonTime = uint64_t{1000000000000};
  1663. // Add time to NowNanos() reading.
  1664. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1665. "TableCache::FindTable:0",
  1666. [&](void* /*arg*/) { env_->addon_time_.fetch_add(kDummyAddonTime); });
  1667. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  1668. SetPerfLevel(PerfLevel::kEnableTimeAndCPUTimeExceptForMutex);
  1669. iter = db_->NewIterator(ReadOptions());
  1670. iter->Seek("k0");
  1671. ASSERT_TRUE(iter->Valid());
  1672. ASSERT_EQ("v0", iter->value().ToString());
  1673. iter->SeekForPrev(last_key);
  1674. ASSERT_TRUE(iter->Valid());
  1675. iter->SeekToLast();
  1676. ASSERT_TRUE(iter->Valid());
  1677. ASSERT_EQ(last_value, iter->value().ToString());
  1678. iter->SeekToFirst();
  1679. ASSERT_TRUE(iter->Valid());
  1680. ASSERT_EQ("v0", iter->value().ToString());
  1681. ASSERT_GT(get_perf_context()->iter_seek_cpu_nanos, 0);
  1682. ASSERT_LT(get_perf_context()->iter_seek_cpu_nanos, kDummyAddonTime);
  1683. iter->Next();
  1684. ASSERT_TRUE(iter->Valid());
  1685. ASSERT_EQ("v1", iter->value().ToString());
  1686. ASSERT_GT(get_perf_context()->iter_next_cpu_nanos, 0);
  1687. ASSERT_LT(get_perf_context()->iter_next_cpu_nanos, kDummyAddonTime);
  1688. iter->Prev();
  1689. ASSERT_TRUE(iter->Valid());
  1690. ASSERT_EQ("v0", iter->value().ToString());
  1691. ASSERT_GT(get_perf_context()->iter_prev_cpu_nanos, 0);
  1692. ASSERT_LT(get_perf_context()->iter_prev_cpu_nanos, kDummyAddonTime);
  1693. ASSERT_GE(env_->now_cpu_count_.load(), 12);
  1694. ASSERT_GT(get_perf_context()->find_table_nanos, kDummyAddonTime);
  1695. SetPerfLevel(PerfLevel::kDisable);
  1696. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  1697. delete iter;
  1698. }
  1699. #endif // OS_LINUX
  1700. // GetUniqueIdFromFile is not implemented on these platforms. Persistent cache
  1701. // breaks when that function is not implemented and no regular block cache is
  1702. // provided.
  1703. #if !defined(OS_SOLARIS) && !defined(OS_WIN)
  1704. TEST_F(DBTest2, PersistentCache) {
  1705. int num_iter = 80;
  1706. Options options;
  1707. options.write_buffer_size = 64 * 1024; // small write buffer
  1708. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  1709. options = CurrentOptions(options);
  1710. auto bsizes = {/*no block cache*/ 0, /*1M*/ 1 * 1024 * 1024};
  1711. auto types = {/*compressed*/ 1, /*uncompressed*/ 0};
  1712. for (auto bsize : bsizes) {
  1713. for (auto type : types) {
  1714. BlockBasedTableOptions table_options;
  1715. table_options.persistent_cache.reset(
  1716. new MockPersistentCache(type, 10 * 1024));
  1717. table_options.no_block_cache = true;
  1718. table_options.block_cache = bsize ? NewLRUCache(bsize) : nullptr;
  1719. table_options.block_cache_compressed = nullptr;
  1720. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1721. DestroyAndReopen(options);
  1722. CreateAndReopenWithCF({"pikachu"}, options);
  1723. // default column family doesn't have block cache
  1724. Options no_block_cache_opts;
  1725. no_block_cache_opts.statistics = options.statistics;
  1726. no_block_cache_opts = CurrentOptions(no_block_cache_opts);
  1727. BlockBasedTableOptions table_options_no_bc;
  1728. table_options_no_bc.no_block_cache = true;
  1729. no_block_cache_opts.table_factory.reset(
  1730. NewBlockBasedTableFactory(table_options_no_bc));
  1731. ReopenWithColumnFamilies(
  1732. {"default", "pikachu"},
  1733. std::vector<Options>({no_block_cache_opts, options}));
  1734. Random rnd(301);
  1735. // Write 8MB (80 values, each 100K)
  1736. ASSERT_EQ(NumTableFilesAtLevel(0, 1), 0);
  1737. std::vector<std::string> values;
  1738. std::string str;
  1739. for (int i = 0; i < num_iter; i++) {
  1740. if (i % 4 == 0) { // high compression ratio
  1741. str = RandomString(&rnd, 1000);
  1742. }
  1743. values.push_back(str);
  1744. ASSERT_OK(Put(1, Key(i), values[i]));
  1745. }
  1746. // flush all data from memtable so that reads are from block cache
  1747. ASSERT_OK(Flush(1));
  1748. for (int i = 0; i < num_iter; i++) {
  1749. ASSERT_EQ(Get(1, Key(i)), values[i]);
  1750. }
  1751. auto hit = options.statistics->getTickerCount(PERSISTENT_CACHE_HIT);
  1752. auto miss = options.statistics->getTickerCount(PERSISTENT_CACHE_MISS);
  1753. ASSERT_GT(hit, 0);
  1754. ASSERT_GT(miss, 0);
  1755. }
  1756. }
  1757. }
  1758. #endif // !defined(OS_SOLARIS) && !defined(OS_WIN)
  1759. namespace {
  1760. void CountSyncPoint() {
  1761. TEST_SYNC_POINT_CALLBACK("DBTest2::MarkedPoint", nullptr /* arg */);
  1762. }
  1763. } // namespace
  1764. TEST_F(DBTest2, SyncPointMarker) {
  1765. std::atomic<int> sync_point_called(0);
  1766. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1767. "DBTest2::MarkedPoint",
  1768. [&](void* /*arg*/) { sync_point_called.fetch_add(1); });
  1769. // The first dependency enforces Marker can be loaded before MarkedPoint.
  1770. // The second checks that thread 1's MarkedPoint should be disabled here.
  1771. // Execution order:
  1772. // | Thread 1 | Thread 2 |
  1773. // | | Marker |
  1774. // | MarkedPoint | |
  1775. // | Thread1First | |
  1776. // | | MarkedPoint |
  1777. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependencyAndMarkers(
  1778. {{"DBTest2::SyncPointMarker:Thread1First", "DBTest2::MarkedPoint"}},
  1779. {{"DBTest2::SyncPointMarker:Marker", "DBTest2::MarkedPoint"}});
  1780. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  1781. std::function<void()> func1 = [&]() {
  1782. CountSyncPoint();
  1783. TEST_SYNC_POINT("DBTest2::SyncPointMarker:Thread1First");
  1784. };
  1785. std::function<void()> func2 = [&]() {
  1786. TEST_SYNC_POINT("DBTest2::SyncPointMarker:Marker");
  1787. CountSyncPoint();
  1788. };
  1789. auto thread1 = port::Thread(func1);
  1790. auto thread2 = port::Thread(func2);
  1791. thread1.join();
  1792. thread2.join();
  1793. // Callback is only executed once
  1794. ASSERT_EQ(sync_point_called.load(), 1);
  1795. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  1796. }
  1797. #endif
  1798. size_t GetEncodedEntrySize(size_t key_size, size_t value_size) {
  1799. std::string buffer;
  1800. PutVarint32(&buffer, static_cast<uint32_t>(0));
  1801. PutVarint32(&buffer, static_cast<uint32_t>(key_size));
  1802. PutVarint32(&buffer, static_cast<uint32_t>(value_size));
  1803. return buffer.size() + key_size + value_size;
  1804. }
  1805. TEST_F(DBTest2, ReadAmpBitmap) {
  1806. Options options = CurrentOptions();
  1807. BlockBasedTableOptions bbto;
  1808. uint32_t bytes_per_bit[2] = {1, 16};
  1809. for (size_t k = 0; k < 2; k++) {
  1810. // Disable delta encoding to make it easier to calculate read amplification
  1811. bbto.use_delta_encoding = false;
  1812. // Huge block cache to make it easier to calculate read amplification
  1813. bbto.block_cache = NewLRUCache(1024 * 1024 * 1024);
  1814. bbto.read_amp_bytes_per_bit = bytes_per_bit[k];
  1815. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  1816. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  1817. DestroyAndReopen(options);
  1818. const size_t kNumEntries = 10000;
  1819. Random rnd(301);
  1820. for (size_t i = 0; i < kNumEntries; i++) {
  1821. ASSERT_OK(Put(Key(static_cast<int>(i)), RandomString(&rnd, 100)));
  1822. }
  1823. ASSERT_OK(Flush());
  1824. Close();
  1825. Reopen(options);
  1826. // Read keys/values randomly and verify that reported read amp error
  1827. // is less than 2%
  1828. uint64_t total_useful_bytes = 0;
  1829. std::set<int> read_keys;
  1830. std::string value;
  1831. for (size_t i = 0; i < kNumEntries * 5; i++) {
  1832. int key_idx = rnd.Next() % kNumEntries;
  1833. std::string key = Key(key_idx);
  1834. ASSERT_OK(db_->Get(ReadOptions(), key, &value));
  1835. if (read_keys.find(key_idx) == read_keys.end()) {
  1836. auto internal_key = InternalKey(key, 0, ValueType::kTypeValue);
  1837. total_useful_bytes +=
  1838. GetEncodedEntrySize(internal_key.size(), value.size());
  1839. read_keys.insert(key_idx);
  1840. }
  1841. double expected_read_amp =
  1842. static_cast<double>(total_useful_bytes) /
  1843. options.statistics->getTickerCount(READ_AMP_TOTAL_READ_BYTES);
  1844. double read_amp =
  1845. static_cast<double>(options.statistics->getTickerCount(
  1846. READ_AMP_ESTIMATE_USEFUL_BYTES)) /
  1847. options.statistics->getTickerCount(READ_AMP_TOTAL_READ_BYTES);
  1848. double error_pct = fabs(expected_read_amp - read_amp) * 100;
  1849. // Error between reported read amp and real read amp should be less than
  1850. // 2%
  1851. EXPECT_LE(error_pct, 2);
  1852. }
  1853. // Make sure we read every thing in the DB (which is smaller than our cache)
  1854. Iterator* iter = db_->NewIterator(ReadOptions());
  1855. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  1856. ASSERT_EQ(iter->value().ToString(), Get(iter->key().ToString()));
  1857. }
  1858. delete iter;
  1859. // Read amp is on average 100% since we read all what we loaded in memory
  1860. if (k == 0) {
  1861. ASSERT_EQ(
  1862. options.statistics->getTickerCount(READ_AMP_ESTIMATE_USEFUL_BYTES),
  1863. options.statistics->getTickerCount(READ_AMP_TOTAL_READ_BYTES));
  1864. } else {
  1865. ASSERT_NEAR(
  1866. options.statistics->getTickerCount(READ_AMP_ESTIMATE_USEFUL_BYTES) *
  1867. 1.0f /
  1868. options.statistics->getTickerCount(READ_AMP_TOTAL_READ_BYTES),
  1869. 1, .01);
  1870. }
  1871. }
  1872. }
  1873. #ifndef OS_SOLARIS // GetUniqueIdFromFile is not implemented
  1874. TEST_F(DBTest2, ReadAmpBitmapLiveInCacheAfterDBClose) {
  1875. {
  1876. const int kIdBufLen = 100;
  1877. char id_buf[kIdBufLen];
  1878. #ifndef OS_WIN
  1879. // You can't open a directory on windows using random access file
  1880. std::unique_ptr<RandomAccessFile> file;
  1881. ASSERT_OK(env_->NewRandomAccessFile(dbname_, &file, EnvOptions()));
  1882. if (file->GetUniqueId(id_buf, kIdBufLen) == 0) {
  1883. // fs holding db directory doesn't support getting a unique file id,
  1884. // this means that running this test will fail because lru_cache will load
  1885. // the blocks again regardless of them being already in the cache
  1886. return;
  1887. }
  1888. #else
  1889. std::unique_ptr<Directory> dir;
  1890. ASSERT_OK(env_->NewDirectory(dbname_, &dir));
  1891. if (dir->GetUniqueId(id_buf, kIdBufLen) == 0) {
  1892. // fs holding db directory doesn't support getting a unique file id,
  1893. // this means that running this test will fail because lru_cache will load
  1894. // the blocks again regardless of them being already in the cache
  1895. return;
  1896. }
  1897. #endif
  1898. }
  1899. uint32_t bytes_per_bit[2] = {1, 16};
  1900. for (size_t k = 0; k < 2; k++) {
  1901. std::shared_ptr<Cache> lru_cache = NewLRUCache(1024 * 1024 * 1024);
  1902. std::shared_ptr<Statistics> stats = ROCKSDB_NAMESPACE::CreateDBStatistics();
  1903. Options options = CurrentOptions();
  1904. BlockBasedTableOptions bbto;
  1905. // Disable delta encoding to make it easier to calculate read amplification
  1906. bbto.use_delta_encoding = false;
  1907. // Huge block cache to make it easier to calculate read amplification
  1908. bbto.block_cache = lru_cache;
  1909. bbto.read_amp_bytes_per_bit = bytes_per_bit[k];
  1910. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  1911. options.statistics = stats;
  1912. DestroyAndReopen(options);
  1913. const int kNumEntries = 10000;
  1914. Random rnd(301);
  1915. for (int i = 0; i < kNumEntries; i++) {
  1916. ASSERT_OK(Put(Key(i), RandomString(&rnd, 100)));
  1917. }
  1918. ASSERT_OK(Flush());
  1919. Close();
  1920. Reopen(options);
  1921. uint64_t total_useful_bytes = 0;
  1922. std::set<int> read_keys;
  1923. std::string value;
  1924. // Iter1: Read half the DB, Read even keys
  1925. // Key(0), Key(2), Key(4), Key(6), Key(8), ...
  1926. for (int i = 0; i < kNumEntries; i += 2) {
  1927. std::string key = Key(i);
  1928. ASSERT_OK(db_->Get(ReadOptions(), key, &value));
  1929. if (read_keys.find(i) == read_keys.end()) {
  1930. auto internal_key = InternalKey(key, 0, ValueType::kTypeValue);
  1931. total_useful_bytes +=
  1932. GetEncodedEntrySize(internal_key.size(), value.size());
  1933. read_keys.insert(i);
  1934. }
  1935. }
  1936. size_t total_useful_bytes_iter1 =
  1937. options.statistics->getTickerCount(READ_AMP_ESTIMATE_USEFUL_BYTES);
  1938. size_t total_loaded_bytes_iter1 =
  1939. options.statistics->getTickerCount(READ_AMP_TOTAL_READ_BYTES);
  1940. Close();
  1941. std::shared_ptr<Statistics> new_statistics =
  1942. ROCKSDB_NAMESPACE::CreateDBStatistics();
  1943. // Destroy old statistics obj that the blocks in lru_cache are pointing to
  1944. options.statistics.reset();
  1945. // Use the statistics object that we just created
  1946. options.statistics = new_statistics;
  1947. Reopen(options);
  1948. // Iter2: Read half the DB, Read odd keys
  1949. // Key(1), Key(3), Key(5), Key(7), Key(9), ...
  1950. for (int i = 1; i < kNumEntries; i += 2) {
  1951. std::string key = Key(i);
  1952. ASSERT_OK(db_->Get(ReadOptions(), key, &value));
  1953. if (read_keys.find(i) == read_keys.end()) {
  1954. auto internal_key = InternalKey(key, 0, ValueType::kTypeValue);
  1955. total_useful_bytes +=
  1956. GetEncodedEntrySize(internal_key.size(), value.size());
  1957. read_keys.insert(i);
  1958. }
  1959. }
  1960. size_t total_useful_bytes_iter2 =
  1961. options.statistics->getTickerCount(READ_AMP_ESTIMATE_USEFUL_BYTES);
  1962. size_t total_loaded_bytes_iter2 =
  1963. options.statistics->getTickerCount(READ_AMP_TOTAL_READ_BYTES);
  1964. // Read amp is on average 100% since we read all what we loaded in memory
  1965. if (k == 0) {
  1966. ASSERT_EQ(total_useful_bytes_iter1 + total_useful_bytes_iter2,
  1967. total_loaded_bytes_iter1 + total_loaded_bytes_iter2);
  1968. } else {
  1969. ASSERT_NEAR((total_useful_bytes_iter1 + total_useful_bytes_iter2) * 1.0f /
  1970. (total_loaded_bytes_iter1 + total_loaded_bytes_iter2),
  1971. 1, .01);
  1972. }
  1973. }
  1974. }
  1975. #endif // !OS_SOLARIS
  1976. #ifndef ROCKSDB_LITE
  1977. TEST_F(DBTest2, AutomaticCompactionOverlapManualCompaction) {
  1978. Options options = CurrentOptions();
  1979. options.num_levels = 3;
  1980. options.IncreaseParallelism(20);
  1981. DestroyAndReopen(options);
  1982. ASSERT_OK(Put(Key(0), "a"));
  1983. ASSERT_OK(Put(Key(5), "a"));
  1984. ASSERT_OK(Flush());
  1985. ASSERT_OK(Put(Key(10), "a"));
  1986. ASSERT_OK(Put(Key(15), "a"));
  1987. ASSERT_OK(Flush());
  1988. CompactRangeOptions cro;
  1989. cro.change_level = true;
  1990. cro.target_level = 2;
  1991. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  1992. auto get_stat = [](std::string level_str, LevelStatType type,
  1993. std::map<std::string, std::string> props) {
  1994. auto prop_str =
  1995. "compaction." + level_str + "." +
  1996. InternalStats::compaction_level_stats.at(type).property_name.c_str();
  1997. auto prop_item = props.find(prop_str);
  1998. return prop_item == props.end() ? 0 : std::stod(prop_item->second);
  1999. };
  2000. // Trivial move 2 files to L2
  2001. ASSERT_EQ("0,0,2", FilesPerLevel());
  2002. // Also test that the stats GetMapProperty API reporting the same result
  2003. {
  2004. std::map<std::string, std::string> prop;
  2005. ASSERT_TRUE(dbfull()->GetMapProperty("rocksdb.cfstats", &prop));
  2006. ASSERT_EQ(0, get_stat("L0", LevelStatType::NUM_FILES, prop));
  2007. ASSERT_EQ(0, get_stat("L1", LevelStatType::NUM_FILES, prop));
  2008. ASSERT_EQ(2, get_stat("L2", LevelStatType::NUM_FILES, prop));
  2009. ASSERT_EQ(2, get_stat("Sum", LevelStatType::NUM_FILES, prop));
  2010. }
  2011. // While the compaction is running, we will create 2 new files that
  2012. // can fit in L2, these 2 files will be moved to L2 and overlap with
  2013. // the running compaction and break the LSM consistency.
  2014. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  2015. "CompactionJob::Run():Start", [&](void* /*arg*/) {
  2016. ASSERT_OK(
  2017. dbfull()->SetOptions({{"level0_file_num_compaction_trigger", "2"},
  2018. {"max_bytes_for_level_base", "1"}}));
  2019. ASSERT_OK(Put(Key(6), "a"));
  2020. ASSERT_OK(Put(Key(7), "a"));
  2021. ASSERT_OK(Flush());
  2022. ASSERT_OK(Put(Key(8), "a"));
  2023. ASSERT_OK(Put(Key(9), "a"));
  2024. ASSERT_OK(Flush());
  2025. });
  2026. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  2027. // Run a manual compaction that will compact the 2 files in L2
  2028. // into 1 file in L2
  2029. cro.exclusive_manual_compaction = false;
  2030. cro.bottommost_level_compaction = BottommostLevelCompaction::kForceOptimized;
  2031. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  2032. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  2033. // Test that the stats GetMapProperty API reporting 1 file in L2
  2034. {
  2035. std::map<std::string, std::string> prop;
  2036. ASSERT_TRUE(dbfull()->GetMapProperty("rocksdb.cfstats", &prop));
  2037. ASSERT_EQ(1, get_stat("L2", LevelStatType::NUM_FILES, prop));
  2038. }
  2039. }
  2040. TEST_F(DBTest2, ManualCompactionOverlapManualCompaction) {
  2041. Options options = CurrentOptions();
  2042. options.num_levels = 2;
  2043. options.IncreaseParallelism(20);
  2044. options.disable_auto_compactions = true;
  2045. DestroyAndReopen(options);
  2046. ASSERT_OK(Put(Key(0), "a"));
  2047. ASSERT_OK(Put(Key(5), "a"));
  2048. ASSERT_OK(Flush());
  2049. ASSERT_OK(Put(Key(10), "a"));
  2050. ASSERT_OK(Put(Key(15), "a"));
  2051. ASSERT_OK(Flush());
  2052. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  2053. // Trivial move 2 files to L1
  2054. ASSERT_EQ("0,2", FilesPerLevel());
  2055. std::function<void()> bg_manual_compact = [&]() {
  2056. std::string k1 = Key(6);
  2057. std::string k2 = Key(9);
  2058. Slice k1s(k1);
  2059. Slice k2s(k2);
  2060. CompactRangeOptions cro;
  2061. cro.exclusive_manual_compaction = false;
  2062. ASSERT_OK(db_->CompactRange(cro, &k1s, &k2s));
  2063. };
  2064. ROCKSDB_NAMESPACE::port::Thread bg_thread;
  2065. // While the compaction is running, we will create 2 new files that
  2066. // can fit in L1, these 2 files will be moved to L1 and overlap with
  2067. // the running compaction and break the LSM consistency.
  2068. std::atomic<bool> flag(false);
  2069. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  2070. "CompactionJob::Run():Start", [&](void* /*arg*/) {
  2071. if (flag.exchange(true)) {
  2072. // We want to make sure to call this callback only once
  2073. return;
  2074. }
  2075. ASSERT_OK(Put(Key(6), "a"));
  2076. ASSERT_OK(Put(Key(7), "a"));
  2077. ASSERT_OK(Flush());
  2078. ASSERT_OK(Put(Key(8), "a"));
  2079. ASSERT_OK(Put(Key(9), "a"));
  2080. ASSERT_OK(Flush());
  2081. // Start a non-exclusive manual compaction in a bg thread
  2082. bg_thread = port::Thread(bg_manual_compact);
  2083. // This manual compaction conflict with the other manual compaction
  2084. // so it should wait until the first compaction finish
  2085. env_->SleepForMicroseconds(1000000);
  2086. });
  2087. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  2088. // Run a manual compaction that will compact the 2 files in L1
  2089. // into 1 file in L1
  2090. CompactRangeOptions cro;
  2091. cro.exclusive_manual_compaction = false;
  2092. cro.bottommost_level_compaction = BottommostLevelCompaction::kForceOptimized;
  2093. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  2094. bg_thread.join();
  2095. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  2096. }
  2097. TEST_F(DBTest2, PausingManualCompaction1) {
  2098. Options options = CurrentOptions();
  2099. options.disable_auto_compactions = true;
  2100. options.num_levels = 7;
  2101. DestroyAndReopen(options);
  2102. Random rnd(301);
  2103. // Generate a file containing 10 keys.
  2104. for (int i = 0; i < 10; i++) {
  2105. ASSERT_OK(Put(Key(i), RandomString(&rnd, 50)));
  2106. }
  2107. ASSERT_OK(Flush());
  2108. // Generate another file containing same keys
  2109. for (int i = 0; i < 10; i++) {
  2110. ASSERT_OK(Put(Key(i), RandomString(&rnd, 50)));
  2111. }
  2112. ASSERT_OK(Flush());
  2113. int manual_compactions_paused = 0;
  2114. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  2115. "CompactionJob::Run():PausingManualCompaction:1", [&](void* arg) {
  2116. auto paused = reinterpret_cast<std::atomic<bool>*>(arg);
  2117. ASSERT_FALSE(paused->load(std::memory_order_acquire));
  2118. paused->store(true, std::memory_order_release);
  2119. manual_compactions_paused += 1;
  2120. });
  2121. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  2122. std::vector<std::string> files_before_compact, files_after_compact;
  2123. // Remember file name before compaction is triggered
  2124. std::vector<LiveFileMetaData> files_meta;
  2125. dbfull()->GetLiveFilesMetaData(&files_meta);
  2126. for (auto file : files_meta) {
  2127. files_before_compact.push_back(file.name);
  2128. }
  2129. // OK, now trigger a manual compaction
  2130. dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr);
  2131. // Wait for compactions to get scheduled and stopped
  2132. dbfull()->TEST_WaitForCompact(true);
  2133. // Get file names after compaction is stopped
  2134. files_meta.clear();
  2135. dbfull()->GetLiveFilesMetaData(&files_meta);
  2136. for (auto file : files_meta) {
  2137. files_after_compact.push_back(file.name);
  2138. }
  2139. // Like nothing happened
  2140. ASSERT_EQ(files_before_compact, files_after_compact);
  2141. ASSERT_EQ(manual_compactions_paused, 1);
  2142. manual_compactions_paused = 0;
  2143. // Now make sure CompactFiles also not run
  2144. dbfull()->CompactFiles(ROCKSDB_NAMESPACE::CompactionOptions(),
  2145. files_before_compact, 0);
  2146. // Wait for manual compaction to get scheduled and finish
  2147. dbfull()->TEST_WaitForCompact(true);
  2148. files_meta.clear();
  2149. files_after_compact.clear();
  2150. dbfull()->GetLiveFilesMetaData(&files_meta);
  2151. for (auto file : files_meta) {
  2152. files_after_compact.push_back(file.name);
  2153. }
  2154. ASSERT_EQ(files_before_compact, files_after_compact);
  2155. // CompactFiles returns at entry point
  2156. ASSERT_EQ(manual_compactions_paused, 0);
  2157. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  2158. }
  2159. // PausingManualCompaction does not affect auto compaction
  2160. TEST_F(DBTest2, PausingManualCompaction2) {
  2161. Options options = CurrentOptions();
  2162. options.level0_file_num_compaction_trigger = 2;
  2163. options.disable_auto_compactions = false;
  2164. DestroyAndReopen(options);
  2165. dbfull()->DisableManualCompaction();
  2166. Random rnd(301);
  2167. for (int i = 0; i < 2; i++) {
  2168. // Generate a file containing 10 keys.
  2169. for (int j = 0; j < 100; j++) {
  2170. ASSERT_OK(Put(Key(j), RandomString(&rnd, 50)));
  2171. }
  2172. ASSERT_OK(Flush());
  2173. }
  2174. ASSERT_OK(dbfull()->TEST_WaitForCompact(true));
  2175. std::vector<LiveFileMetaData> files_meta;
  2176. dbfull()->GetLiveFilesMetaData(&files_meta);
  2177. ASSERT_EQ(files_meta.size(), 1);
  2178. }
  2179. TEST_F(DBTest2, PausingManualCompaction3) {
  2180. CompactRangeOptions compact_options;
  2181. Options options = CurrentOptions();
  2182. options.disable_auto_compactions = true;
  2183. options.num_levels = 7;
  2184. Random rnd(301);
  2185. auto generate_files = [&]() {
  2186. for (int i = 0; i < options.num_levels; i++) {
  2187. for (int j = 0; j < options.num_levels - i + 1; j++) {
  2188. for (int k = 0; k < 1000; k++) {
  2189. ASSERT_OK(Put(Key(k + j * 1000), RandomString(&rnd, 50)));
  2190. }
  2191. Flush();
  2192. }
  2193. for (int l = 1; l < options.num_levels - i; l++) {
  2194. MoveFilesToLevel(l);
  2195. }
  2196. }
  2197. };
  2198. DestroyAndReopen(options);
  2199. generate_files();
  2200. #ifndef ROCKSDB_LITE
  2201. ASSERT_EQ("2,3,4,5,6,7,8", FilesPerLevel());
  2202. #endif // !ROCKSDB_LITE
  2203. int run_manual_compactions = 0;
  2204. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  2205. "CompactionJob::Run():PausingManualCompaction:1",
  2206. [&](void* /*arg*/) { run_manual_compactions++; });
  2207. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  2208. dbfull()->DisableManualCompaction();
  2209. dbfull()->CompactRange(compact_options, nullptr, nullptr);
  2210. dbfull()->TEST_WaitForCompact(true);
  2211. // As manual compaction disabled, not even reach sync point
  2212. ASSERT_EQ(run_manual_compactions, 0);
  2213. #ifndef ROCKSDB_LITE
  2214. ASSERT_EQ("2,3,4,5,6,7,8", FilesPerLevel());
  2215. #endif // !ROCKSDB_LITE
  2216. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearCallBack(
  2217. "CompactionJob::Run():PausingManualCompaction:1");
  2218. dbfull()->EnableManualCompaction();
  2219. dbfull()->CompactRange(compact_options, nullptr, nullptr);
  2220. dbfull()->TEST_WaitForCompact(true);
  2221. #ifndef ROCKSDB_LITE
  2222. ASSERT_EQ("0,0,0,0,0,0,2", FilesPerLevel());
  2223. #endif // !ROCKSDB_LITE
  2224. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  2225. }
  2226. TEST_F(DBTest2, PausingManualCompaction4) {
  2227. CompactRangeOptions compact_options;
  2228. Options options = CurrentOptions();
  2229. options.disable_auto_compactions = true;
  2230. options.num_levels = 7;
  2231. Random rnd(301);
  2232. auto generate_files = [&]() {
  2233. for (int i = 0; i < options.num_levels; i++) {
  2234. for (int j = 0; j < options.num_levels - i + 1; j++) {
  2235. for (int k = 0; k < 1000; k++) {
  2236. ASSERT_OK(Put(Key(k + j * 1000), RandomString(&rnd, 50)));
  2237. }
  2238. Flush();
  2239. }
  2240. for (int l = 1; l < options.num_levels - i; l++) {
  2241. MoveFilesToLevel(l);
  2242. }
  2243. }
  2244. };
  2245. DestroyAndReopen(options);
  2246. generate_files();
  2247. #ifndef ROCKSDB_LITE
  2248. ASSERT_EQ("2,3,4,5,6,7,8", FilesPerLevel());
  2249. #endif // !ROCKSDB_LITE
  2250. int run_manual_compactions = 0;
  2251. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  2252. "CompactionJob::Run():PausingManualCompaction:2", [&](void* arg) {
  2253. auto paused = reinterpret_cast<std::atomic<bool>*>(arg);
  2254. ASSERT_FALSE(paused->load(std::memory_order_acquire));
  2255. paused->store(true, std::memory_order_release);
  2256. run_manual_compactions++;
  2257. });
  2258. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  2259. dbfull()->EnableManualCompaction();
  2260. dbfull()->CompactRange(compact_options, nullptr, nullptr);
  2261. dbfull()->TEST_WaitForCompact(true);
  2262. ASSERT_EQ(run_manual_compactions, 1);
  2263. #ifndef ROCKSDB_LITE
  2264. ASSERT_EQ("2,3,4,5,6,7,8", FilesPerLevel());
  2265. #endif // !ROCKSDB_LITE
  2266. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearCallBack(
  2267. "CompactionJob::Run():PausingManualCompaction:2");
  2268. dbfull()->EnableManualCompaction();
  2269. dbfull()->CompactRange(compact_options, nullptr, nullptr);
  2270. dbfull()->TEST_WaitForCompact(true);
  2271. #ifndef ROCKSDB_LITE
  2272. ASSERT_EQ("0,0,0,0,0,0,2", FilesPerLevel());
  2273. #endif // !ROCKSDB_LITE
  2274. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  2275. }
  2276. TEST_F(DBTest2, OptimizeForPointLookup) {
  2277. Options options = CurrentOptions();
  2278. Close();
  2279. options.OptimizeForPointLookup(2);
  2280. ASSERT_OK(DB::Open(options, dbname_, &db_));
  2281. ASSERT_OK(Put("foo", "v1"));
  2282. ASSERT_EQ("v1", Get("foo"));
  2283. Flush();
  2284. ASSERT_EQ("v1", Get("foo"));
  2285. }
  2286. TEST_F(DBTest2, OptimizeForSmallDB) {
  2287. Options options = CurrentOptions();
  2288. Close();
  2289. options.OptimizeForSmallDb();
  2290. // Find the cache object
  2291. ASSERT_EQ(std::string(BlockBasedTableFactory::kName),
  2292. std::string(options.table_factory->Name()));
  2293. BlockBasedTableOptions* table_options =
  2294. reinterpret_cast<BlockBasedTableOptions*>(
  2295. options.table_factory->GetOptions());
  2296. ASSERT_TRUE(table_options != nullptr);
  2297. std::shared_ptr<Cache> cache = table_options->block_cache;
  2298. ASSERT_EQ(0, cache->GetUsage());
  2299. ASSERT_OK(DB::Open(options, dbname_, &db_));
  2300. ASSERT_OK(Put("foo", "v1"));
  2301. // memtable size is costed to the block cache
  2302. ASSERT_NE(0, cache->GetUsage());
  2303. ASSERT_EQ("v1", Get("foo"));
  2304. Flush();
  2305. size_t prev_size = cache->GetUsage();
  2306. // Remember block cache size, so that we can find that
  2307. // it is filled after Get().
  2308. // Use pinnable slice so that it can ping the block so that
  2309. // when we check the size it is not evicted.
  2310. PinnableSlice value;
  2311. ASSERT_OK(db_->Get(ReadOptions(), db_->DefaultColumnFamily(), "foo", &value));
  2312. ASSERT_GT(cache->GetUsage(), prev_size);
  2313. value.Reset();
  2314. }
  2315. #endif // ROCKSDB_LITE
  2316. TEST_F(DBTest2, GetRaceFlush1) {
  2317. ASSERT_OK(Put("foo", "v1"));
  2318. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
  2319. {{"DBImpl::GetImpl:1", "DBTest2::GetRaceFlush:1"},
  2320. {"DBTest2::GetRaceFlush:2", "DBImpl::GetImpl:2"}});
  2321. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  2322. ROCKSDB_NAMESPACE::port::Thread t1([&] {
  2323. TEST_SYNC_POINT("DBTest2::GetRaceFlush:1");
  2324. ASSERT_OK(Put("foo", "v2"));
  2325. Flush();
  2326. TEST_SYNC_POINT("DBTest2::GetRaceFlush:2");
  2327. });
  2328. // Get() is issued after the first Put(), so it should see either
  2329. // "v1" or "v2".
  2330. ASSERT_NE("NOT_FOUND", Get("foo"));
  2331. t1.join();
  2332. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  2333. }
  2334. TEST_F(DBTest2, GetRaceFlush2) {
  2335. ASSERT_OK(Put("foo", "v1"));
  2336. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
  2337. {{"DBImpl::GetImpl:3", "DBTest2::GetRaceFlush:1"},
  2338. {"DBTest2::GetRaceFlush:2", "DBImpl::GetImpl:4"}});
  2339. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  2340. port::Thread t1([&] {
  2341. TEST_SYNC_POINT("DBTest2::GetRaceFlush:1");
  2342. ASSERT_OK(Put("foo", "v2"));
  2343. Flush();
  2344. TEST_SYNC_POINT("DBTest2::GetRaceFlush:2");
  2345. });
  2346. // Get() is issued after the first Put(), so it should see either
  2347. // "v1" or "v2".
  2348. ASSERT_NE("NOT_FOUND", Get("foo"));
  2349. t1.join();
  2350. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  2351. }
  2352. TEST_F(DBTest2, DirectIO) {
  2353. if (!IsDirectIOSupported()) {
  2354. return;
  2355. }
  2356. Options options = CurrentOptions();
  2357. options.use_direct_reads = options.use_direct_io_for_flush_and_compaction =
  2358. true;
  2359. options.allow_mmap_reads = options.allow_mmap_writes = false;
  2360. DestroyAndReopen(options);
  2361. ASSERT_OK(Put(Key(0), "a"));
  2362. ASSERT_OK(Put(Key(5), "a"));
  2363. ASSERT_OK(Flush());
  2364. ASSERT_OK(Put(Key(10), "a"));
  2365. ASSERT_OK(Put(Key(15), "a"));
  2366. ASSERT_OK(Flush());
  2367. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  2368. Reopen(options);
  2369. }
  2370. TEST_F(DBTest2, MemtableOnlyIterator) {
  2371. Options options = CurrentOptions();
  2372. CreateAndReopenWithCF({"pikachu"}, options);
  2373. ASSERT_OK(Put(1, "foo", "first"));
  2374. ASSERT_OK(Put(1, "bar", "second"));
  2375. ReadOptions ropt;
  2376. ropt.read_tier = kMemtableTier;
  2377. std::string value;
  2378. Iterator* it = nullptr;
  2379. // Before flushing
  2380. // point lookups
  2381. ASSERT_OK(db_->Get(ropt, handles_[1], "foo", &value));
  2382. ASSERT_EQ("first", value);
  2383. ASSERT_OK(db_->Get(ropt, handles_[1], "bar", &value));
  2384. ASSERT_EQ("second", value);
  2385. // Memtable-only iterator (read_tier=kMemtableTier); data not flushed yet.
  2386. it = db_->NewIterator(ropt, handles_[1]);
  2387. int count = 0;
  2388. for (it->SeekToFirst(); it->Valid(); it->Next()) {
  2389. ASSERT_TRUE(it->Valid());
  2390. count++;
  2391. }
  2392. ASSERT_TRUE(!it->Valid());
  2393. ASSERT_EQ(2, count);
  2394. delete it;
  2395. Flush(1);
  2396. // After flushing
  2397. // point lookups
  2398. ASSERT_OK(db_->Get(ropt, handles_[1], "foo", &value));
  2399. ASSERT_EQ("first", value);
  2400. ASSERT_OK(db_->Get(ropt, handles_[1], "bar", &value));
  2401. ASSERT_EQ("second", value);
  2402. // nothing should be returned using memtable-only iterator after flushing.
  2403. it = db_->NewIterator(ropt, handles_[1]);
  2404. count = 0;
  2405. for (it->SeekToFirst(); it->Valid(); it->Next()) {
  2406. ASSERT_TRUE(it->Valid());
  2407. count++;
  2408. }
  2409. ASSERT_TRUE(!it->Valid());
  2410. ASSERT_EQ(0, count);
  2411. delete it;
  2412. // Add a key to memtable
  2413. ASSERT_OK(Put(1, "foobar", "third"));
  2414. it = db_->NewIterator(ropt, handles_[1]);
  2415. count = 0;
  2416. for (it->SeekToFirst(); it->Valid(); it->Next()) {
  2417. ASSERT_TRUE(it->Valid());
  2418. ASSERT_EQ("foobar", it->key().ToString());
  2419. ASSERT_EQ("third", it->value().ToString());
  2420. count++;
  2421. }
  2422. ASSERT_TRUE(!it->Valid());
  2423. ASSERT_EQ(1, count);
  2424. delete it;
  2425. }
  2426. TEST_F(DBTest2, LowPriWrite) {
  2427. Options options = CurrentOptions();
  2428. // Compaction pressure should trigger since 6 files
  2429. options.level0_file_num_compaction_trigger = 4;
  2430. options.level0_slowdown_writes_trigger = 12;
  2431. options.level0_stop_writes_trigger = 30;
  2432. options.delayed_write_rate = 8 * 1024 * 1024;
  2433. Reopen(options);
  2434. std::atomic<int> rate_limit_count(0);
  2435. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  2436. "GenericRateLimiter::Request:1", [&](void* arg) {
  2437. rate_limit_count.fetch_add(1);
  2438. int64_t* rate_bytes_per_sec = static_cast<int64_t*>(arg);
  2439. ASSERT_EQ(1024 * 1024, *rate_bytes_per_sec);
  2440. });
  2441. // Block compaction
  2442. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency({
  2443. {"DBTest.LowPriWrite:0", "DBImpl::BGWorkCompaction"},
  2444. });
  2445. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  2446. WriteOptions wo;
  2447. for (int i = 0; i < 6; i++) {
  2448. wo.low_pri = false;
  2449. Put("", "", wo);
  2450. wo.low_pri = true;
  2451. Put("", "", wo);
  2452. Flush();
  2453. }
  2454. ASSERT_EQ(0, rate_limit_count.load());
  2455. wo.low_pri = true;
  2456. Put("", "", wo);
  2457. ASSERT_EQ(1, rate_limit_count.load());
  2458. wo.low_pri = false;
  2459. Put("", "", wo);
  2460. ASSERT_EQ(1, rate_limit_count.load());
  2461. TEST_SYNC_POINT("DBTest.LowPriWrite:0");
  2462. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  2463. dbfull()->TEST_WaitForCompact();
  2464. wo.low_pri = true;
  2465. Put("", "", wo);
  2466. ASSERT_EQ(1, rate_limit_count.load());
  2467. wo.low_pri = false;
  2468. Put("", "", wo);
  2469. ASSERT_EQ(1, rate_limit_count.load());
  2470. }
  2471. #ifndef ROCKSDB_LITE
  2472. TEST_F(DBTest2, RateLimitedCompactionReads) {
  2473. // compaction input has 512KB data
  2474. const int kNumKeysPerFile = 128;
  2475. const int kBytesPerKey = 1024;
  2476. const int kNumL0Files = 4;
  2477. for (auto use_direct_io : {false, true}) {
  2478. if (use_direct_io && !IsDirectIOSupported()) {
  2479. continue;
  2480. }
  2481. Options options = CurrentOptions();
  2482. options.compression = kNoCompression;
  2483. options.level0_file_num_compaction_trigger = kNumL0Files;
  2484. options.memtable_factory.reset(new SpecialSkipListFactory(kNumKeysPerFile));
  2485. options.new_table_reader_for_compaction_inputs = true;
  2486. // takes roughly one second, split into 100 x 10ms intervals. Each interval
  2487. // permits 5.12KB, which is smaller than the block size, so this test
  2488. // exercises the code for chunking reads.
  2489. options.rate_limiter.reset(NewGenericRateLimiter(
  2490. static_cast<int64_t>(kNumL0Files * kNumKeysPerFile *
  2491. kBytesPerKey) /* rate_bytes_per_sec */,
  2492. 10 * 1000 /* refill_period_us */, 10 /* fairness */,
  2493. RateLimiter::Mode::kReadsOnly));
  2494. options.use_direct_reads = options.use_direct_io_for_flush_and_compaction =
  2495. use_direct_io;
  2496. BlockBasedTableOptions bbto;
  2497. bbto.block_size = 16384;
  2498. bbto.no_block_cache = true;
  2499. options.table_factory.reset(new BlockBasedTableFactory(bbto));
  2500. DestroyAndReopen(options);
  2501. for (int i = 0; i < kNumL0Files; ++i) {
  2502. for (int j = 0; j <= kNumKeysPerFile; ++j) {
  2503. ASSERT_OK(Put(Key(j), DummyString(kBytesPerKey)));
  2504. }
  2505. dbfull()->TEST_WaitForFlushMemTable();
  2506. ASSERT_EQ(i + 1, NumTableFilesAtLevel(0));
  2507. }
  2508. dbfull()->TEST_WaitForCompact();
  2509. ASSERT_EQ(0, NumTableFilesAtLevel(0));
  2510. ASSERT_EQ(0, options.rate_limiter->GetTotalBytesThrough(Env::IO_HIGH));
  2511. // should be slightly above 512KB due to non-data blocks read. Arbitrarily
  2512. // chose 1MB as the upper bound on the total bytes read.
  2513. size_t rate_limited_bytes =
  2514. options.rate_limiter->GetTotalBytesThrough(Env::IO_LOW);
  2515. // Include the explicit prefetch of the footer in direct I/O case.
  2516. size_t direct_io_extra = use_direct_io ? 512 * 1024 : 0;
  2517. ASSERT_GE(
  2518. rate_limited_bytes,
  2519. static_cast<size_t>(kNumKeysPerFile * kBytesPerKey * kNumL0Files));
  2520. ASSERT_LT(
  2521. rate_limited_bytes,
  2522. static_cast<size_t>(2 * kNumKeysPerFile * kBytesPerKey * kNumL0Files +
  2523. direct_io_extra));
  2524. Iterator* iter = db_->NewIterator(ReadOptions());
  2525. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  2526. ASSERT_EQ(iter->value().ToString(), DummyString(kBytesPerKey));
  2527. }
  2528. delete iter;
  2529. // bytes read for user iterator shouldn't count against the rate limit.
  2530. ASSERT_EQ(rate_limited_bytes,
  2531. static_cast<size_t>(
  2532. options.rate_limiter->GetTotalBytesThrough(Env::IO_LOW)));
  2533. }
  2534. }
  2535. #endif // ROCKSDB_LITE
  2536. // Make sure DB can be reopen with reduced number of levels, given no file
  2537. // is on levels higher than the new num_levels.
  2538. TEST_F(DBTest2, ReduceLevel) {
  2539. Options options;
  2540. options.disable_auto_compactions = true;
  2541. options.num_levels = 7;
  2542. Reopen(options);
  2543. Put("foo", "bar");
  2544. Flush();
  2545. MoveFilesToLevel(6);
  2546. #ifndef ROCKSDB_LITE
  2547. ASSERT_EQ("0,0,0,0,0,0,1", FilesPerLevel());
  2548. #endif // !ROCKSDB_LITE
  2549. CompactRangeOptions compact_options;
  2550. compact_options.change_level = true;
  2551. compact_options.target_level = 1;
  2552. dbfull()->CompactRange(compact_options, nullptr, nullptr);
  2553. #ifndef ROCKSDB_LITE
  2554. ASSERT_EQ("0,1", FilesPerLevel());
  2555. #endif // !ROCKSDB_LITE
  2556. options.num_levels = 3;
  2557. Reopen(options);
  2558. #ifndef ROCKSDB_LITE
  2559. ASSERT_EQ("0,1", FilesPerLevel());
  2560. #endif // !ROCKSDB_LITE
  2561. }
  2562. // Test that ReadCallback is actually used in both memtbale and sst tables
  2563. TEST_F(DBTest2, ReadCallbackTest) {
  2564. Options options;
  2565. options.disable_auto_compactions = true;
  2566. options.num_levels = 7;
  2567. Reopen(options);
  2568. std::vector<const Snapshot*> snapshots;
  2569. // Try to create a db with multiple layers and a memtable
  2570. const std::string key = "foo";
  2571. const std::string value = "bar";
  2572. // This test assumes that the seq start with 1 and increased by 1 after each
  2573. // write batch of size 1. If that behavior changes, the test needs to be
  2574. // updated as well.
  2575. // TODO(myabandeh): update this test to use the seq number that is returned by
  2576. // the DB instead of assuming what seq the DB used.
  2577. int i = 1;
  2578. for (; i < 10; i++) {
  2579. Put(key, value + std::to_string(i));
  2580. // Take a snapshot to avoid the value being removed during compaction
  2581. auto snapshot = dbfull()->GetSnapshot();
  2582. snapshots.push_back(snapshot);
  2583. }
  2584. Flush();
  2585. for (; i < 20; i++) {
  2586. Put(key, value + std::to_string(i));
  2587. // Take a snapshot to avoid the value being removed during compaction
  2588. auto snapshot = dbfull()->GetSnapshot();
  2589. snapshots.push_back(snapshot);
  2590. }
  2591. Flush();
  2592. MoveFilesToLevel(6);
  2593. #ifndef ROCKSDB_LITE
  2594. ASSERT_EQ("0,0,0,0,0,0,2", FilesPerLevel());
  2595. #endif // !ROCKSDB_LITE
  2596. for (; i < 30; i++) {
  2597. Put(key, value + std::to_string(i));
  2598. auto snapshot = dbfull()->GetSnapshot();
  2599. snapshots.push_back(snapshot);
  2600. }
  2601. Flush();
  2602. #ifndef ROCKSDB_LITE
  2603. ASSERT_EQ("1,0,0,0,0,0,2", FilesPerLevel());
  2604. #endif // !ROCKSDB_LITE
  2605. // And also add some values to the memtable
  2606. for (; i < 40; i++) {
  2607. Put(key, value + std::to_string(i));
  2608. auto snapshot = dbfull()->GetSnapshot();
  2609. snapshots.push_back(snapshot);
  2610. }
  2611. class TestReadCallback : public ReadCallback {
  2612. public:
  2613. explicit TestReadCallback(SequenceNumber snapshot)
  2614. : ReadCallback(snapshot), snapshot_(snapshot) {}
  2615. bool IsVisibleFullCheck(SequenceNumber seq) override {
  2616. return seq <= snapshot_;
  2617. }
  2618. private:
  2619. SequenceNumber snapshot_;
  2620. };
  2621. for (int seq = 1; seq < i; seq++) {
  2622. PinnableSlice pinnable_val;
  2623. ReadOptions roptions;
  2624. TestReadCallback callback(seq);
  2625. bool dont_care = true;
  2626. DBImpl::GetImplOptions get_impl_options;
  2627. get_impl_options.column_family = dbfull()->DefaultColumnFamily();
  2628. get_impl_options.value = &pinnable_val;
  2629. get_impl_options.value_found = &dont_care;
  2630. get_impl_options.callback = &callback;
  2631. Status s = dbfull()->GetImpl(roptions, key, get_impl_options);
  2632. ASSERT_TRUE(s.ok());
  2633. // Assuming that after each Put the DB increased seq by one, the value and
  2634. // seq number must be equal since we also inc value by 1 after each Put.
  2635. ASSERT_EQ(value + std::to_string(seq), pinnable_val.ToString());
  2636. }
  2637. for (auto snapshot : snapshots) {
  2638. dbfull()->ReleaseSnapshot(snapshot);
  2639. }
  2640. }
  2641. #ifndef ROCKSDB_LITE
  2642. TEST_F(DBTest2, LiveFilesOmitObsoleteFiles) {
  2643. // Regression test for race condition where an obsolete file is returned to
  2644. // user as a "live file" but then deleted, all while file deletions are
  2645. // disabled.
  2646. //
  2647. // It happened like this:
  2648. //
  2649. // 1. [flush thread] Log file "x.log" found by FindObsoleteFiles
  2650. // 2. [user thread] DisableFileDeletions, GetSortedWalFiles are called and the
  2651. // latter returned "x.log"
  2652. // 3. [flush thread] PurgeObsoleteFiles deleted "x.log"
  2653. // 4. [user thread] Reading "x.log" failed
  2654. //
  2655. // Unfortunately the only regression test I can come up with involves sleep.
  2656. // We cannot set SyncPoints to repro since, once the fix is applied, the
  2657. // SyncPoints would cause a deadlock as the repro's sequence of events is now
  2658. // prohibited.
  2659. //
  2660. // Instead, if we sleep for a second between Find and Purge, and ensure the
  2661. // read attempt happens after purge, then the sequence of events will almost
  2662. // certainly happen on the old code.
  2663. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency({
  2664. {"DBImpl::BackgroundCallFlush:FilesFound",
  2665. "DBTest2::LiveFilesOmitObsoleteFiles:FlushTriggered"},
  2666. {"DBImpl::PurgeObsoleteFiles:End",
  2667. "DBTest2::LiveFilesOmitObsoleteFiles:LiveFilesCaptured"},
  2668. });
  2669. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  2670. "DBImpl::PurgeObsoleteFiles:Begin",
  2671. [&](void* /*arg*/) { env_->SleepForMicroseconds(1000000); });
  2672. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  2673. Put("key", "val");
  2674. FlushOptions flush_opts;
  2675. flush_opts.wait = false;
  2676. db_->Flush(flush_opts);
  2677. TEST_SYNC_POINT("DBTest2::LiveFilesOmitObsoleteFiles:FlushTriggered");
  2678. db_->DisableFileDeletions();
  2679. VectorLogPtr log_files;
  2680. db_->GetSortedWalFiles(log_files);
  2681. TEST_SYNC_POINT("DBTest2::LiveFilesOmitObsoleteFiles:LiveFilesCaptured");
  2682. for (const auto& log_file : log_files) {
  2683. ASSERT_OK(env_->FileExists(LogFileName(dbname_, log_file->LogNumber())));
  2684. }
  2685. db_->EnableFileDeletions();
  2686. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  2687. }
  2688. TEST_F(DBTest2, TestNumPread) {
  2689. Options options = CurrentOptions();
  2690. // disable block cache
  2691. BlockBasedTableOptions table_options;
  2692. table_options.no_block_cache = true;
  2693. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2694. Reopen(options);
  2695. env_->count_random_reads_ = true;
  2696. env_->random_file_open_counter_.store(0);
  2697. ASSERT_OK(Put("bar", "foo"));
  2698. ASSERT_OK(Put("foo", "bar"));
  2699. ASSERT_OK(Flush());
  2700. // After flush, we'll open the file and read footer, meta block,
  2701. // property block and index block.
  2702. ASSERT_EQ(4, env_->random_read_counter_.Read());
  2703. ASSERT_EQ(1, env_->random_file_open_counter_.load());
  2704. // One pread per a normal data block read
  2705. env_->random_file_open_counter_.store(0);
  2706. env_->random_read_counter_.Reset();
  2707. ASSERT_EQ("bar", Get("foo"));
  2708. ASSERT_EQ(1, env_->random_read_counter_.Read());
  2709. // All files are already opened.
  2710. ASSERT_EQ(0, env_->random_file_open_counter_.load());
  2711. env_->random_file_open_counter_.store(0);
  2712. env_->random_read_counter_.Reset();
  2713. ASSERT_OK(Put("bar2", "foo2"));
  2714. ASSERT_OK(Put("foo2", "bar2"));
  2715. ASSERT_OK(Flush());
  2716. // After flush, we'll open the file and read footer, meta block,
  2717. // property block and index block.
  2718. ASSERT_EQ(4, env_->random_read_counter_.Read());
  2719. ASSERT_EQ(1, env_->random_file_open_counter_.load());
  2720. // Compaction needs two input blocks, which requires 2 preads, and
  2721. // generate a new SST file which needs 4 preads (footer, meta block,
  2722. // property block and index block). In total 6.
  2723. env_->random_file_open_counter_.store(0);
  2724. env_->random_read_counter_.Reset();
  2725. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  2726. ASSERT_EQ(6, env_->random_read_counter_.Read());
  2727. // All compactin input files should have already been opened.
  2728. ASSERT_EQ(1, env_->random_file_open_counter_.load());
  2729. // One pread per a normal data block read
  2730. env_->random_file_open_counter_.store(0);
  2731. env_->random_read_counter_.Reset();
  2732. ASSERT_EQ("foo2", Get("bar2"));
  2733. ASSERT_EQ(1, env_->random_read_counter_.Read());
  2734. // SST files are already opened.
  2735. ASSERT_EQ(0, env_->random_file_open_counter_.load());
  2736. }
  2737. TEST_F(DBTest2, TraceAndReplay) {
  2738. Options options = CurrentOptions();
  2739. options.merge_operator = MergeOperators::CreatePutOperator();
  2740. ReadOptions ro;
  2741. WriteOptions wo;
  2742. TraceOptions trace_opts;
  2743. EnvOptions env_opts;
  2744. CreateAndReopenWithCF({"pikachu"}, options);
  2745. Random rnd(301);
  2746. Iterator* single_iter = nullptr;
  2747. ASSERT_TRUE(db_->EndTrace().IsIOError());
  2748. std::string trace_filename = dbname_ + "/rocksdb.trace";
  2749. std::unique_ptr<TraceWriter> trace_writer;
  2750. ASSERT_OK(NewFileTraceWriter(env_, env_opts, trace_filename, &trace_writer));
  2751. ASSERT_OK(db_->StartTrace(trace_opts, std::move(trace_writer)));
  2752. ASSERT_OK(Put(0, "a", "1"));
  2753. ASSERT_OK(Merge(0, "b", "2"));
  2754. ASSERT_OK(Delete(0, "c"));
  2755. ASSERT_OK(SingleDelete(0, "d"));
  2756. ASSERT_OK(db_->DeleteRange(wo, dbfull()->DefaultColumnFamily(), "e", "f"));
  2757. WriteBatch batch;
  2758. ASSERT_OK(batch.Put("f", "11"));
  2759. ASSERT_OK(batch.Merge("g", "12"));
  2760. ASSERT_OK(batch.Delete("h"));
  2761. ASSERT_OK(batch.SingleDelete("i"));
  2762. ASSERT_OK(batch.DeleteRange("j", "k"));
  2763. ASSERT_OK(db_->Write(wo, &batch));
  2764. single_iter = db_->NewIterator(ro);
  2765. single_iter->Seek("f");
  2766. single_iter->SeekForPrev("g");
  2767. delete single_iter;
  2768. ASSERT_EQ("1", Get(0, "a"));
  2769. ASSERT_EQ("12", Get(0, "g"));
  2770. ASSERT_OK(Put(1, "foo", "bar"));
  2771. ASSERT_OK(Put(1, "rocksdb", "rocks"));
  2772. ASSERT_EQ("NOT_FOUND", Get(1, "leveldb"));
  2773. ASSERT_OK(db_->EndTrace());
  2774. // These should not get into the trace file as it is after EndTrace.
  2775. Put("hello", "world");
  2776. Merge("foo", "bar");
  2777. // Open another db, replay, and verify the data
  2778. std::string value;
  2779. std::string dbname2 = test::TmpDir(env_) + "/db_replay";
  2780. ASSERT_OK(DestroyDB(dbname2, options));
  2781. // Using a different name than db2, to pacify infer's use-after-lifetime
  2782. // warnings (http://fbinfer.com).
  2783. DB* db2_init = nullptr;
  2784. options.create_if_missing = true;
  2785. ASSERT_OK(DB::Open(options, dbname2, &db2_init));
  2786. ColumnFamilyHandle* cf;
  2787. ASSERT_OK(
  2788. db2_init->CreateColumnFamily(ColumnFamilyOptions(), "pikachu", &cf));
  2789. delete cf;
  2790. delete db2_init;
  2791. DB* db2 = nullptr;
  2792. std::vector<ColumnFamilyDescriptor> column_families;
  2793. ColumnFamilyOptions cf_options;
  2794. cf_options.merge_operator = MergeOperators::CreatePutOperator();
  2795. column_families.push_back(ColumnFamilyDescriptor("default", cf_options));
  2796. column_families.push_back(
  2797. ColumnFamilyDescriptor("pikachu", ColumnFamilyOptions()));
  2798. std::vector<ColumnFamilyHandle*> handles;
  2799. ASSERT_OK(DB::Open(DBOptions(), dbname2, column_families, &handles, &db2));
  2800. env_->SleepForMicroseconds(100);
  2801. // Verify that the keys don't already exist
  2802. ASSERT_TRUE(db2->Get(ro, handles[0], "a", &value).IsNotFound());
  2803. ASSERT_TRUE(db2->Get(ro, handles[0], "g", &value).IsNotFound());
  2804. std::unique_ptr<TraceReader> trace_reader;
  2805. ASSERT_OK(NewFileTraceReader(env_, env_opts, trace_filename, &trace_reader));
  2806. Replayer replayer(db2, handles_, std::move(trace_reader));
  2807. ASSERT_OK(replayer.Replay());
  2808. ASSERT_OK(db2->Get(ro, handles[0], "a", &value));
  2809. ASSERT_EQ("1", value);
  2810. ASSERT_OK(db2->Get(ro, handles[0], "g", &value));
  2811. ASSERT_EQ("12", value);
  2812. ASSERT_TRUE(db2->Get(ro, handles[0], "hello", &value).IsNotFound());
  2813. ASSERT_TRUE(db2->Get(ro, handles[0], "world", &value).IsNotFound());
  2814. ASSERT_OK(db2->Get(ro, handles[1], "foo", &value));
  2815. ASSERT_EQ("bar", value);
  2816. ASSERT_OK(db2->Get(ro, handles[1], "rocksdb", &value));
  2817. ASSERT_EQ("rocks", value);
  2818. for (auto handle : handles) {
  2819. delete handle;
  2820. }
  2821. delete db2;
  2822. ASSERT_OK(DestroyDB(dbname2, options));
  2823. }
  2824. TEST_F(DBTest2, TraceWithLimit) {
  2825. Options options = CurrentOptions();
  2826. options.merge_operator = MergeOperators::CreatePutOperator();
  2827. ReadOptions ro;
  2828. WriteOptions wo;
  2829. TraceOptions trace_opts;
  2830. EnvOptions env_opts;
  2831. CreateAndReopenWithCF({"pikachu"}, options);
  2832. Random rnd(301);
  2833. // test the max trace file size options
  2834. trace_opts.max_trace_file_size = 5;
  2835. std::string trace_filename = dbname_ + "/rocksdb.trace1";
  2836. std::unique_ptr<TraceWriter> trace_writer;
  2837. ASSERT_OK(NewFileTraceWriter(env_, env_opts, trace_filename, &trace_writer));
  2838. ASSERT_OK(db_->StartTrace(trace_opts, std::move(trace_writer)));
  2839. ASSERT_OK(Put(0, "a", "1"));
  2840. ASSERT_OK(Put(0, "b", "1"));
  2841. ASSERT_OK(Put(0, "c", "1"));
  2842. ASSERT_OK(db_->EndTrace());
  2843. std::string dbname2 = test::TmpDir(env_) + "/db_replay2";
  2844. std::string value;
  2845. ASSERT_OK(DestroyDB(dbname2, options));
  2846. // Using a different name than db2, to pacify infer's use-after-lifetime
  2847. // warnings (http://fbinfer.com).
  2848. DB* db2_init = nullptr;
  2849. options.create_if_missing = true;
  2850. ASSERT_OK(DB::Open(options, dbname2, &db2_init));
  2851. ColumnFamilyHandle* cf;
  2852. ASSERT_OK(
  2853. db2_init->CreateColumnFamily(ColumnFamilyOptions(), "pikachu", &cf));
  2854. delete cf;
  2855. delete db2_init;
  2856. DB* db2 = nullptr;
  2857. std::vector<ColumnFamilyDescriptor> column_families;
  2858. ColumnFamilyOptions cf_options;
  2859. cf_options.merge_operator = MergeOperators::CreatePutOperator();
  2860. column_families.push_back(ColumnFamilyDescriptor("default", cf_options));
  2861. column_families.push_back(
  2862. ColumnFamilyDescriptor("pikachu", ColumnFamilyOptions()));
  2863. std::vector<ColumnFamilyHandle*> handles;
  2864. ASSERT_OK(DB::Open(DBOptions(), dbname2, column_families, &handles, &db2));
  2865. env_->SleepForMicroseconds(100);
  2866. // Verify that the keys don't already exist
  2867. ASSERT_TRUE(db2->Get(ro, handles[0], "a", &value).IsNotFound());
  2868. ASSERT_TRUE(db2->Get(ro, handles[0], "b", &value).IsNotFound());
  2869. ASSERT_TRUE(db2->Get(ro, handles[0], "c", &value).IsNotFound());
  2870. std::unique_ptr<TraceReader> trace_reader;
  2871. ASSERT_OK(NewFileTraceReader(env_, env_opts, trace_filename, &trace_reader));
  2872. Replayer replayer(db2, handles_, std::move(trace_reader));
  2873. ASSERT_OK(replayer.Replay());
  2874. ASSERT_TRUE(db2->Get(ro, handles[0], "a", &value).IsNotFound());
  2875. ASSERT_TRUE(db2->Get(ro, handles[0], "b", &value).IsNotFound());
  2876. ASSERT_TRUE(db2->Get(ro, handles[0], "c", &value).IsNotFound());
  2877. for (auto handle : handles) {
  2878. delete handle;
  2879. }
  2880. delete db2;
  2881. ASSERT_OK(DestroyDB(dbname2, options));
  2882. }
  2883. TEST_F(DBTest2, TraceWithSampling) {
  2884. Options options = CurrentOptions();
  2885. ReadOptions ro;
  2886. WriteOptions wo;
  2887. TraceOptions trace_opts;
  2888. EnvOptions env_opts;
  2889. CreateAndReopenWithCF({"pikachu"}, options);
  2890. Random rnd(301);
  2891. // test the trace file sampling options
  2892. trace_opts.sampling_frequency = 2;
  2893. std::string trace_filename = dbname_ + "/rocksdb.trace_sampling";
  2894. std::unique_ptr<TraceWriter> trace_writer;
  2895. ASSERT_OK(NewFileTraceWriter(env_, env_opts, trace_filename, &trace_writer));
  2896. ASSERT_OK(db_->StartTrace(trace_opts, std::move(trace_writer)));
  2897. ASSERT_OK(Put(0, "a", "1"));
  2898. ASSERT_OK(Put(0, "b", "2"));
  2899. ASSERT_OK(Put(0, "c", "3"));
  2900. ASSERT_OK(Put(0, "d", "4"));
  2901. ASSERT_OK(Put(0, "e", "5"));
  2902. ASSERT_OK(db_->EndTrace());
  2903. std::string dbname2 = test::TmpDir(env_) + "/db_replay_sampling";
  2904. std::string value;
  2905. ASSERT_OK(DestroyDB(dbname2, options));
  2906. // Using a different name than db2, to pacify infer's use-after-lifetime
  2907. // warnings (http://fbinfer.com).
  2908. DB* db2_init = nullptr;
  2909. options.create_if_missing = true;
  2910. ASSERT_OK(DB::Open(options, dbname2, &db2_init));
  2911. ColumnFamilyHandle* cf;
  2912. ASSERT_OK(
  2913. db2_init->CreateColumnFamily(ColumnFamilyOptions(), "pikachu", &cf));
  2914. delete cf;
  2915. delete db2_init;
  2916. DB* db2 = nullptr;
  2917. std::vector<ColumnFamilyDescriptor> column_families;
  2918. ColumnFamilyOptions cf_options;
  2919. column_families.push_back(ColumnFamilyDescriptor("default", cf_options));
  2920. column_families.push_back(
  2921. ColumnFamilyDescriptor("pikachu", ColumnFamilyOptions()));
  2922. std::vector<ColumnFamilyHandle*> handles;
  2923. ASSERT_OK(DB::Open(DBOptions(), dbname2, column_families, &handles, &db2));
  2924. env_->SleepForMicroseconds(100);
  2925. ASSERT_TRUE(db2->Get(ro, handles[0], "a", &value).IsNotFound());
  2926. ASSERT_TRUE(db2->Get(ro, handles[0], "b", &value).IsNotFound());
  2927. ASSERT_TRUE(db2->Get(ro, handles[0], "c", &value).IsNotFound());
  2928. ASSERT_TRUE(db2->Get(ro, handles[0], "d", &value).IsNotFound());
  2929. ASSERT_TRUE(db2->Get(ro, handles[0], "e", &value).IsNotFound());
  2930. std::unique_ptr<TraceReader> trace_reader;
  2931. ASSERT_OK(NewFileTraceReader(env_, env_opts, trace_filename, &trace_reader));
  2932. Replayer replayer(db2, handles_, std::move(trace_reader));
  2933. ASSERT_OK(replayer.Replay());
  2934. ASSERT_TRUE(db2->Get(ro, handles[0], "a", &value).IsNotFound());
  2935. ASSERT_FALSE(db2->Get(ro, handles[0], "b", &value).IsNotFound());
  2936. ASSERT_TRUE(db2->Get(ro, handles[0], "c", &value).IsNotFound());
  2937. ASSERT_FALSE(db2->Get(ro, handles[0], "d", &value).IsNotFound());
  2938. ASSERT_TRUE(db2->Get(ro, handles[0], "e", &value).IsNotFound());
  2939. for (auto handle : handles) {
  2940. delete handle;
  2941. }
  2942. delete db2;
  2943. ASSERT_OK(DestroyDB(dbname2, options));
  2944. }
  2945. TEST_F(DBTest2, TraceWithFilter) {
  2946. Options options = CurrentOptions();
  2947. options.merge_operator = MergeOperators::CreatePutOperator();
  2948. ReadOptions ro;
  2949. WriteOptions wo;
  2950. TraceOptions trace_opts;
  2951. EnvOptions env_opts;
  2952. CreateAndReopenWithCF({"pikachu"}, options);
  2953. Random rnd(301);
  2954. Iterator* single_iter = nullptr;
  2955. trace_opts.filter = TraceFilterType::kTraceFilterWrite;
  2956. std::string trace_filename = dbname_ + "/rocksdb.trace";
  2957. std::unique_ptr<TraceWriter> trace_writer;
  2958. ASSERT_OK(NewFileTraceWriter(env_, env_opts, trace_filename, &trace_writer));
  2959. ASSERT_OK(db_->StartTrace(trace_opts, std::move(trace_writer)));
  2960. ASSERT_OK(Put(0, "a", "1"));
  2961. ASSERT_OK(Merge(0, "b", "2"));
  2962. ASSERT_OK(Delete(0, "c"));
  2963. ASSERT_OK(SingleDelete(0, "d"));
  2964. ASSERT_OK(db_->DeleteRange(wo, dbfull()->DefaultColumnFamily(), "e", "f"));
  2965. WriteBatch batch;
  2966. ASSERT_OK(batch.Put("f", "11"));
  2967. ASSERT_OK(batch.Merge("g", "12"));
  2968. ASSERT_OK(batch.Delete("h"));
  2969. ASSERT_OK(batch.SingleDelete("i"));
  2970. ASSERT_OK(batch.DeleteRange("j", "k"));
  2971. ASSERT_OK(db_->Write(wo, &batch));
  2972. single_iter = db_->NewIterator(ro);
  2973. single_iter->Seek("f");
  2974. single_iter->SeekForPrev("g");
  2975. delete single_iter;
  2976. ASSERT_EQ("1", Get(0, "a"));
  2977. ASSERT_EQ("12", Get(0, "g"));
  2978. ASSERT_OK(Put(1, "foo", "bar"));
  2979. ASSERT_OK(Put(1, "rocksdb", "rocks"));
  2980. ASSERT_EQ("NOT_FOUND", Get(1, "leveldb"));
  2981. ASSERT_OK(db_->EndTrace());
  2982. // These should not get into the trace file as it is after EndTrace.
  2983. Put("hello", "world");
  2984. Merge("foo", "bar");
  2985. // Open another db, replay, and verify the data
  2986. std::string value;
  2987. std::string dbname2 = test::TmpDir(env_) + "/db_replay";
  2988. ASSERT_OK(DestroyDB(dbname2, options));
  2989. // Using a different name than db2, to pacify infer's use-after-lifetime
  2990. // warnings (http://fbinfer.com).
  2991. DB* db2_init = nullptr;
  2992. options.create_if_missing = true;
  2993. ASSERT_OK(DB::Open(options, dbname2, &db2_init));
  2994. ColumnFamilyHandle* cf;
  2995. ASSERT_OK(
  2996. db2_init->CreateColumnFamily(ColumnFamilyOptions(), "pikachu", &cf));
  2997. delete cf;
  2998. delete db2_init;
  2999. DB* db2 = nullptr;
  3000. std::vector<ColumnFamilyDescriptor> column_families;
  3001. ColumnFamilyOptions cf_options;
  3002. cf_options.merge_operator = MergeOperators::CreatePutOperator();
  3003. column_families.push_back(ColumnFamilyDescriptor("default", cf_options));
  3004. column_families.push_back(
  3005. ColumnFamilyDescriptor("pikachu", ColumnFamilyOptions()));
  3006. std::vector<ColumnFamilyHandle*> handles;
  3007. ASSERT_OK(DB::Open(DBOptions(), dbname2, column_families, &handles, &db2));
  3008. env_->SleepForMicroseconds(100);
  3009. // Verify that the keys don't already exist
  3010. ASSERT_TRUE(db2->Get(ro, handles[0], "a", &value).IsNotFound());
  3011. ASSERT_TRUE(db2->Get(ro, handles[0], "g", &value).IsNotFound());
  3012. std::unique_ptr<TraceReader> trace_reader;
  3013. ASSERT_OK(NewFileTraceReader(env_, env_opts, trace_filename, &trace_reader));
  3014. Replayer replayer(db2, handles_, std::move(trace_reader));
  3015. ASSERT_OK(replayer.Replay());
  3016. // All the key-values should not present since we filter out the WRITE ops.
  3017. ASSERT_TRUE(db2->Get(ro, handles[0], "a", &value).IsNotFound());
  3018. ASSERT_TRUE(db2->Get(ro, handles[0], "g", &value).IsNotFound());
  3019. ASSERT_TRUE(db2->Get(ro, handles[0], "hello", &value).IsNotFound());
  3020. ASSERT_TRUE(db2->Get(ro, handles[0], "world", &value).IsNotFound());
  3021. ASSERT_TRUE(db2->Get(ro, handles[0], "foo", &value).IsNotFound());
  3022. ASSERT_TRUE(db2->Get(ro, handles[0], "rocksdb", &value).IsNotFound());
  3023. for (auto handle : handles) {
  3024. delete handle;
  3025. }
  3026. delete db2;
  3027. ASSERT_OK(DestroyDB(dbname2, options));
  3028. // Set up a new db.
  3029. std::string dbname3 = test::TmpDir(env_) + "/db_not_trace_read";
  3030. ASSERT_OK(DestroyDB(dbname3, options));
  3031. DB* db3_init = nullptr;
  3032. options.create_if_missing = true;
  3033. ColumnFamilyHandle* cf3;
  3034. ASSERT_OK(DB::Open(options, dbname3, &db3_init));
  3035. ASSERT_OK(
  3036. db3_init->CreateColumnFamily(ColumnFamilyOptions(), "pikachu", &cf3));
  3037. delete cf3;
  3038. delete db3_init;
  3039. column_families.clear();
  3040. column_families.push_back(ColumnFamilyDescriptor("default", cf_options));
  3041. column_families.push_back(
  3042. ColumnFamilyDescriptor("pikachu", ColumnFamilyOptions()));
  3043. handles.clear();
  3044. DB* db3 = nullptr;
  3045. ASSERT_OK(DB::Open(DBOptions(), dbname3, column_families, &handles, &db3));
  3046. env_->SleepForMicroseconds(100);
  3047. // Verify that the keys don't already exist
  3048. ASSERT_TRUE(db3->Get(ro, handles[0], "a", &value).IsNotFound());
  3049. ASSERT_TRUE(db3->Get(ro, handles[0], "g", &value).IsNotFound());
  3050. //The tracer will not record the READ ops.
  3051. trace_opts.filter = TraceFilterType::kTraceFilterGet;
  3052. std::string trace_filename3 = dbname_ + "/rocksdb.trace_3";
  3053. std::unique_ptr<TraceWriter> trace_writer3;
  3054. ASSERT_OK(
  3055. NewFileTraceWriter(env_, env_opts, trace_filename3, &trace_writer3));
  3056. ASSERT_OK(db3->StartTrace(trace_opts, std::move(trace_writer3)));
  3057. ASSERT_OK(db3->Put(wo, handles[0], "a", "1"));
  3058. ASSERT_OK(db3->Merge(wo, handles[0], "b", "2"));
  3059. ASSERT_OK(db3->Delete(wo, handles[0], "c"));
  3060. ASSERT_OK(db3->SingleDelete(wo, handles[0], "d"));
  3061. ASSERT_OK(db3->Get(ro, handles[0], "a", &value));
  3062. ASSERT_EQ(value, "1");
  3063. ASSERT_TRUE(db3->Get(ro, handles[0], "c", &value).IsNotFound());
  3064. ASSERT_OK(db3->EndTrace());
  3065. for (auto handle : handles) {
  3066. delete handle;
  3067. }
  3068. delete db3;
  3069. ASSERT_OK(DestroyDB(dbname3, options));
  3070. std::unique_ptr<TraceReader> trace_reader3;
  3071. ASSERT_OK(
  3072. NewFileTraceReader(env_, env_opts, trace_filename3, &trace_reader3));
  3073. // Count the number of records in the trace file;
  3074. int count = 0;
  3075. std::string data;
  3076. Status s;
  3077. while (true) {
  3078. s = trace_reader3->Read(&data);
  3079. if (!s.ok()) {
  3080. break;
  3081. }
  3082. count += 1;
  3083. }
  3084. // We also need to count the header and footer
  3085. // 4 WRITE + HEADER + FOOTER = 6
  3086. ASSERT_EQ(count, 6);
  3087. }
  3088. #endif // ROCKSDB_LITE
  3089. TEST_F(DBTest2, PinnableSliceAndMmapReads) {
  3090. Options options = CurrentOptions();
  3091. options.allow_mmap_reads = true;
  3092. options.max_open_files = 100;
  3093. options.compression = kNoCompression;
  3094. Reopen(options);
  3095. ASSERT_OK(Put("foo", "bar"));
  3096. ASSERT_OK(Flush());
  3097. PinnableSlice pinned_value;
  3098. ASSERT_EQ(Get("foo", &pinned_value), Status::OK());
  3099. // It is not safe to pin mmap files as they might disappear by compaction
  3100. ASSERT_FALSE(pinned_value.IsPinned());
  3101. ASSERT_EQ(pinned_value.ToString(), "bar");
  3102. dbfull()->TEST_CompactRange(0 /* level */, nullptr /* begin */,
  3103. nullptr /* end */, nullptr /* column_family */,
  3104. true /* disallow_trivial_move */);
  3105. // Ensure pinned_value doesn't rely on memory munmap'd by the above
  3106. // compaction. It crashes if it does.
  3107. ASSERT_EQ(pinned_value.ToString(), "bar");
  3108. #ifndef ROCKSDB_LITE
  3109. pinned_value.Reset();
  3110. // Unsafe to pin mmap files when they could be kicked out of table cache
  3111. Close();
  3112. ASSERT_OK(ReadOnlyReopen(options));
  3113. ASSERT_EQ(Get("foo", &pinned_value), Status::OK());
  3114. ASSERT_FALSE(pinned_value.IsPinned());
  3115. ASSERT_EQ(pinned_value.ToString(), "bar");
  3116. pinned_value.Reset();
  3117. // In read-only mode with infinite capacity on table cache it should pin the
  3118. // value and avoid the memcpy
  3119. Close();
  3120. options.max_open_files = -1;
  3121. ASSERT_OK(ReadOnlyReopen(options));
  3122. ASSERT_EQ(Get("foo", &pinned_value), Status::OK());
  3123. ASSERT_TRUE(pinned_value.IsPinned());
  3124. ASSERT_EQ(pinned_value.ToString(), "bar");
  3125. #endif
  3126. }
  3127. TEST_F(DBTest2, DISABLED_IteratorPinnedMemory) {
  3128. Options options = CurrentOptions();
  3129. options.create_if_missing = true;
  3130. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  3131. BlockBasedTableOptions bbto;
  3132. bbto.no_block_cache = false;
  3133. bbto.cache_index_and_filter_blocks = false;
  3134. bbto.block_cache = NewLRUCache(100000);
  3135. bbto.block_size = 400; // small block size
  3136. options.table_factory.reset(new BlockBasedTableFactory(bbto));
  3137. Reopen(options);
  3138. Random rnd(301);
  3139. std::string v = RandomString(&rnd, 400);
  3140. // Since v is the size of a block, each key should take a block
  3141. // of 400+ bytes.
  3142. Put("1", v);
  3143. Put("3", v);
  3144. Put("5", v);
  3145. Put("7", v);
  3146. ASSERT_OK(Flush());
  3147. ASSERT_EQ(0, bbto.block_cache->GetPinnedUsage());
  3148. // Verify that iterators don't pin more than one data block in block cache
  3149. // at each time.
  3150. {
  3151. std::unique_ptr<Iterator> iter(db_->NewIterator(ReadOptions()));
  3152. iter->SeekToFirst();
  3153. for (int i = 0; i < 4; i++) {
  3154. ASSERT_TRUE(iter->Valid());
  3155. // Block cache should contain exactly one block.
  3156. ASSERT_GT(bbto.block_cache->GetPinnedUsage(), 0);
  3157. ASSERT_LT(bbto.block_cache->GetPinnedUsage(), 800);
  3158. iter->Next();
  3159. }
  3160. ASSERT_FALSE(iter->Valid());
  3161. iter->Seek("4");
  3162. ASSERT_TRUE(iter->Valid());
  3163. ASSERT_GT(bbto.block_cache->GetPinnedUsage(), 0);
  3164. ASSERT_LT(bbto.block_cache->GetPinnedUsage(), 800);
  3165. iter->Seek("3");
  3166. ASSERT_TRUE(iter->Valid());
  3167. ASSERT_GT(bbto.block_cache->GetPinnedUsage(), 0);
  3168. ASSERT_LT(bbto.block_cache->GetPinnedUsage(), 800);
  3169. }
  3170. ASSERT_EQ(0, bbto.block_cache->GetPinnedUsage());
  3171. // Test compaction case
  3172. Put("2", v);
  3173. Put("5", v);
  3174. Put("6", v);
  3175. Put("8", v);
  3176. ASSERT_OK(Flush());
  3177. // Clear existing data in block cache
  3178. bbto.block_cache->SetCapacity(0);
  3179. bbto.block_cache->SetCapacity(100000);
  3180. // Verify compaction input iterators don't hold more than one data blocks at
  3181. // one time.
  3182. std::atomic<bool> finished(false);
  3183. std::atomic<int> block_newed(0);
  3184. std::atomic<int> block_destroyed(0);
  3185. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  3186. "Block::Block:0", [&](void* /*arg*/) {
  3187. if (finished) {
  3188. return;
  3189. }
  3190. // Two iterators. At most 2 outstanding blocks.
  3191. EXPECT_GE(block_newed.load(), block_destroyed.load());
  3192. EXPECT_LE(block_newed.load(), block_destroyed.load() + 1);
  3193. block_newed.fetch_add(1);
  3194. });
  3195. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  3196. "Block::~Block", [&](void* /*arg*/) {
  3197. if (finished) {
  3198. return;
  3199. }
  3200. // Two iterators. At most 2 outstanding blocks.
  3201. EXPECT_GE(block_newed.load(), block_destroyed.load() + 1);
  3202. EXPECT_LE(block_newed.load(), block_destroyed.load() + 2);
  3203. block_destroyed.fetch_add(1);
  3204. });
  3205. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  3206. "CompactionJob::Run:BeforeVerify",
  3207. [&](void* /*arg*/) { finished = true; });
  3208. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  3209. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  3210. // Two input files. Each of them has 4 data blocks.
  3211. ASSERT_EQ(8, block_newed.load());
  3212. ASSERT_EQ(8, block_destroyed.load());
  3213. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  3214. }
  3215. TEST_F(DBTest2, TestBBTTailPrefetch) {
  3216. std::atomic<bool> called(false);
  3217. size_t expected_lower_bound = 512 * 1024;
  3218. size_t expected_higher_bound = 512 * 1024;
  3219. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  3220. "BlockBasedTable::Open::TailPrefetchLen", [&](void* arg) {
  3221. size_t* prefetch_size = static_cast<size_t*>(arg);
  3222. EXPECT_LE(expected_lower_bound, *prefetch_size);
  3223. EXPECT_GE(expected_higher_bound, *prefetch_size);
  3224. called = true;
  3225. });
  3226. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  3227. Put("1", "1");
  3228. Put("9", "1");
  3229. Flush();
  3230. expected_lower_bound = 0;
  3231. expected_higher_bound = 8 * 1024;
  3232. Put("1", "1");
  3233. Put("9", "1");
  3234. Flush();
  3235. Put("1", "1");
  3236. Put("9", "1");
  3237. Flush();
  3238. // Full compaction to make sure there is no L0 file after the open.
  3239. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  3240. ASSERT_TRUE(called.load());
  3241. called = false;
  3242. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  3243. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();
  3244. std::atomic<bool> first_call(true);
  3245. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  3246. "BlockBasedTable::Open::TailPrefetchLen", [&](void* arg) {
  3247. size_t* prefetch_size = static_cast<size_t*>(arg);
  3248. if (first_call) {
  3249. EXPECT_EQ(4 * 1024, *prefetch_size);
  3250. first_call = false;
  3251. } else {
  3252. EXPECT_GE(4 * 1024, *prefetch_size);
  3253. }
  3254. called = true;
  3255. });
  3256. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  3257. Options options = CurrentOptions();
  3258. options.max_file_opening_threads = 1; // one thread
  3259. BlockBasedTableOptions table_options;
  3260. table_options.cache_index_and_filter_blocks = true;
  3261. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  3262. options.max_open_files = -1;
  3263. Reopen(options);
  3264. Put("1", "1");
  3265. Put("9", "1");
  3266. Flush();
  3267. Put("1", "1");
  3268. Put("9", "1");
  3269. Flush();
  3270. ASSERT_TRUE(called.load());
  3271. called = false;
  3272. // Parallel loading SST files
  3273. options.max_file_opening_threads = 16;
  3274. Reopen(options);
  3275. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  3276. ASSERT_TRUE(called.load());
  3277. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  3278. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();
  3279. }
  3280. TEST_F(DBTest2, TestGetColumnFamilyHandleUnlocked) {
  3281. // Setup sync point dependency to reproduce the race condition of
  3282. // DBImpl::GetColumnFamilyHandleUnlocked
  3283. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency({
  3284. {"TestGetColumnFamilyHandleUnlocked::GetColumnFamilyHandleUnlocked1",
  3285. "TestGetColumnFamilyHandleUnlocked::PreGetColumnFamilyHandleUnlocked2"},
  3286. {"TestGetColumnFamilyHandleUnlocked::GetColumnFamilyHandleUnlocked2",
  3287. "TestGetColumnFamilyHandleUnlocked::ReadColumnFamilyHandle1"},
  3288. });
  3289. SyncPoint::GetInstance()->EnableProcessing();
  3290. CreateColumnFamilies({"test1", "test2"}, Options());
  3291. ASSERT_EQ(handles_.size(), 2);
  3292. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  3293. port::Thread user_thread1([&]() {
  3294. auto cfh = dbi->GetColumnFamilyHandleUnlocked(handles_[0]->GetID());
  3295. ASSERT_EQ(cfh->GetID(), handles_[0]->GetID());
  3296. TEST_SYNC_POINT("TestGetColumnFamilyHandleUnlocked::GetColumnFamilyHandleUnlocked1");
  3297. TEST_SYNC_POINT("TestGetColumnFamilyHandleUnlocked::ReadColumnFamilyHandle1");
  3298. ASSERT_EQ(cfh->GetID(), handles_[0]->GetID());
  3299. });
  3300. port::Thread user_thread2([&]() {
  3301. TEST_SYNC_POINT("TestGetColumnFamilyHandleUnlocked::PreGetColumnFamilyHandleUnlocked2");
  3302. auto cfh = dbi->GetColumnFamilyHandleUnlocked(handles_[1]->GetID());
  3303. ASSERT_EQ(cfh->GetID(), handles_[1]->GetID());
  3304. TEST_SYNC_POINT("TestGetColumnFamilyHandleUnlocked::GetColumnFamilyHandleUnlocked2");
  3305. ASSERT_EQ(cfh->GetID(), handles_[1]->GetID());
  3306. });
  3307. user_thread1.join();
  3308. user_thread2.join();
  3309. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  3310. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();
  3311. }
  3312. #ifndef ROCKSDB_LITE
  3313. TEST_F(DBTest2, TestCompactFiles) {
  3314. // Setup sync point dependency to reproduce the race condition of
  3315. // DBImpl::GetColumnFamilyHandleUnlocked
  3316. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency({
  3317. {"TestCompactFiles::IngestExternalFile1",
  3318. "TestCompactFiles::IngestExternalFile2"},
  3319. });
  3320. SyncPoint::GetInstance()->EnableProcessing();
  3321. Options options;
  3322. options.num_levels = 2;
  3323. options.disable_auto_compactions = true;
  3324. Reopen(options);
  3325. auto* handle = db_->DefaultColumnFamily();
  3326. ASSERT_EQ(db_->NumberLevels(handle), 2);
  3327. ROCKSDB_NAMESPACE::SstFileWriter sst_file_writer{
  3328. ROCKSDB_NAMESPACE::EnvOptions(), options};
  3329. std::string external_file1 = dbname_ + "/test_compact_files1.sst_t";
  3330. std::string external_file2 = dbname_ + "/test_compact_files2.sst_t";
  3331. std::string external_file3 = dbname_ + "/test_compact_files3.sst_t";
  3332. ASSERT_OK(sst_file_writer.Open(external_file1));
  3333. ASSERT_OK(sst_file_writer.Put("1", "1"));
  3334. ASSERT_OK(sst_file_writer.Put("2", "2"));
  3335. ASSERT_OK(sst_file_writer.Finish());
  3336. ASSERT_OK(sst_file_writer.Open(external_file2));
  3337. ASSERT_OK(sst_file_writer.Put("3", "3"));
  3338. ASSERT_OK(sst_file_writer.Put("4", "4"));
  3339. ASSERT_OK(sst_file_writer.Finish());
  3340. ASSERT_OK(sst_file_writer.Open(external_file3));
  3341. ASSERT_OK(sst_file_writer.Put("5", "5"));
  3342. ASSERT_OK(sst_file_writer.Put("6", "6"));
  3343. ASSERT_OK(sst_file_writer.Finish());
  3344. ASSERT_OK(db_->IngestExternalFile(handle, {external_file1, external_file3},
  3345. IngestExternalFileOptions()));
  3346. ASSERT_EQ(NumTableFilesAtLevel(1, 0), 2);
  3347. std::vector<std::string> files;
  3348. GetSstFiles(env_, dbname_, &files);
  3349. ASSERT_EQ(files.size(), 2);
  3350. port::Thread user_thread1(
  3351. [&]() { db_->CompactFiles(CompactionOptions(), handle, files, 1); });
  3352. port::Thread user_thread2([&]() {
  3353. ASSERT_OK(db_->IngestExternalFile(handle, {external_file2},
  3354. IngestExternalFileOptions()));
  3355. TEST_SYNC_POINT("TestCompactFiles::IngestExternalFile1");
  3356. });
  3357. user_thread1.join();
  3358. user_thread2.join();
  3359. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  3360. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();
  3361. }
  3362. #endif // ROCKSDB_LITE
  3363. // TODO: figure out why this test fails in appveyor
  3364. #ifndef OS_WIN
  3365. TEST_F(DBTest2, MultiDBParallelOpenTest) {
  3366. const int kNumDbs = 2;
  3367. Options options = CurrentOptions();
  3368. std::vector<std::string> dbnames;
  3369. for (int i = 0; i < kNumDbs; ++i) {
  3370. dbnames.emplace_back(test::TmpDir(env_) + "/db" + ToString(i));
  3371. ASSERT_OK(DestroyDB(dbnames.back(), options));
  3372. }
  3373. // Verify empty DBs can be created in parallel
  3374. std::vector<std::thread> open_threads;
  3375. std::vector<DB*> dbs{static_cast<unsigned int>(kNumDbs), nullptr};
  3376. options.create_if_missing = true;
  3377. for (int i = 0; i < kNumDbs; ++i) {
  3378. open_threads.emplace_back(
  3379. [&](int dbnum) {
  3380. ASSERT_OK(DB::Open(options, dbnames[dbnum], &dbs[dbnum]));
  3381. },
  3382. i);
  3383. }
  3384. // Now add some data and close, so next we can verify non-empty DBs can be
  3385. // recovered in parallel
  3386. for (int i = 0; i < kNumDbs; ++i) {
  3387. open_threads[i].join();
  3388. ASSERT_OK(dbs[i]->Put(WriteOptions(), "xi", "gua"));
  3389. delete dbs[i];
  3390. }
  3391. // Verify non-empty DBs can be recovered in parallel
  3392. dbs.clear();
  3393. open_threads.clear();
  3394. for (int i = 0; i < kNumDbs; ++i) {
  3395. open_threads.emplace_back(
  3396. [&](int dbnum) {
  3397. ASSERT_OK(DB::Open(options, dbnames[dbnum], &dbs[dbnum]));
  3398. },
  3399. i);
  3400. }
  3401. // Wait and cleanup
  3402. for (int i = 0; i < kNumDbs; ++i) {
  3403. open_threads[i].join();
  3404. delete dbs[i];
  3405. ASSERT_OK(DestroyDB(dbnames[i], options));
  3406. }
  3407. }
  3408. #endif // OS_WIN
  3409. namespace {
  3410. class DummyOldStats : public Statistics {
  3411. public:
  3412. uint64_t getTickerCount(uint32_t /*ticker_type*/) const override { return 0; }
  3413. void recordTick(uint32_t /* ticker_type */, uint64_t /* count */) override {
  3414. num_rt++;
  3415. }
  3416. void setTickerCount(uint32_t /*ticker_type*/, uint64_t /*count*/) override {}
  3417. uint64_t getAndResetTickerCount(uint32_t /*ticker_type*/) override {
  3418. return 0;
  3419. }
  3420. void measureTime(uint32_t /*histogram_type*/, uint64_t /*count*/) override {
  3421. num_mt++;
  3422. }
  3423. void histogramData(
  3424. uint32_t /*histogram_type*/,
  3425. ROCKSDB_NAMESPACE::HistogramData* const /*data*/) const override {}
  3426. std::string getHistogramString(uint32_t /*type*/) const override {
  3427. return "";
  3428. }
  3429. bool HistEnabledForType(uint32_t /*type*/) const override { return false; }
  3430. std::string ToString() const override { return ""; }
  3431. int num_rt = 0;
  3432. int num_mt = 0;
  3433. };
  3434. } // namespace
  3435. TEST_F(DBTest2, OldStatsInterface) {
  3436. DummyOldStats* dos = new DummyOldStats();
  3437. std::shared_ptr<Statistics> stats(dos);
  3438. Options options = CurrentOptions();
  3439. options.create_if_missing = true;
  3440. options.statistics = stats;
  3441. Reopen(options);
  3442. Put("foo", "bar");
  3443. ASSERT_EQ("bar", Get("foo"));
  3444. ASSERT_OK(Flush());
  3445. ASSERT_EQ("bar", Get("foo"));
  3446. ASSERT_GT(dos->num_rt, 0);
  3447. ASSERT_GT(dos->num_mt, 0);
  3448. }
  3449. TEST_F(DBTest2, CloseWithUnreleasedSnapshot) {
  3450. const Snapshot* ss = db_->GetSnapshot();
  3451. for (auto h : handles_) {
  3452. db_->DestroyColumnFamilyHandle(h);
  3453. }
  3454. handles_.clear();
  3455. ASSERT_NOK(db_->Close());
  3456. db_->ReleaseSnapshot(ss);
  3457. ASSERT_OK(db_->Close());
  3458. delete db_;
  3459. db_ = nullptr;
  3460. }
  3461. TEST_F(DBTest2, PrefixBloomReseek) {
  3462. Options options = CurrentOptions();
  3463. options.create_if_missing = true;
  3464. options.prefix_extractor.reset(NewCappedPrefixTransform(3));
  3465. BlockBasedTableOptions bbto;
  3466. bbto.filter_policy.reset(NewBloomFilterPolicy(10, false));
  3467. bbto.whole_key_filtering = false;
  3468. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  3469. DestroyAndReopen(options);
  3470. // Construct two L1 files with keys:
  3471. // f1:[aaa1 ccc1] f2:[ddd0]
  3472. ASSERT_OK(Put("aaa1", ""));
  3473. ASSERT_OK(Put("ccc1", ""));
  3474. ASSERT_OK(Flush());
  3475. ASSERT_OK(Put("ddd0", ""));
  3476. ASSERT_OK(Flush());
  3477. CompactRangeOptions cro;
  3478. cro.bottommost_level_compaction = BottommostLevelCompaction::kSkip;
  3479. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  3480. ASSERT_OK(Put("bbb1", ""));
  3481. Iterator* iter = db_->NewIterator(ReadOptions());
  3482. // Seeking into f1, the iterator will check bloom filter which returns the
  3483. // file iterator ot be invalidate, and the cursor will put into f2, with
  3484. // the next key to be "ddd0".
  3485. iter->Seek("bbb1");
  3486. ASSERT_TRUE(iter->Valid());
  3487. ASSERT_EQ("bbb1", iter->key().ToString());
  3488. // Reseek ccc1, the L1 iterator needs to go back to f1 and reseek.
  3489. iter->Seek("ccc1");
  3490. ASSERT_TRUE(iter->Valid());
  3491. ASSERT_EQ("ccc1", iter->key().ToString());
  3492. delete iter;
  3493. }
  3494. TEST_F(DBTest2, PrefixBloomFilteredOut) {
  3495. Options options = CurrentOptions();
  3496. options.create_if_missing = true;
  3497. options.prefix_extractor.reset(NewCappedPrefixTransform(3));
  3498. BlockBasedTableOptions bbto;
  3499. bbto.filter_policy.reset(NewBloomFilterPolicy(10, false));
  3500. bbto.whole_key_filtering = false;
  3501. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  3502. DestroyAndReopen(options);
  3503. // Construct two L1 files with keys:
  3504. // f1:[aaa1 ccc1] f2:[ddd0]
  3505. ASSERT_OK(Put("aaa1", ""));
  3506. ASSERT_OK(Put("ccc1", ""));
  3507. ASSERT_OK(Flush());
  3508. ASSERT_OK(Put("ddd0", ""));
  3509. ASSERT_OK(Flush());
  3510. CompactRangeOptions cro;
  3511. cro.bottommost_level_compaction = BottommostLevelCompaction::kSkip;
  3512. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  3513. Iterator* iter = db_->NewIterator(ReadOptions());
  3514. // Bloom filter is filterd out by f1.
  3515. // This is just one of several valid position following the contract.
  3516. // Postioning to ccc1 or ddd0 is also valid. This is just to validate
  3517. // the behavior of the current implementation. If underlying implementation
  3518. // changes, the test might fail here.
  3519. iter->Seek("bbb1");
  3520. ASSERT_FALSE(iter->Valid());
  3521. delete iter;
  3522. }
  3523. #ifndef ROCKSDB_LITE
  3524. TEST_F(DBTest2, RowCacheSnapshot) {
  3525. Options options = CurrentOptions();
  3526. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  3527. options.row_cache = NewLRUCache(8 * 8192);
  3528. DestroyAndReopen(options);
  3529. ASSERT_OK(Put("foo", "bar1"));
  3530. const Snapshot* s1 = db_->GetSnapshot();
  3531. ASSERT_OK(Put("foo", "bar2"));
  3532. ASSERT_OK(Flush());
  3533. ASSERT_OK(Put("foo2", "bar"));
  3534. const Snapshot* s2 = db_->GetSnapshot();
  3535. ASSERT_OK(Put("foo3", "bar"));
  3536. const Snapshot* s3 = db_->GetSnapshot();
  3537. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), 0);
  3538. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 0);
  3539. ASSERT_EQ(Get("foo"), "bar2");
  3540. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), 0);
  3541. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 1);
  3542. ASSERT_EQ(Get("foo"), "bar2");
  3543. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), 1);
  3544. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 1);
  3545. ASSERT_EQ(Get("foo", s1), "bar1");
  3546. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), 1);
  3547. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 2);
  3548. ASSERT_EQ(Get("foo", s2), "bar2");
  3549. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), 2);
  3550. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 2);
  3551. ASSERT_EQ(Get("foo", s1), "bar1");
  3552. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), 3);
  3553. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 2);
  3554. ASSERT_EQ(Get("foo", s3), "bar2");
  3555. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), 4);
  3556. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 2);
  3557. db_->ReleaseSnapshot(s1);
  3558. db_->ReleaseSnapshot(s2);
  3559. db_->ReleaseSnapshot(s3);
  3560. }
  3561. #endif // ROCKSDB_LITE
  3562. // When DB is reopened with multiple column families, the manifest file
  3563. // is written after the first CF is flushed, and it is written again
  3564. // after each flush. If DB crashes between the flushes, the flushed CF
  3565. // flushed will pass the latest log file, and now we require it not
  3566. // to be corrupted, and triggering a corruption report.
  3567. // We need to fix the bug and enable the test.
  3568. TEST_F(DBTest2, CrashInRecoveryMultipleCF) {
  3569. const std::vector<std::string> sync_points = {
  3570. "DBImpl::RecoverLogFiles:BeforeFlushFinalMemtable",
  3571. "VersionSet::ProcessManifestWrites:BeforeWriteLastVersionEdit:0"};
  3572. for (const auto& test_sync_point : sync_points) {
  3573. Options options = CurrentOptions();
  3574. // First destroy original db to ensure a clean start.
  3575. DestroyAndReopen(options);
  3576. options.create_if_missing = true;
  3577. options.wal_recovery_mode = WALRecoveryMode::kPointInTimeRecovery;
  3578. CreateAndReopenWithCF({"pikachu"}, options);
  3579. ASSERT_OK(Put("foo", "bar"));
  3580. ASSERT_OK(Flush());
  3581. ASSERT_OK(Put(1, "foo", "bar"));
  3582. ASSERT_OK(Flush(1));
  3583. ASSERT_OK(Put("foo", "bar"));
  3584. ASSERT_OK(Put(1, "foo", "bar"));
  3585. // The value is large enough to be divided to two blocks.
  3586. std::string large_value(400, ' ');
  3587. ASSERT_OK(Put("foo1", large_value));
  3588. ASSERT_OK(Put("foo2", large_value));
  3589. Close();
  3590. // Corrupt the log file in the middle, so that it is not corrupted
  3591. // in the tail.
  3592. std::vector<std::string> filenames;
  3593. ASSERT_OK(env_->GetChildren(dbname_, &filenames));
  3594. for (const auto& f : filenames) {
  3595. uint64_t number;
  3596. FileType type;
  3597. if (ParseFileName(f, &number, &type) && type == FileType::kLogFile) {
  3598. std::string fname = dbname_ + "/" + f;
  3599. std::string file_content;
  3600. ASSERT_OK(ReadFileToString(env_, fname, &file_content));
  3601. file_content[400] = 'h';
  3602. file_content[401] = 'a';
  3603. ASSERT_OK(WriteStringToFile(env_, file_content, fname));
  3604. break;
  3605. }
  3606. }
  3607. // Reopen and freeze the file system after the first manifest write.
  3608. FaultInjectionTestEnv fit_env(options.env);
  3609. options.env = &fit_env;
  3610. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();
  3611. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  3612. test_sync_point,
  3613. [&](void* /*arg*/) { fit_env.SetFilesystemActive(false); });
  3614. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  3615. ASSERT_NOK(TryReopenWithColumnFamilies(
  3616. {kDefaultColumnFamilyName, "pikachu"}, options));
  3617. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  3618. fit_env.SetFilesystemActive(true);
  3619. // If we continue using failure ingestion Env, it will conplain something
  3620. // when renaming current file, which is not expected. Need to investigate
  3621. // why.
  3622. options.env = env_;
  3623. ASSERT_OK(TryReopenWithColumnFamilies({kDefaultColumnFamilyName, "pikachu"},
  3624. options));
  3625. }
  3626. }
  3627. TEST_F(DBTest2, SeekFileRangeDeleteTail) {
  3628. Options options = CurrentOptions();
  3629. options.prefix_extractor.reset(NewCappedPrefixTransform(1));
  3630. options.num_levels = 3;
  3631. DestroyAndReopen(options);
  3632. ASSERT_OK(Put("a", "a"));
  3633. const Snapshot* s1 = db_->GetSnapshot();
  3634. ASSERT_OK(
  3635. db_->DeleteRange(WriteOptions(), db_->DefaultColumnFamily(), "a", "f"));
  3636. ASSERT_OK(Put("b", "a"));
  3637. ASSERT_OK(Flush());
  3638. ASSERT_OK(Put("x", "a"));
  3639. ASSERT_OK(Put("z", "a"));
  3640. ASSERT_OK(Flush());
  3641. CompactRangeOptions cro;
  3642. cro.change_level = true;
  3643. cro.target_level = 2;
  3644. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  3645. {
  3646. ReadOptions ro;
  3647. ro.total_order_seek = true;
  3648. std::unique_ptr<Iterator> iter(db_->NewIterator(ro));
  3649. iter->Seek("e");
  3650. ASSERT_TRUE(iter->Valid());
  3651. ASSERT_EQ("x", iter->key().ToString());
  3652. }
  3653. db_->ReleaseSnapshot(s1);
  3654. }
  3655. TEST_F(DBTest2, BackgroundPurgeTest) {
  3656. Options options = CurrentOptions();
  3657. options.write_buffer_manager =
  3658. std::make_shared<ROCKSDB_NAMESPACE::WriteBufferManager>(1 << 20);
  3659. options.avoid_unnecessary_blocking_io = true;
  3660. DestroyAndReopen(options);
  3661. size_t base_value = options.write_buffer_manager->memory_usage();
  3662. ASSERT_OK(Put("a", "a"));
  3663. Iterator* iter = db_->NewIterator(ReadOptions());
  3664. ASSERT_OK(Flush());
  3665. size_t value = options.write_buffer_manager->memory_usage();
  3666. ASSERT_GT(value, base_value);
  3667. db_->GetEnv()->SetBackgroundThreads(1, Env::Priority::HIGH);
  3668. test::SleepingBackgroundTask sleeping_task_after;
  3669. db_->GetEnv()->Schedule(&test::SleepingBackgroundTask::DoSleepTask,
  3670. &sleeping_task_after, Env::Priority::HIGH);
  3671. delete iter;
  3672. Env::Default()->SleepForMicroseconds(100000);
  3673. value = options.write_buffer_manager->memory_usage();
  3674. ASSERT_GT(value, base_value);
  3675. sleeping_task_after.WakeUp();
  3676. sleeping_task_after.WaitUntilDone();
  3677. test::SleepingBackgroundTask sleeping_task_after2;
  3678. db_->GetEnv()->Schedule(&test::SleepingBackgroundTask::DoSleepTask,
  3679. &sleeping_task_after2, Env::Priority::HIGH);
  3680. sleeping_task_after2.WakeUp();
  3681. sleeping_task_after2.WaitUntilDone();
  3682. value = options.write_buffer_manager->memory_usage();
  3683. ASSERT_EQ(base_value, value);
  3684. }
  3685. TEST_F(DBTest2, SwitchMemtableRaceWithNewManifest) {
  3686. Options options = CurrentOptions();
  3687. DestroyAndReopen(options);
  3688. options.max_manifest_file_size = 10;
  3689. options.create_if_missing = true;
  3690. CreateAndReopenWithCF({"pikachu"}, options);
  3691. ASSERT_EQ(2, handles_.size());
  3692. ASSERT_OK(Put("foo", "value"));
  3693. const int kL0Files = options.level0_file_num_compaction_trigger;
  3694. for (int i = 0; i < kL0Files; ++i) {
  3695. ASSERT_OK(Put(/*cf=*/1, "a", std::to_string(i)));
  3696. ASSERT_OK(Flush(/*cf=*/1));
  3697. }
  3698. port::Thread thread([&]() { ASSERT_OK(Flush()); });
  3699. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  3700. thread.join();
  3701. }
  3702. TEST_F(DBTest2, SameSmallestInSameLevel) {
  3703. // This test validates fractional casacading logic when several files at one
  3704. // one level only contains the same user key.
  3705. Options options = CurrentOptions();
  3706. options.merge_operator = MergeOperators::CreateStringAppendOperator();
  3707. DestroyAndReopen(options);
  3708. ASSERT_OK(Put("key", "1"));
  3709. ASSERT_OK(Put("key", "2"));
  3710. ASSERT_OK(db_->Merge(WriteOptions(), "key", "3"));
  3711. ASSERT_OK(db_->Merge(WriteOptions(), "key", "4"));
  3712. Flush();
  3713. CompactRangeOptions cro;
  3714. cro.change_level = true;
  3715. cro.target_level = 2;
  3716. ASSERT_OK(dbfull()->CompactRange(cro, db_->DefaultColumnFamily(), nullptr,
  3717. nullptr));
  3718. ASSERT_OK(db_->Merge(WriteOptions(), "key", "5"));
  3719. Flush();
  3720. ASSERT_OK(db_->Merge(WriteOptions(), "key", "6"));
  3721. Flush();
  3722. ASSERT_OK(db_->Merge(WriteOptions(), "key", "7"));
  3723. Flush();
  3724. ASSERT_OK(db_->Merge(WriteOptions(), "key", "8"));
  3725. Flush();
  3726. dbfull()->TEST_WaitForCompact(true);
  3727. #ifndef ROCKSDB_LITE
  3728. ASSERT_EQ("0,4,1", FilesPerLevel());
  3729. #endif // ROCKSDB_LITE
  3730. ASSERT_EQ("2,3,4,5,6,7,8", Get("key"));
  3731. }
  3732. TEST_F(DBTest2, BlockBasedTablePrefixIndexSeekForPrev) {
  3733. // create a DB with block prefix index
  3734. BlockBasedTableOptions table_options;
  3735. Options options = CurrentOptions();
  3736. table_options.block_size = 300;
  3737. table_options.index_type = BlockBasedTableOptions::kHashSearch;
  3738. table_options.index_shortening =
  3739. BlockBasedTableOptions::IndexShorteningMode::kNoShortening;
  3740. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  3741. options.prefix_extractor.reset(NewFixedPrefixTransform(1));
  3742. Reopen(options);
  3743. Random rnd(301);
  3744. std::string large_value = RandomString(&rnd, 500);
  3745. ASSERT_OK(Put("a1", large_value));
  3746. ASSERT_OK(Put("x1", large_value));
  3747. ASSERT_OK(Put("y1", large_value));
  3748. Flush();
  3749. {
  3750. std::unique_ptr<Iterator> iterator(db_->NewIterator(ReadOptions()));
  3751. iterator->SeekForPrev("x3");
  3752. ASSERT_TRUE(iterator->Valid());
  3753. ASSERT_EQ("x1", iterator->key().ToString());
  3754. iterator->SeekForPrev("a3");
  3755. ASSERT_TRUE(iterator->Valid());
  3756. ASSERT_EQ("a1", iterator->key().ToString());
  3757. iterator->SeekForPrev("y3");
  3758. ASSERT_TRUE(iterator->Valid());
  3759. ASSERT_EQ("y1", iterator->key().ToString());
  3760. // Query more than one non-existing prefix to cover the case both
  3761. // of empty hash bucket and hash bucket conflict.
  3762. iterator->SeekForPrev("b1");
  3763. // Result should be not valid or "a1".
  3764. if (iterator->Valid()) {
  3765. ASSERT_EQ("a1", iterator->key().ToString());
  3766. }
  3767. iterator->SeekForPrev("c1");
  3768. // Result should be not valid or "a1".
  3769. if (iterator->Valid()) {
  3770. ASSERT_EQ("a1", iterator->key().ToString());
  3771. }
  3772. iterator->SeekForPrev("d1");
  3773. // Result should be not valid or "a1".
  3774. if (iterator->Valid()) {
  3775. ASSERT_EQ("a1", iterator->key().ToString());
  3776. }
  3777. iterator->SeekForPrev("y3");
  3778. ASSERT_TRUE(iterator->Valid());
  3779. ASSERT_EQ("y1", iterator->key().ToString());
  3780. }
  3781. }
  3782. TEST_F(DBTest2, ChangePrefixExtractor) {
  3783. for (bool use_partitioned_filter : {true, false}) {
  3784. // create a DB with block prefix index
  3785. BlockBasedTableOptions table_options;
  3786. Options options = CurrentOptions();
  3787. // Sometimes filter is checked based on upper bound. Assert counters
  3788. // for that case. Otherwise, only check data correctness.
  3789. #ifndef ROCKSDB_LITE
  3790. bool expect_filter_check = !use_partitioned_filter;
  3791. #else
  3792. bool expect_filter_check = false;
  3793. #endif
  3794. table_options.partition_filters = use_partitioned_filter;
  3795. if (use_partitioned_filter) {
  3796. table_options.index_type =
  3797. BlockBasedTableOptions::IndexType::kTwoLevelIndexSearch;
  3798. }
  3799. table_options.filter_policy.reset(NewBloomFilterPolicy(10, false));
  3800. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  3801. options.statistics = CreateDBStatistics();
  3802. options.prefix_extractor.reset(NewFixedPrefixTransform(2));
  3803. DestroyAndReopen(options);
  3804. Random rnd(301);
  3805. ASSERT_OK(Put("aa", ""));
  3806. ASSERT_OK(Put("xb", ""));
  3807. ASSERT_OK(Put("xx1", ""));
  3808. ASSERT_OK(Put("xz1", ""));
  3809. ASSERT_OK(Put("zz", ""));
  3810. Flush();
  3811. // After reopening DB with prefix size 2 => 1, prefix extractor
  3812. // won't take effective unless it won't change results based
  3813. // on upper bound and seek key.
  3814. options.prefix_extractor.reset(NewFixedPrefixTransform(1));
  3815. Reopen(options);
  3816. {
  3817. std::unique_ptr<Iterator> iterator(db_->NewIterator(ReadOptions()));
  3818. iterator->Seek("xa");
  3819. ASSERT_TRUE(iterator->Valid());
  3820. ASSERT_EQ("xb", iterator->key().ToString());
  3821. // It's a bug that the counter BLOOM_FILTER_PREFIX_CHECKED is not
  3822. // correct in this case. So don't check counters in this case.
  3823. if (expect_filter_check) {
  3824. ASSERT_EQ(0, TestGetTickerCount(options, BLOOM_FILTER_PREFIX_CHECKED));
  3825. }
  3826. iterator->Seek("xz");
  3827. ASSERT_TRUE(iterator->Valid());
  3828. ASSERT_EQ("xz1", iterator->key().ToString());
  3829. if (expect_filter_check) {
  3830. ASSERT_EQ(0, TestGetTickerCount(options, BLOOM_FILTER_PREFIX_CHECKED));
  3831. }
  3832. }
  3833. std::string ub_str = "xg9";
  3834. Slice ub(ub_str);
  3835. ReadOptions ro;
  3836. ro.iterate_upper_bound = &ub;
  3837. {
  3838. std::unique_ptr<Iterator> iterator(db_->NewIterator(ro));
  3839. // SeekForPrev() never uses prefix bloom if it is changed.
  3840. iterator->SeekForPrev("xg0");
  3841. ASSERT_TRUE(iterator->Valid());
  3842. ASSERT_EQ("xb", iterator->key().ToString());
  3843. if (expect_filter_check) {
  3844. ASSERT_EQ(0, TestGetTickerCount(options, BLOOM_FILTER_PREFIX_CHECKED));
  3845. }
  3846. }
  3847. ub_str = "xx9";
  3848. ub = Slice(ub_str);
  3849. {
  3850. std::unique_ptr<Iterator> iterator(db_->NewIterator(ro));
  3851. iterator->Seek("x");
  3852. ASSERT_TRUE(iterator->Valid());
  3853. ASSERT_EQ("xb", iterator->key().ToString());
  3854. if (expect_filter_check) {
  3855. ASSERT_EQ(0, TestGetTickerCount(options, BLOOM_FILTER_PREFIX_CHECKED));
  3856. }
  3857. iterator->Seek("xx0");
  3858. ASSERT_TRUE(iterator->Valid());
  3859. ASSERT_EQ("xx1", iterator->key().ToString());
  3860. if (expect_filter_check) {
  3861. ASSERT_EQ(1, TestGetTickerCount(options, BLOOM_FILTER_PREFIX_CHECKED));
  3862. }
  3863. }
  3864. CompactRangeOptions compact_range_opts;
  3865. compact_range_opts.bottommost_level_compaction =
  3866. BottommostLevelCompaction::kForce;
  3867. ASSERT_OK(db_->CompactRange(compact_range_opts, nullptr, nullptr));
  3868. ASSERT_OK(db_->CompactRange(compact_range_opts, nullptr, nullptr));
  3869. // Re-execute similar queries after a full compaction
  3870. {
  3871. std::unique_ptr<Iterator> iterator(db_->NewIterator(ReadOptions()));
  3872. iterator->Seek("x");
  3873. ASSERT_TRUE(iterator->Valid());
  3874. ASSERT_EQ("xb", iterator->key().ToString());
  3875. if (expect_filter_check) {
  3876. ASSERT_EQ(2, TestGetTickerCount(options, BLOOM_FILTER_PREFIX_CHECKED));
  3877. }
  3878. iterator->Seek("xg");
  3879. ASSERT_TRUE(iterator->Valid());
  3880. ASSERT_EQ("xx1", iterator->key().ToString());
  3881. if (expect_filter_check) {
  3882. ASSERT_EQ(3, TestGetTickerCount(options, BLOOM_FILTER_PREFIX_CHECKED));
  3883. }
  3884. iterator->Seek("xz");
  3885. ASSERT_TRUE(iterator->Valid());
  3886. ASSERT_EQ("xz1", iterator->key().ToString());
  3887. if (expect_filter_check) {
  3888. ASSERT_EQ(4, TestGetTickerCount(options, BLOOM_FILTER_PREFIX_CHECKED));
  3889. }
  3890. }
  3891. {
  3892. std::unique_ptr<Iterator> iterator(db_->NewIterator(ro));
  3893. iterator->SeekForPrev("xx0");
  3894. ASSERT_TRUE(iterator->Valid());
  3895. ASSERT_EQ("xb", iterator->key().ToString());
  3896. if (expect_filter_check) {
  3897. ASSERT_EQ(5, TestGetTickerCount(options, BLOOM_FILTER_PREFIX_CHECKED));
  3898. }
  3899. iterator->Seek("xx0");
  3900. ASSERT_TRUE(iterator->Valid());
  3901. ASSERT_EQ("xx1", iterator->key().ToString());
  3902. if (expect_filter_check) {
  3903. ASSERT_EQ(6, TestGetTickerCount(options, BLOOM_FILTER_PREFIX_CHECKED));
  3904. }
  3905. }
  3906. ub_str = "xg9";
  3907. ub = Slice(ub_str);
  3908. {
  3909. std::unique_ptr<Iterator> iterator(db_->NewIterator(ro));
  3910. iterator->SeekForPrev("xg0");
  3911. ASSERT_TRUE(iterator->Valid());
  3912. ASSERT_EQ("xb", iterator->key().ToString());
  3913. if (expect_filter_check) {
  3914. ASSERT_EQ(7, TestGetTickerCount(options, BLOOM_FILTER_PREFIX_CHECKED));
  3915. }
  3916. }
  3917. }
  3918. }
  3919. TEST_F(DBTest2, BlockBasedTablePrefixGetIndexNotFound) {
  3920. // create a DB with block prefix index
  3921. BlockBasedTableOptions table_options;
  3922. Options options = CurrentOptions();
  3923. table_options.block_size = 300;
  3924. table_options.index_type = BlockBasedTableOptions::kHashSearch;
  3925. table_options.index_shortening =
  3926. BlockBasedTableOptions::IndexShorteningMode::kNoShortening;
  3927. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  3928. options.prefix_extractor.reset(NewFixedPrefixTransform(1));
  3929. options.level0_file_num_compaction_trigger = 8;
  3930. Reopen(options);
  3931. ASSERT_OK(Put("b1", "ok"));
  3932. Flush();
  3933. // Flushing several files so that the chance that hash bucket
  3934. // is empty fo "b" in at least one of the files is high.
  3935. ASSERT_OK(Put("a1", ""));
  3936. ASSERT_OK(Put("c1", ""));
  3937. Flush();
  3938. ASSERT_OK(Put("a2", ""));
  3939. ASSERT_OK(Put("c2", ""));
  3940. Flush();
  3941. ASSERT_OK(Put("a3", ""));
  3942. ASSERT_OK(Put("c3", ""));
  3943. Flush();
  3944. ASSERT_OK(Put("a4", ""));
  3945. ASSERT_OK(Put("c4", ""));
  3946. Flush();
  3947. ASSERT_OK(Put("a5", ""));
  3948. ASSERT_OK(Put("c5", ""));
  3949. Flush();
  3950. ASSERT_EQ("ok", Get("b1"));
  3951. }
  3952. #ifndef ROCKSDB_LITE
  3953. TEST_F(DBTest2, AutoPrefixMode1) {
  3954. // create a DB with block prefix index
  3955. BlockBasedTableOptions table_options;
  3956. Options options = CurrentOptions();
  3957. table_options.filter_policy.reset(NewBloomFilterPolicy(10, false));
  3958. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  3959. options.prefix_extractor.reset(NewFixedPrefixTransform(1));
  3960. options.statistics = CreateDBStatistics();
  3961. Reopen(options);
  3962. Random rnd(301);
  3963. std::string large_value = RandomString(&rnd, 500);
  3964. ASSERT_OK(Put("a1", large_value));
  3965. ASSERT_OK(Put("x1", large_value));
  3966. ASSERT_OK(Put("y1", large_value));
  3967. Flush();
  3968. ReadOptions ro;
  3969. ro.total_order_seek = false;
  3970. ro.auto_prefix_mode = true;
  3971. {
  3972. std::unique_ptr<Iterator> iterator(db_->NewIterator(ro));
  3973. iterator->Seek("b1");
  3974. ASSERT_TRUE(iterator->Valid());
  3975. ASSERT_EQ("x1", iterator->key().ToString());
  3976. ASSERT_EQ(0, TestGetTickerCount(options, BLOOM_FILTER_PREFIX_CHECKED));
  3977. }
  3978. std::string ub_str = "b9";
  3979. Slice ub(ub_str);
  3980. ro.iterate_upper_bound = &ub;
  3981. {
  3982. std::unique_ptr<Iterator> iterator(db_->NewIterator(ro));
  3983. iterator->Seek("b1");
  3984. ASSERT_FALSE(iterator->Valid());
  3985. ASSERT_EQ(1, TestGetTickerCount(options, BLOOM_FILTER_PREFIX_CHECKED));
  3986. }
  3987. ub_str = "z";
  3988. ub = Slice(ub_str);
  3989. {
  3990. std::unique_ptr<Iterator> iterator(db_->NewIterator(ro));
  3991. iterator->Seek("b1");
  3992. ASSERT_TRUE(iterator->Valid());
  3993. ASSERT_EQ("x1", iterator->key().ToString());
  3994. ASSERT_EQ(1, TestGetTickerCount(options, BLOOM_FILTER_PREFIX_CHECKED));
  3995. }
  3996. ub_str = "c";
  3997. ub = Slice(ub_str);
  3998. {
  3999. std::unique_ptr<Iterator> iterator(db_->NewIterator(ro));
  4000. iterator->Seek("b1");
  4001. ASSERT_FALSE(iterator->Valid());
  4002. ASSERT_EQ(2, TestGetTickerCount(options, BLOOM_FILTER_PREFIX_CHECKED));
  4003. }
  4004. // The same queries without recreating iterator
  4005. {
  4006. ub_str = "b9";
  4007. ub = Slice(ub_str);
  4008. ro.iterate_upper_bound = &ub;
  4009. std::unique_ptr<Iterator> iterator(db_->NewIterator(ro));
  4010. iterator->Seek("b1");
  4011. ASSERT_FALSE(iterator->Valid());
  4012. ASSERT_EQ(3, TestGetTickerCount(options, BLOOM_FILTER_PREFIX_CHECKED));
  4013. ub_str = "z";
  4014. ub = Slice(ub_str);
  4015. iterator->Seek("b1");
  4016. ASSERT_TRUE(iterator->Valid());
  4017. ASSERT_EQ("x1", iterator->key().ToString());
  4018. ASSERT_EQ(3, TestGetTickerCount(options, BLOOM_FILTER_PREFIX_CHECKED));
  4019. ub_str = "c";
  4020. ub = Slice(ub_str);
  4021. iterator->Seek("b1");
  4022. ASSERT_FALSE(iterator->Valid());
  4023. ASSERT_EQ(4, TestGetTickerCount(options, BLOOM_FILTER_PREFIX_CHECKED));
  4024. ub_str = "b9";
  4025. ub = Slice(ub_str);
  4026. ro.iterate_upper_bound = &ub;
  4027. iterator->SeekForPrev("b1");
  4028. ASSERT_TRUE(iterator->Valid());
  4029. ASSERT_EQ("a1", iterator->key().ToString());
  4030. ASSERT_EQ(4, TestGetTickerCount(options, BLOOM_FILTER_PREFIX_CHECKED));
  4031. ub_str = "zz";
  4032. ub = Slice(ub_str);
  4033. ro.iterate_upper_bound = &ub;
  4034. iterator->SeekToLast();
  4035. ASSERT_TRUE(iterator->Valid());
  4036. ASSERT_EQ("y1", iterator->key().ToString());
  4037. iterator->SeekToFirst();
  4038. ASSERT_TRUE(iterator->Valid());
  4039. ASSERT_EQ("a1", iterator->key().ToString());
  4040. }
  4041. }
  4042. #endif // ROCKSDB_LITE
  4043. } // namespace ROCKSDB_NAMESPACE
  4044. #ifdef ROCKSDB_UNITTESTS_WITH_CUSTOM_OBJECTS_FROM_STATIC_LIBS
  4045. extern "C" {
  4046. void RegisterCustomObjects(int argc, char** argv);
  4047. }
  4048. #else
  4049. void RegisterCustomObjects(int /*argc*/, char** /*argv*/) {}
  4050. #endif // !ROCKSDB_UNITTESTS_WITH_CUSTOM_OBJECTS_FROM_STATIC_LIBS
  4051. int main(int argc, char** argv) {
  4052. ROCKSDB_NAMESPACE::port::InstallStackTraceHandler();
  4053. ::testing::InitGoogleTest(&argc, argv);
  4054. RegisterCustomObjects(argc, argv);
  4055. return RUN_ALL_TESTS();
  4056. }