external_sst_file_test.cc 170 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. #include <table/block_based/block_based_table_factory.h>
  6. #include <functional>
  7. #include <memory>
  8. #include <sstream>
  9. #include "db/db_test_util.h"
  10. #include "db/dbformat.h"
  11. #include "file/filename.h"
  12. #include "options/options_helper.h"
  13. #include "port/port.h"
  14. #include "port/stack_trace.h"
  15. #include "rocksdb/sst_file_reader.h"
  16. #include "rocksdb/sst_file_writer.h"
  17. #include "test_util/testutil.h"
  18. #include "util/random.h"
  19. #include "util/thread_guard.h"
  20. #include "utilities/fault_injection_env.h"
  21. namespace ROCKSDB_NAMESPACE {
  22. // A test environment that can be configured to fail the Link operation.
  23. class ExternalSSTTestFS : public FileSystemWrapper {
  24. public:
  25. ExternalSSTTestFS(const std::shared_ptr<FileSystem>& t, bool fail_link)
  26. : FileSystemWrapper(t), fail_link_(fail_link) {}
  27. static const char* kClassName() { return "ExternalSSTTestFS"; }
  28. const char* Name() const override { return kClassName(); }
  29. IOStatus LinkFile(const std::string& s, const std::string& t,
  30. const IOOptions& options, IODebugContext* dbg) override {
  31. if (fail_link_) {
  32. return IOStatus::NotSupported("Link failed");
  33. }
  34. return target()->LinkFile(s, t, options, dbg);
  35. }
  36. void set_fail_link(bool fail_link) { fail_link_ = fail_link; }
  37. private:
  38. bool fail_link_;
  39. };
  40. class ExternalSSTFileTestBase : public DBTestBase {
  41. public:
  42. ExternalSSTFileTestBase()
  43. : DBTestBase("external_sst_file_test", /*env_do_fsync=*/true) {
  44. sst_files_dir_ = dbname_ + "/sst_files/";
  45. DestroyAndRecreateExternalSSTFilesDir();
  46. }
  47. void DestroyAndRecreateExternalSSTFilesDir() {
  48. ASSERT_OK(DestroyDir(env_, sst_files_dir_));
  49. ASSERT_OK(env_->CreateDir(sst_files_dir_));
  50. }
  51. ~ExternalSSTFileTestBase() override {
  52. DestroyDir(env_, sst_files_dir_).PermitUncheckedError();
  53. }
  54. protected:
  55. std::string sst_files_dir_;
  56. };
  57. class ExternSSTFileLinkFailFallbackTest
  58. : public ExternalSSTFileTestBase,
  59. public ::testing::WithParamInterface<std::tuple<bool, bool, bool>> {
  60. public:
  61. ExternSSTFileLinkFailFallbackTest() {
  62. fs_ = std::make_shared<ExternalSSTTestFS>(env_->GetFileSystem(), true);
  63. test_env_.reset(new CompositeEnvWrapper(env_, fs_));
  64. options_ = CurrentOptions();
  65. options_.disable_auto_compactions = true;
  66. options_.env = test_env_.get();
  67. }
  68. void TearDown() override {
  69. delete db_;
  70. db_ = nullptr;
  71. ASSERT_OK(DestroyDB(dbname_, options_));
  72. }
  73. protected:
  74. Options options_;
  75. std::shared_ptr<ExternalSSTTestFS> fs_;
  76. std::unique_ptr<Env> test_env_;
  77. };
  78. class ExternalSSTFileTest
  79. : public ExternalSSTFileTestBase,
  80. public ::testing::WithParamInterface<std::tuple<bool, bool>> {
  81. public:
  82. ExternalSSTFileTest() = default;
  83. Status GenerateOneExternalFile(
  84. const Options& options, ColumnFamilyHandle* cfh,
  85. std::vector<std::pair<std::string, std::string>>& data, int file_id,
  86. bool sort_data, std::string* external_file_path,
  87. std::map<std::string, std::string>* true_data) {
  88. // Generate a file id if not provided
  89. if (-1 == file_id) {
  90. file_id = (++last_file_id_);
  91. }
  92. // Sort data if asked to do so
  93. if (sort_data) {
  94. std::sort(data.begin(), data.end(),
  95. [&](const std::pair<std::string, std::string>& e1,
  96. const std::pair<std::string, std::string>& e2) {
  97. return options.comparator->Compare(e1.first, e2.first) < 0;
  98. });
  99. auto uniq_iter = std::unique(
  100. data.begin(), data.end(),
  101. [&](const std::pair<std::string, std::string>& e1,
  102. const std::pair<std::string, std::string>& e2) {
  103. return options.comparator->Compare(e1.first, e2.first) == 0;
  104. });
  105. data.resize(uniq_iter - data.begin());
  106. }
  107. std::string file_path = sst_files_dir_ + std::to_string(file_id);
  108. SstFileWriter sst_file_writer(EnvOptions(), options, cfh);
  109. Status s = sst_file_writer.Open(file_path);
  110. if (!s.ok()) {
  111. return s;
  112. }
  113. for (const auto& entry : data) {
  114. s = sst_file_writer.Put(entry.first, entry.second);
  115. if (!s.ok()) {
  116. sst_file_writer.Finish().PermitUncheckedError();
  117. return s;
  118. }
  119. }
  120. s = sst_file_writer.Finish();
  121. if (s.ok() && external_file_path != nullptr) {
  122. *external_file_path = file_path;
  123. }
  124. if (s.ok() && nullptr != true_data) {
  125. for (const auto& entry : data) {
  126. true_data->insert({entry.first, entry.second});
  127. }
  128. }
  129. return s;
  130. }
  131. Status GenerateAndAddExternalFile(
  132. const Options options,
  133. std::vector<std::pair<std::string, std::string>> data, int file_id = -1,
  134. bool allow_global_seqno = false, bool write_global_seqno = false,
  135. bool verify_checksums_before_ingest = true, bool ingest_behind = false,
  136. bool sort_data = false,
  137. std::map<std::string, std::string>* true_data = nullptr,
  138. ColumnFamilyHandle* cfh = nullptr, bool fill_cache = false) {
  139. // Generate a file id if not provided
  140. if (file_id == -1) {
  141. file_id = last_file_id_ + 1;
  142. last_file_id_++;
  143. }
  144. // Sort data if asked to do so
  145. if (sort_data) {
  146. std::sort(data.begin(), data.end(),
  147. [&](const std::pair<std::string, std::string>& e1,
  148. const std::pair<std::string, std::string>& e2) {
  149. return options.comparator->Compare(e1.first, e2.first) < 0;
  150. });
  151. auto uniq_iter = std::unique(
  152. data.begin(), data.end(),
  153. [&](const std::pair<std::string, std::string>& e1,
  154. const std::pair<std::string, std::string>& e2) {
  155. return options.comparator->Compare(e1.first, e2.first) == 0;
  156. });
  157. data.resize(uniq_iter - data.begin());
  158. }
  159. std::string file_path = sst_files_dir_ + std::to_string(file_id);
  160. SstFileWriter sst_file_writer(EnvOptions(), options, cfh);
  161. Status s = sst_file_writer.Open(file_path);
  162. if (!s.ok()) {
  163. return s;
  164. }
  165. for (auto& entry : data) {
  166. s = sst_file_writer.Put(entry.first, entry.second);
  167. if (!s.ok()) {
  168. sst_file_writer.Finish().PermitUncheckedError();
  169. return s;
  170. }
  171. }
  172. s = sst_file_writer.Finish();
  173. if (s.ok()) {
  174. IngestExternalFileOptions ifo;
  175. ifo.allow_global_seqno = allow_global_seqno;
  176. ifo.write_global_seqno = allow_global_seqno ? write_global_seqno : false;
  177. ifo.verify_checksums_before_ingest = verify_checksums_before_ingest;
  178. ifo.ingest_behind = ingest_behind;
  179. ifo.fill_cache = fill_cache;
  180. if (cfh) {
  181. s = db_->IngestExternalFile(cfh, {file_path}, ifo);
  182. } else {
  183. s = db_->IngestExternalFile({file_path}, ifo);
  184. }
  185. }
  186. if (s.ok() && true_data) {
  187. for (auto& entry : data) {
  188. (*true_data)[entry.first] = entry.second;
  189. }
  190. }
  191. return s;
  192. }
  193. Status GenerateAndAddExternalFiles(
  194. const Options& options,
  195. const std::vector<ColumnFamilyHandle*>& column_families,
  196. const std::vector<IngestExternalFileOptions>& ifos,
  197. std::vector<std::vector<std::pair<std::string, std::string>>>& data,
  198. int file_id, bool sort_data,
  199. std::vector<std::map<std::string, std::string>>& true_data) {
  200. if (-1 == file_id) {
  201. file_id = (++last_file_id_);
  202. }
  203. // Generate external SST files, one for each column family
  204. size_t num_cfs = column_families.size();
  205. assert(ifos.size() == num_cfs);
  206. assert(data.size() == num_cfs);
  207. std::vector<IngestExternalFileArg> args(num_cfs);
  208. for (size_t i = 0; i != num_cfs; ++i) {
  209. std::string external_file_path;
  210. Status s = GenerateOneExternalFile(
  211. options, column_families[i], data[i], file_id, sort_data,
  212. &external_file_path,
  213. true_data.size() == num_cfs ? &true_data[i] : nullptr);
  214. if (!s.ok()) {
  215. return s;
  216. }
  217. ++file_id;
  218. args[i].column_family = column_families[i];
  219. args[i].external_files.push_back(external_file_path);
  220. args[i].options = ifos[i];
  221. }
  222. return db_->IngestExternalFiles(args);
  223. }
  224. Status GenerateAndAddExternalFile(
  225. const Options options, std::vector<std::pair<int, std::string>> data,
  226. int file_id = -1, bool allow_global_seqno = false,
  227. bool write_global_seqno = false,
  228. bool verify_checksums_before_ingest = true, bool ingest_behind = false,
  229. bool sort_data = false,
  230. std::map<std::string, std::string>* true_data = nullptr,
  231. ColumnFamilyHandle* cfh = nullptr) {
  232. std::vector<std::pair<std::string, std::string>> file_data;
  233. for (auto& entry : data) {
  234. file_data.emplace_back(Key(entry.first), entry.second);
  235. }
  236. return GenerateAndAddExternalFile(options, file_data, file_id,
  237. allow_global_seqno, write_global_seqno,
  238. verify_checksums_before_ingest,
  239. ingest_behind, sort_data, true_data, cfh);
  240. }
  241. Status GenerateAndAddExternalFile(
  242. const Options options, std::vector<int> keys, int file_id = -1,
  243. bool allow_global_seqno = false, bool write_global_seqno = false,
  244. bool verify_checksums_before_ingest = true, bool ingest_behind = false,
  245. bool sort_data = false,
  246. std::map<std::string, std::string>* true_data = nullptr,
  247. ColumnFamilyHandle* cfh = nullptr, bool fill_cache = false) {
  248. std::vector<std::pair<std::string, std::string>> file_data;
  249. for (auto& k : keys) {
  250. file_data.emplace_back(Key(k), Key(k) + std::to_string(file_id));
  251. }
  252. return GenerateAndAddExternalFile(
  253. options, file_data, file_id, allow_global_seqno, write_global_seqno,
  254. verify_checksums_before_ingest, ingest_behind, sort_data, true_data,
  255. cfh, fill_cache);
  256. }
  257. Status DeprecatedAddFile(const std::vector<std::string>& files,
  258. bool move_files = false,
  259. bool skip_snapshot_check = false,
  260. bool skip_write_global_seqno = false) {
  261. IngestExternalFileOptions opts;
  262. opts.move_files = move_files;
  263. opts.snapshot_consistency = !skip_snapshot_check;
  264. opts.allow_global_seqno = false;
  265. opts.allow_blocking_flush = false;
  266. opts.write_global_seqno = !skip_write_global_seqno;
  267. return db_->IngestExternalFile(files, opts);
  268. }
  269. protected:
  270. int last_file_id_ = 0;
  271. };
  272. TEST_F(ExternalSSTFileTest, ComparatorMismatch) {
  273. Options options = CurrentOptions();
  274. Options options_diff_ucmp = options;
  275. options.comparator = BytewiseComparator();
  276. options_diff_ucmp.comparator = ReverseBytewiseComparator();
  277. SstFileWriter sst_file_writer(EnvOptions(), options_diff_ucmp);
  278. std::string file = sst_files_dir_ + "file.sst";
  279. ASSERT_OK(sst_file_writer.Open(file));
  280. ASSERT_OK(sst_file_writer.Put("foo", "val"));
  281. ASSERT_OK(sst_file_writer.Put("bar", "val1"));
  282. ASSERT_OK(sst_file_writer.Finish());
  283. DestroyAndReopen(options);
  284. ASSERT_NOK(DeprecatedAddFile({file}));
  285. }
  286. TEST_F(ExternalSSTFileTest, NoBlockCache) {
  287. LRUCacheOptions co;
  288. co.capacity = 32 << 20;
  289. std::shared_ptr<Cache> cache = NewLRUCache(co);
  290. BlockBasedTableOptions table_options;
  291. table_options.block_cache = cache;
  292. table_options.filter_policy.reset(NewBloomFilterPolicy(10));
  293. table_options.cache_index_and_filter_blocks = true;
  294. Options options = CurrentOptions();
  295. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  296. Reopen(options);
  297. size_t usage_before_ingestion = cache->GetUsage();
  298. std::map<std::string, std::string> true_data;
  299. // Ingest with fill_cache = true
  300. ASSERT_OK(GenerateAndAddExternalFile(options, {1, 2}, -1, false, false, true,
  301. false, false, &true_data, nullptr,
  302. /*fill_cache=*/true));
  303. ASSERT_EQ(FilesPerLevel(), "0,0,0,0,0,0,1");
  304. EXPECT_GT(cache->GetUsage(), usage_before_ingestion);
  305. TablePropertiesCollection tp;
  306. ASSERT_OK(db_->GetPropertiesOfAllTables(&tp));
  307. for (const auto& entry : tp) {
  308. EXPECT_GT(entry.second->index_size, 0);
  309. EXPECT_GT(entry.second->filter_size, 0);
  310. }
  311. usage_before_ingestion = cache->GetUsage();
  312. // Ingest with fill_cache = false
  313. ASSERT_OK(GenerateAndAddExternalFile(options, {3, 4}, -1, false, false, true,
  314. false, false, &true_data, nullptr,
  315. /*fill_cache=*/false));
  316. EXPECT_EQ(usage_before_ingestion, cache->GetUsage());
  317. tp.clear();
  318. ASSERT_OK(db_->GetPropertiesOfAllTables(&tp));
  319. for (const auto& entry : tp) {
  320. EXPECT_GT(entry.second->index_size, 0);
  321. EXPECT_GT(entry.second->filter_size, 0);
  322. }
  323. }
  324. TEST_F(ExternalSSTFileTest, Basic) {
  325. do {
  326. Options options = CurrentOptions();
  327. SstFileWriter sst_file_writer(EnvOptions(), options);
  328. // Current file size should be 0 after sst_file_writer init and before open
  329. // a file.
  330. ASSERT_EQ(sst_file_writer.FileSize(), 0);
  331. // file1.sst (0 => 99)
  332. std::string file1 = sst_files_dir_ + "file1.sst";
  333. ASSERT_OK(sst_file_writer.Open(file1));
  334. for (int k = 0; k < 100; k++) {
  335. ASSERT_OK(sst_file_writer.Put(Key(k), Key(k) + "_val"));
  336. }
  337. ExternalSstFileInfo file1_info;
  338. ASSERT_OK(sst_file_writer.Finish(&file1_info));
  339. // Current file size should be non-zero after success write.
  340. ASSERT_GT(sst_file_writer.FileSize(), 0);
  341. ASSERT_EQ(file1_info.file_path, file1);
  342. ASSERT_EQ(file1_info.num_entries, 100);
  343. ASSERT_EQ(file1_info.smallest_key, Key(0));
  344. ASSERT_EQ(file1_info.largest_key, Key(99));
  345. ASSERT_EQ(file1_info.num_range_del_entries, 0);
  346. ASSERT_EQ(file1_info.smallest_range_del_key, "");
  347. ASSERT_EQ(file1_info.largest_range_del_key, "");
  348. // sst_file_writer already finished, cannot add this value
  349. ASSERT_NOK(sst_file_writer.Put(Key(100), "bad_val"));
  350. // file2.sst (100 => 199)
  351. std::string file2 = sst_files_dir_ + "file2.sst";
  352. ASSERT_OK(sst_file_writer.Open(file2));
  353. for (int k = 100; k < 200; k++) {
  354. ASSERT_OK(sst_file_writer.Put(Key(k), Key(k) + "_val"));
  355. }
  356. // Cannot add this key because it's not after last added key
  357. ASSERT_NOK(sst_file_writer.Put(Key(99), "bad_val"));
  358. ExternalSstFileInfo file2_info;
  359. ASSERT_OK(sst_file_writer.Finish(&file2_info));
  360. ASSERT_EQ(file2_info.file_path, file2);
  361. ASSERT_EQ(file2_info.num_entries, 100);
  362. ASSERT_EQ(file2_info.smallest_key, Key(100));
  363. ASSERT_EQ(file2_info.largest_key, Key(199));
  364. // file3.sst (195 => 299)
  365. // This file values overlap with file2 values
  366. std::string file3 = sst_files_dir_ + "file3.sst";
  367. ASSERT_OK(sst_file_writer.Open(file3));
  368. for (int k = 195; k < 300; k++) {
  369. ASSERT_OK(sst_file_writer.Put(Key(k), Key(k) + "_val_overlap"));
  370. }
  371. ExternalSstFileInfo file3_info;
  372. ASSERT_OK(sst_file_writer.Finish(&file3_info));
  373. // Current file size should be non-zero after success finish.
  374. ASSERT_GT(sst_file_writer.FileSize(), 0);
  375. ASSERT_EQ(file3_info.file_path, file3);
  376. ASSERT_EQ(file3_info.num_entries, 105);
  377. ASSERT_EQ(file3_info.smallest_key, Key(195));
  378. ASSERT_EQ(file3_info.largest_key, Key(299));
  379. // file4.sst (30 => 39)
  380. // This file values overlap with file1 values
  381. std::string file4 = sst_files_dir_ + "file4.sst";
  382. ASSERT_OK(sst_file_writer.Open(file4));
  383. for (int k = 30; k < 40; k++) {
  384. ASSERT_OK(sst_file_writer.Put(Key(k), Key(k) + "_val_overlap"));
  385. }
  386. ExternalSstFileInfo file4_info;
  387. ASSERT_OK(sst_file_writer.Finish(&file4_info));
  388. ASSERT_EQ(file4_info.file_path, file4);
  389. ASSERT_EQ(file4_info.num_entries, 10);
  390. ASSERT_EQ(file4_info.smallest_key, Key(30));
  391. ASSERT_EQ(file4_info.largest_key, Key(39));
  392. // file5.sst (400 => 499)
  393. std::string file5 = sst_files_dir_ + "file5.sst";
  394. ASSERT_OK(sst_file_writer.Open(file5));
  395. for (int k = 400; k < 500; k++) {
  396. ASSERT_OK(sst_file_writer.Put(Key(k), Key(k) + "_val"));
  397. }
  398. ExternalSstFileInfo file5_info;
  399. ASSERT_OK(sst_file_writer.Finish(&file5_info));
  400. ASSERT_EQ(file5_info.file_path, file5);
  401. ASSERT_EQ(file5_info.num_entries, 100);
  402. ASSERT_EQ(file5_info.smallest_key, Key(400));
  403. ASSERT_EQ(file5_info.largest_key, Key(499));
  404. // file6.sst (delete 400 => 500)
  405. std::string file6 = sst_files_dir_ + "file6.sst";
  406. ASSERT_OK(sst_file_writer.Open(file6));
  407. ASSERT_OK(sst_file_writer.DeleteRange(Key(400), Key(500)));
  408. ExternalSstFileInfo file6_info;
  409. ASSERT_OK(sst_file_writer.Finish(&file6_info));
  410. ASSERT_EQ(file6_info.file_path, file6);
  411. ASSERT_EQ(file6_info.num_entries, 0);
  412. ASSERT_EQ(file6_info.smallest_key, "");
  413. ASSERT_EQ(file6_info.largest_key, "");
  414. ASSERT_EQ(file6_info.num_range_del_entries, 1);
  415. ASSERT_EQ(file6_info.smallest_range_del_key, Key(400));
  416. ASSERT_EQ(file6_info.largest_range_del_key, Key(500));
  417. // file7.sst (delete 500 => 570, put 520 => 599 divisible by 2)
  418. std::string file7 = sst_files_dir_ + "file7.sst";
  419. ASSERT_OK(sst_file_writer.Open(file7));
  420. ASSERT_OK(sst_file_writer.DeleteRange(Key(500), Key(550)));
  421. for (int k = 520; k < 560; k += 2) {
  422. ASSERT_OK(sst_file_writer.Put(Key(k), Key(k) + "_val"));
  423. }
  424. ASSERT_OK(sst_file_writer.DeleteRange(Key(525), Key(575)));
  425. for (int k = 560; k < 600; k += 2) {
  426. ASSERT_OK(sst_file_writer.Put(Key(k), Key(k) + "_val"));
  427. }
  428. ExternalSstFileInfo file7_info;
  429. ASSERT_OK(sst_file_writer.Finish(&file7_info));
  430. ASSERT_EQ(file7_info.file_path, file7);
  431. ASSERT_EQ(file7_info.num_entries, 40);
  432. ASSERT_EQ(file7_info.smallest_key, Key(520));
  433. ASSERT_EQ(file7_info.largest_key, Key(598));
  434. ASSERT_EQ(file7_info.num_range_del_entries, 2);
  435. ASSERT_EQ(file7_info.smallest_range_del_key, Key(500));
  436. ASSERT_EQ(file7_info.largest_range_del_key, Key(575));
  437. // file8.sst (delete 600 => 700)
  438. std::string file8 = sst_files_dir_ + "file8.sst";
  439. ASSERT_OK(sst_file_writer.Open(file8));
  440. ASSERT_OK(sst_file_writer.DeleteRange(Key(600), Key(700)));
  441. ExternalSstFileInfo file8_info;
  442. ASSERT_OK(sst_file_writer.Finish(&file8_info));
  443. ASSERT_EQ(file8_info.file_path, file8);
  444. ASSERT_EQ(file8_info.num_entries, 0);
  445. ASSERT_EQ(file8_info.smallest_key, "");
  446. ASSERT_EQ(file8_info.largest_key, "");
  447. ASSERT_EQ(file8_info.num_range_del_entries, 1);
  448. ASSERT_EQ(file8_info.smallest_range_del_key, Key(600));
  449. ASSERT_EQ(file8_info.largest_range_del_key, Key(700));
  450. // Cannot create an empty sst file
  451. std::string file_empty = sst_files_dir_ + "file_empty.sst";
  452. ExternalSstFileInfo file_empty_info;
  453. ASSERT_NOK(sst_file_writer.Finish(&file_empty_info));
  454. DestroyAndReopen(options);
  455. // Add file using file path
  456. ASSERT_OK(DeprecatedAddFile({file1}));
  457. ASSERT_EQ(db_->GetLatestSequenceNumber(), 0U);
  458. for (int k = 0; k < 100; k++) {
  459. ASSERT_EQ(Get(Key(k)), Key(k) + "_val");
  460. }
  461. // Add file while holding a snapshot will fail
  462. const Snapshot* s1 = db_->GetSnapshot();
  463. if (s1 != nullptr) {
  464. ASSERT_NOK(DeprecatedAddFile({file2}));
  465. db_->ReleaseSnapshot(s1);
  466. }
  467. // We can add the file after releaseing the snapshot
  468. ASSERT_OK(DeprecatedAddFile({file2}));
  469. ASSERT_EQ(db_->GetLatestSequenceNumber(), 0U);
  470. for (int k = 0; k < 200; k++) {
  471. ASSERT_EQ(Get(Key(k)), Key(k) + "_val");
  472. }
  473. // This file has overlapping values with the existing data
  474. ASSERT_NOK(DeprecatedAddFile({file3}));
  475. // This file has overlapping values with the existing data
  476. ASSERT_NOK(DeprecatedAddFile({file4}));
  477. // Overwrite values of keys divisible by 5
  478. for (int k = 0; k < 200; k += 5) {
  479. ASSERT_OK(Put(Key(k), Key(k) + "_val_new"));
  480. }
  481. ASSERT_NE(db_->GetLatestSequenceNumber(), 0U);
  482. // Key range of file5 (400 => 499) don't overlap with any keys in DB
  483. ASSERT_OK(DeprecatedAddFile({file5}));
  484. // This file has overlapping values with the existing data
  485. ASSERT_NOK(DeprecatedAddFile({file6}));
  486. // Key range of file7 (500 => 598) don't overlap with any keys in DB
  487. ASSERT_OK(DeprecatedAddFile({file7}));
  488. // Key range of file7 (600 => 700) don't overlap with any keys in DB
  489. ASSERT_OK(DeprecatedAddFile({file8}));
  490. // Make sure values are correct before and after flush/compaction
  491. for (int i = 0; i < 2; i++) {
  492. for (int k = 0; k < 200; k++) {
  493. std::string value = Key(k) + "_val";
  494. if (k % 5 == 0) {
  495. value += "_new";
  496. }
  497. ASSERT_EQ(Get(Key(k)), value);
  498. }
  499. for (int k = 400; k < 500; k++) {
  500. std::string value = Key(k) + "_val";
  501. ASSERT_EQ(Get(Key(k)), value);
  502. }
  503. for (int k = 500; k < 600; k++) {
  504. std::string value = Key(k) + "_val";
  505. if (k < 520 || k % 2 == 1) {
  506. value = "NOT_FOUND";
  507. }
  508. ASSERT_EQ(Get(Key(k)), value);
  509. }
  510. ASSERT_OK(Flush());
  511. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  512. }
  513. Close();
  514. options.disable_auto_compactions = true;
  515. Reopen(options);
  516. // Delete keys in range (400 => 499)
  517. for (int k = 400; k < 500; k++) {
  518. ASSERT_OK(Delete(Key(k)));
  519. }
  520. // We deleted range (400 => 499) but cannot add file5 because
  521. // of the range tombstones
  522. ASSERT_NOK(DeprecatedAddFile({file5}));
  523. // Compacting the DB will remove the tombstones
  524. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  525. // Now we can add the file
  526. ASSERT_OK(DeprecatedAddFile({file5}));
  527. // Verify values of file5 in DB
  528. for (int k = 400; k < 500; k++) {
  529. std::string value = Key(k) + "_val";
  530. ASSERT_EQ(Get(Key(k)), value);
  531. }
  532. DestroyAndRecreateExternalSSTFilesDir();
  533. } while (ChangeOptions(kSkipPlainTable | kSkipFIFOCompaction |
  534. kRangeDelSkipConfigs));
  535. }
  536. TEST_F(ExternalSSTFileTest, BasicWideColumn) {
  537. do {
  538. Options options = CurrentOptions();
  539. SstFileWriter sst_file_writer(EnvOptions(), options);
  540. // Current file size should be 0 after sst_file_writer init and before open
  541. // a file.
  542. ASSERT_EQ(sst_file_writer.FileSize(), 0);
  543. std::string file = sst_files_dir_ + "wide_column_file.sst";
  544. ASSERT_OK(sst_file_writer.Open(file));
  545. for (int k = 0; k < 10; k++) {
  546. std::string val1 = Key(k) + "_attr_1_val";
  547. std::string val2 = Key(k) + "_attr_2_val";
  548. WideColumns columns{{"attr_1", val1}, {"attr_2", val2}};
  549. ASSERT_OK(sst_file_writer.PutEntity(Key(k), columns));
  550. }
  551. ExternalSstFileInfo file_info;
  552. ASSERT_OK(sst_file_writer.Finish(&file_info));
  553. // Current file size should be non-zero after success write.
  554. ASSERT_GT(sst_file_writer.FileSize(), 0);
  555. ASSERT_EQ(file_info.file_path, file);
  556. ASSERT_EQ(file_info.num_entries, 10);
  557. ASSERT_EQ(file_info.smallest_key, Key(0));
  558. ASSERT_EQ(file_info.largest_key, Key(9));
  559. ASSERT_EQ(file_info.num_range_del_entries, 0);
  560. ASSERT_EQ(file_info.smallest_range_del_key, "");
  561. ASSERT_EQ(file_info.largest_range_del_key, "");
  562. DestroyAndReopen(options);
  563. // Add file using file path
  564. ASSERT_OK(DeprecatedAddFile({file}));
  565. ASSERT_EQ(db_->GetLatestSequenceNumber(), 0U);
  566. for (int k = 0; k < 10; k++) {
  567. PinnableWideColumns result;
  568. ASSERT_OK(db_->GetEntity(ReadOptions(), db_->DefaultColumnFamily(),
  569. Key(k), &result));
  570. std::string val1 = Key(k) + "_attr_1_val";
  571. std::string val2 = Key(k) + "_attr_2_val";
  572. WideColumns expected_columns{{"attr_1", val1}, {"attr_2", val2}};
  573. ASSERT_EQ(result.columns(), expected_columns);
  574. }
  575. } while (ChangeOptions(kSkipPlainTable | kSkipFIFOCompaction |
  576. kRangeDelSkipConfigs));
  577. }
  578. TEST_F(ExternalSSTFileTest, BasicMixed) {
  579. do {
  580. Options options = CurrentOptions();
  581. SstFileWriter sst_file_writer(EnvOptions(), options);
  582. // Current file size should be 0 after sst_file_writer init and before open
  583. // a file.
  584. ASSERT_EQ(sst_file_writer.FileSize(), 0);
  585. std::string file = sst_files_dir_ + "mixed_file.sst";
  586. ASSERT_OK(sst_file_writer.Open(file));
  587. for (int k = 0; k < 100; k++) {
  588. if (k % 5 == 0) {
  589. std::string val1 = Key(k) + "_attr_1_val";
  590. std::string val2 = Key(k) + "_attr_2_val";
  591. WideColumns columns{{"attr_1", val1}, {"attr_2", val2}};
  592. ASSERT_OK(sst_file_writer.PutEntity(Key(k), columns));
  593. } else {
  594. ASSERT_OK(sst_file_writer.Put(Key(k), Key(k) + "_val"));
  595. }
  596. }
  597. ExternalSstFileInfo file_info;
  598. ASSERT_OK(sst_file_writer.Finish(&file_info));
  599. // Current file size should be non-zero after success write.
  600. ASSERT_GT(sst_file_writer.FileSize(), 0);
  601. ASSERT_EQ(file_info.file_path, file);
  602. ASSERT_EQ(file_info.num_entries, 100);
  603. ASSERT_EQ(file_info.smallest_key, Key(0));
  604. ASSERT_EQ(file_info.largest_key, Key(99));
  605. ASSERT_EQ(file_info.num_range_del_entries, 0);
  606. ASSERT_EQ(file_info.smallest_range_del_key, "");
  607. ASSERT_EQ(file_info.largest_range_del_key, "");
  608. DestroyAndReopen(options);
  609. // Add file using file path
  610. ASSERT_OK(DeprecatedAddFile({file}));
  611. ASSERT_EQ(db_->GetLatestSequenceNumber(), 0U);
  612. for (int k = 0; k < 10; k++) {
  613. if (k % 5 == 0) {
  614. PinnableWideColumns result;
  615. ASSERT_OK(db_->GetEntity(ReadOptions(), db_->DefaultColumnFamily(),
  616. Key(k), &result));
  617. std::string val1 = Key(k) + "_attr_1_val";
  618. std::string val2 = Key(k) + "_attr_2_val";
  619. WideColumns expected_columns{{"attr_1", val1}, {"attr_2", val2}};
  620. ASSERT_EQ(result.columns(), expected_columns);
  621. } else {
  622. ASSERT_EQ(Get(Key(k)), Key(k) + "_val");
  623. }
  624. }
  625. } while (ChangeOptions(kSkipPlainTable | kSkipFIFOCompaction |
  626. kRangeDelSkipConfigs));
  627. }
  628. class SstFileWriterCollector : public TablePropertiesCollector {
  629. public:
  630. explicit SstFileWriterCollector(const std::string prefix) : prefix_(prefix) {
  631. name_ = prefix_ + "_SstFileWriterCollector";
  632. }
  633. const char* Name() const override { return name_.c_str(); }
  634. Status Finish(UserCollectedProperties* properties) override {
  635. std::string count = std::to_string(count_);
  636. properties->insert({prefix_ + "_SstFileWriterCollector", "YES"});
  637. properties->insert({prefix_ + "_Count", count});
  638. return Status::OK();
  639. }
  640. Status AddUserKey(const Slice& /*user_key*/, const Slice& /*value*/,
  641. EntryType /*type*/, SequenceNumber /*seq*/,
  642. uint64_t /*file_size*/) override {
  643. ++count_;
  644. return Status::OK();
  645. }
  646. UserCollectedProperties GetReadableProperties() const override {
  647. return UserCollectedProperties{};
  648. }
  649. private:
  650. uint32_t count_ = 0;
  651. std::string prefix_;
  652. std::string name_;
  653. };
  654. class SstFileWriterCollectorFactory : public TablePropertiesCollectorFactory {
  655. public:
  656. explicit SstFileWriterCollectorFactory(std::string prefix)
  657. : prefix_(prefix), num_created_(0) {}
  658. TablePropertiesCollector* CreateTablePropertiesCollector(
  659. TablePropertiesCollectorFactory::Context /*context*/) override {
  660. num_created_++;
  661. return new SstFileWriterCollector(prefix_);
  662. }
  663. const char* Name() const override { return "SstFileWriterCollectorFactory"; }
  664. std::string prefix_;
  665. uint32_t num_created_;
  666. };
  667. TEST_F(ExternalSSTFileTest, AddList) {
  668. do {
  669. Options options = CurrentOptions();
  670. auto abc_collector = std::make_shared<SstFileWriterCollectorFactory>("abc");
  671. auto xyz_collector = std::make_shared<SstFileWriterCollectorFactory>("xyz");
  672. options.table_properties_collector_factories.emplace_back(abc_collector);
  673. options.table_properties_collector_factories.emplace_back(xyz_collector);
  674. SstFileWriter sst_file_writer(EnvOptions(), options);
  675. // file1.sst (0 => 99)
  676. std::string file1 = sst_files_dir_ + "file1.sst";
  677. ASSERT_OK(sst_file_writer.Open(file1));
  678. for (int k = 0; k < 100; k++) {
  679. ASSERT_OK(sst_file_writer.Put(Key(k), Key(k) + "_val"));
  680. }
  681. ExternalSstFileInfo file1_info;
  682. ASSERT_OK(sst_file_writer.Finish(&file1_info));
  683. ASSERT_EQ(file1_info.file_path, file1);
  684. ASSERT_EQ(file1_info.num_entries, 100);
  685. ASSERT_EQ(file1_info.smallest_key, Key(0));
  686. ASSERT_EQ(file1_info.largest_key, Key(99));
  687. // sst_file_writer already finished, cannot add this value
  688. ASSERT_NOK(sst_file_writer.Put(Key(100), "bad_val"));
  689. // file2.sst (100 => 199)
  690. std::string file2 = sst_files_dir_ + "file2.sst";
  691. ASSERT_OK(sst_file_writer.Open(file2));
  692. for (int k = 100; k < 200; k++) {
  693. ASSERT_OK(sst_file_writer.Put(Key(k), Key(k) + "_val"));
  694. }
  695. // Cannot add this key because it's not after last added key
  696. ASSERT_NOK(sst_file_writer.Put(Key(99), "bad_val"));
  697. ExternalSstFileInfo file2_info;
  698. ASSERT_OK(sst_file_writer.Finish(&file2_info));
  699. ASSERT_EQ(file2_info.file_path, file2);
  700. ASSERT_EQ(file2_info.num_entries, 100);
  701. ASSERT_EQ(file2_info.smallest_key, Key(100));
  702. ASSERT_EQ(file2_info.largest_key, Key(199));
  703. // file3.sst (195 => 199)
  704. // This file values overlap with file2 values
  705. std::string file3 = sst_files_dir_ + "file3.sst";
  706. ASSERT_OK(sst_file_writer.Open(file3));
  707. for (int k = 195; k < 200; k++) {
  708. ASSERT_OK(sst_file_writer.Put(Key(k), Key(k) + "_val_overlap"));
  709. }
  710. ExternalSstFileInfo file3_info;
  711. ASSERT_OK(sst_file_writer.Finish(&file3_info));
  712. ASSERT_EQ(file3_info.file_path, file3);
  713. ASSERT_EQ(file3_info.num_entries, 5);
  714. ASSERT_EQ(file3_info.smallest_key, Key(195));
  715. ASSERT_EQ(file3_info.largest_key, Key(199));
  716. // file4.sst (30 => 39)
  717. // This file values overlap with file1 values
  718. std::string file4 = sst_files_dir_ + "file4.sst";
  719. ASSERT_OK(sst_file_writer.Open(file4));
  720. for (int k = 30; k < 40; k++) {
  721. ASSERT_OK(sst_file_writer.Put(Key(k), Key(k) + "_val_overlap"));
  722. }
  723. ExternalSstFileInfo file4_info;
  724. ASSERT_OK(sst_file_writer.Finish(&file4_info));
  725. ASSERT_EQ(file4_info.file_path, file4);
  726. ASSERT_EQ(file4_info.num_entries, 10);
  727. ASSERT_EQ(file4_info.smallest_key, Key(30));
  728. ASSERT_EQ(file4_info.largest_key, Key(39));
  729. // file5.sst (200 => 299)
  730. std::string file5 = sst_files_dir_ + "file5.sst";
  731. ASSERT_OK(sst_file_writer.Open(file5));
  732. for (int k = 200; k < 300; k++) {
  733. ASSERT_OK(sst_file_writer.Put(Key(k), Key(k) + "_val"));
  734. }
  735. ExternalSstFileInfo file5_info;
  736. ASSERT_OK(sst_file_writer.Finish(&file5_info));
  737. ASSERT_EQ(file5_info.file_path, file5);
  738. ASSERT_EQ(file5_info.num_entries, 100);
  739. ASSERT_EQ(file5_info.smallest_key, Key(200));
  740. ASSERT_EQ(file5_info.largest_key, Key(299));
  741. // file6.sst (delete 0 => 100)
  742. std::string file6 = sst_files_dir_ + "file6.sst";
  743. ASSERT_OK(sst_file_writer.Open(file6));
  744. ASSERT_OK(sst_file_writer.DeleteRange(Key(0), Key(75)));
  745. ASSERT_OK(sst_file_writer.DeleteRange(Key(25), Key(100)));
  746. ExternalSstFileInfo file6_info;
  747. ASSERT_OK(sst_file_writer.Finish(&file6_info));
  748. ASSERT_EQ(file6_info.file_path, file6);
  749. ASSERT_EQ(file6_info.num_entries, 0);
  750. ASSERT_EQ(file6_info.smallest_key, "");
  751. ASSERT_EQ(file6_info.largest_key, "");
  752. ASSERT_EQ(file6_info.num_range_del_entries, 2);
  753. ASSERT_EQ(file6_info.smallest_range_del_key, Key(0));
  754. ASSERT_EQ(file6_info.largest_range_del_key, Key(100));
  755. // file7.sst (delete 99 => 201)
  756. std::string file7 = sst_files_dir_ + "file7.sst";
  757. ASSERT_OK(sst_file_writer.Open(file7));
  758. ASSERT_OK(sst_file_writer.DeleteRange(Key(99), Key(201)));
  759. ExternalSstFileInfo file7_info;
  760. ASSERT_OK(sst_file_writer.Finish(&file7_info));
  761. ASSERT_EQ(file7_info.file_path, file7);
  762. ASSERT_EQ(file7_info.num_entries, 0);
  763. ASSERT_EQ(file7_info.smallest_key, "");
  764. ASSERT_EQ(file7_info.largest_key, "");
  765. ASSERT_EQ(file7_info.num_range_del_entries, 1);
  766. ASSERT_EQ(file7_info.smallest_range_del_key, Key(99));
  767. ASSERT_EQ(file7_info.largest_range_del_key, Key(201));
  768. // list 1 has internal key range conflict
  769. std::vector<std::string> file_list0({file1, file2});
  770. std::vector<std::string> file_list1({file3, file2, file1});
  771. std::vector<std::string> file_list2({file5});
  772. std::vector<std::string> file_list3({file3, file4});
  773. std::vector<std::string> file_list4({file5, file7});
  774. std::vector<std::string> file_list5({file6, file7});
  775. DestroyAndReopen(options);
  776. // These lists of files have key ranges that overlap with each other
  777. ASSERT_NOK(DeprecatedAddFile(file_list1));
  778. // Both of the following overlap on the range deletion tombstone.
  779. ASSERT_NOK(DeprecatedAddFile(file_list4));
  780. ASSERT_NOK(DeprecatedAddFile(file_list5));
  781. // Add files using file path list
  782. ASSERT_OK(DeprecatedAddFile(file_list0));
  783. ASSERT_EQ(db_->GetLatestSequenceNumber(), 0U);
  784. for (int k = 0; k < 200; k++) {
  785. ASSERT_EQ(Get(Key(k)), Key(k) + "_val");
  786. }
  787. TablePropertiesCollection props;
  788. ASSERT_OK(db_->GetPropertiesOfAllTables(&props));
  789. ASSERT_EQ(props.size(), 2);
  790. for (const auto& file_props : props) {
  791. auto user_props = file_props.second->user_collected_properties;
  792. ASSERT_EQ(user_props["abc_SstFileWriterCollector"], "YES");
  793. ASSERT_EQ(user_props["xyz_SstFileWriterCollector"], "YES");
  794. ASSERT_EQ(user_props["abc_Count"], "100");
  795. ASSERT_EQ(user_props["xyz_Count"], "100");
  796. }
  797. // Add file while holding a snapshot will fail
  798. const Snapshot* s1 = db_->GetSnapshot();
  799. if (s1 != nullptr) {
  800. ASSERT_NOK(DeprecatedAddFile(file_list2));
  801. db_->ReleaseSnapshot(s1);
  802. }
  803. // We can add the file after releaseing the snapshot
  804. ASSERT_OK(DeprecatedAddFile(file_list2));
  805. ASSERT_EQ(db_->GetLatestSequenceNumber(), 0U);
  806. for (int k = 0; k < 300; k++) {
  807. ASSERT_EQ(Get(Key(k)), Key(k) + "_val");
  808. }
  809. ASSERT_OK(db_->GetPropertiesOfAllTables(&props));
  810. ASSERT_EQ(props.size(), 3);
  811. for (const auto& file_props : props) {
  812. auto user_props = file_props.second->user_collected_properties;
  813. ASSERT_EQ(user_props["abc_SstFileWriterCollector"], "YES");
  814. ASSERT_EQ(user_props["xyz_SstFileWriterCollector"], "YES");
  815. ASSERT_EQ(user_props["abc_Count"], "100");
  816. ASSERT_EQ(user_props["xyz_Count"], "100");
  817. }
  818. // This file list has overlapping values with the existing data
  819. ASSERT_NOK(DeprecatedAddFile(file_list3));
  820. // Overwrite values of keys divisible by 5
  821. for (int k = 0; k < 200; k += 5) {
  822. ASSERT_OK(Put(Key(k), Key(k) + "_val_new"));
  823. }
  824. ASSERT_NE(db_->GetLatestSequenceNumber(), 0U);
  825. // Make sure values are correct before and after flush/compaction
  826. for (int i = 0; i < 2; i++) {
  827. for (int k = 0; k < 200; k++) {
  828. std::string value = Key(k) + "_val";
  829. if (k % 5 == 0) {
  830. value += "_new";
  831. }
  832. ASSERT_EQ(Get(Key(k)), value);
  833. }
  834. for (int k = 200; k < 300; k++) {
  835. std::string value = Key(k) + "_val";
  836. ASSERT_EQ(Get(Key(k)), value);
  837. }
  838. ASSERT_OK(Flush());
  839. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  840. }
  841. // Delete keys in range (200 => 299)
  842. for (int k = 200; k < 300; k++) {
  843. ASSERT_OK(Delete(Key(k)));
  844. }
  845. // We deleted range (200 => 299) but cannot add file5 because
  846. // of the range tombstones
  847. ASSERT_NOK(DeprecatedAddFile(file_list2));
  848. // Compacting the DB will remove the tombstones
  849. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  850. // Now we can add the file
  851. ASSERT_OK(DeprecatedAddFile(file_list2));
  852. // Verify values of file5 in DB
  853. for (int k = 200; k < 300; k++) {
  854. std::string value = Key(k) + "_val";
  855. ASSERT_EQ(Get(Key(k)), value);
  856. }
  857. DestroyAndRecreateExternalSSTFilesDir();
  858. } while (ChangeOptions(kSkipPlainTable | kSkipFIFOCompaction |
  859. kRangeDelSkipConfigs));
  860. }
  861. TEST_F(ExternalSSTFileTest, AddListAtomicity) {
  862. do {
  863. Options options = CurrentOptions();
  864. SstFileWriter sst_file_writer(EnvOptions(), options);
  865. // files[0].sst (0 => 99)
  866. // files[1].sst (100 => 199)
  867. // ...
  868. // file[8].sst (800 => 899)
  869. int n = 9;
  870. std::vector<std::string> files(n);
  871. std::vector<ExternalSstFileInfo> files_info(n);
  872. for (int i = 0; i < n; i++) {
  873. files[i] = sst_files_dir_ + "file" + std::to_string(i) + ".sst";
  874. ASSERT_OK(sst_file_writer.Open(files[i]));
  875. for (int k = i * 100; k < (i + 1) * 100; k++) {
  876. ASSERT_OK(sst_file_writer.Put(Key(k), Key(k) + "_val"));
  877. }
  878. ASSERT_OK(sst_file_writer.Finish(&files_info[i]));
  879. ASSERT_EQ(files_info[i].file_path, files[i]);
  880. ASSERT_EQ(files_info[i].num_entries, 100);
  881. ASSERT_EQ(files_info[i].smallest_key, Key(i * 100));
  882. ASSERT_EQ(files_info[i].largest_key, Key((i + 1) * 100 - 1));
  883. }
  884. files.push_back(sst_files_dir_ + "file" + std::to_string(n) + ".sst");
  885. ASSERT_NOK(DeprecatedAddFile(files));
  886. for (int k = 0; k < n * 100; k++) {
  887. ASSERT_EQ("NOT_FOUND", Get(Key(k)));
  888. }
  889. files.pop_back();
  890. ASSERT_OK(DeprecatedAddFile(files));
  891. for (int k = 0; k < n * 100; k++) {
  892. std::string value = Key(k) + "_val";
  893. ASSERT_EQ(Get(Key(k)), value);
  894. }
  895. DestroyAndRecreateExternalSSTFilesDir();
  896. } while (ChangeOptions(kSkipPlainTable | kSkipFIFOCompaction));
  897. }
  898. // This test reporduce a bug that can happen in some cases if the DB started
  899. // purging obsolete files when we are adding an external sst file.
  900. // This situation may result in deleting the file while it's being added.
  901. TEST_F(ExternalSSTFileTest, PurgeObsoleteFilesBug) {
  902. Options options = CurrentOptions();
  903. SstFileWriter sst_file_writer(EnvOptions(), options);
  904. // file1.sst (0 => 500)
  905. std::string sst_file_path = sst_files_dir_ + "file1.sst";
  906. ASSERT_OK(sst_file_writer.Open(sst_file_path));
  907. for (int i = 0; i < 500; i++) {
  908. std::string k = Key(i);
  909. ASSERT_OK(sst_file_writer.Put(k, k + "_val"));
  910. }
  911. ExternalSstFileInfo sst_file_info;
  912. ASSERT_OK(sst_file_writer.Finish(&sst_file_info));
  913. options.delete_obsolete_files_period_micros = 0;
  914. options.disable_auto_compactions = true;
  915. DestroyAndReopen(options);
  916. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  917. "ExternalSstFileIngestionJob::Prepare:FileAdded", [&](void* /* arg */) {
  918. ASSERT_OK(Put("aaa", "bbb"));
  919. ASSERT_OK(Flush());
  920. ASSERT_OK(Put("aaa", "xxx"));
  921. ASSERT_OK(Flush());
  922. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  923. });
  924. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  925. ASSERT_OK(DeprecatedAddFile({sst_file_path}));
  926. for (int i = 0; i < 500; i++) {
  927. std::string k = Key(i);
  928. std::string v = k + "_val";
  929. ASSERT_EQ(Get(k), v);
  930. }
  931. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  932. }
  933. TEST_F(ExternalSSTFileTest, SkipSnapshot) {
  934. Options options = CurrentOptions();
  935. SstFileWriter sst_file_writer(EnvOptions(), options);
  936. // file1.sst (0 => 99)
  937. std::string file1 = sst_files_dir_ + "file1.sst";
  938. ASSERT_OK(sst_file_writer.Open(file1));
  939. for (int k = 0; k < 100; k++) {
  940. ASSERT_OK(sst_file_writer.Put(Key(k), Key(k) + "_val"));
  941. }
  942. ExternalSstFileInfo file1_info;
  943. ASSERT_OK(sst_file_writer.Finish(&file1_info));
  944. ASSERT_EQ(file1_info.file_path, file1);
  945. ASSERT_EQ(file1_info.num_entries, 100);
  946. ASSERT_EQ(file1_info.smallest_key, Key(0));
  947. ASSERT_EQ(file1_info.largest_key, Key(99));
  948. // file2.sst (100 => 299)
  949. std::string file2 = sst_files_dir_ + "file2.sst";
  950. ASSERT_OK(sst_file_writer.Open(file2));
  951. for (int k = 100; k < 300; k++) {
  952. ASSERT_OK(sst_file_writer.Put(Key(k), Key(k) + "_val"));
  953. }
  954. ExternalSstFileInfo file2_info;
  955. ASSERT_OK(sst_file_writer.Finish(&file2_info));
  956. ASSERT_EQ(file2_info.file_path, file2);
  957. ASSERT_EQ(file2_info.num_entries, 200);
  958. ASSERT_EQ(file2_info.smallest_key, Key(100));
  959. ASSERT_EQ(file2_info.largest_key, Key(299));
  960. ASSERT_OK(DeprecatedAddFile({file1}));
  961. // Add file will fail when holding snapshot and use the default
  962. // skip_snapshot_check to false
  963. const Snapshot* s1 = db_->GetSnapshot();
  964. if (s1 != nullptr) {
  965. ASSERT_NOK(DeprecatedAddFile({file2}));
  966. }
  967. // Add file will success when set skip_snapshot_check to true even db holding
  968. // snapshot
  969. if (s1 != nullptr) {
  970. ASSERT_OK(DeprecatedAddFile({file2}, false, true));
  971. db_->ReleaseSnapshot(s1);
  972. }
  973. // file3.sst (300 => 399)
  974. std::string file3 = sst_files_dir_ + "file3.sst";
  975. ASSERT_OK(sst_file_writer.Open(file3));
  976. for (int k = 300; k < 400; k++) {
  977. ASSERT_OK(sst_file_writer.Put(Key(k), Key(k) + "_val"));
  978. }
  979. ExternalSstFileInfo file3_info;
  980. ASSERT_OK(sst_file_writer.Finish(&file3_info));
  981. ASSERT_EQ(file3_info.file_path, file3);
  982. ASSERT_EQ(file3_info.num_entries, 100);
  983. ASSERT_EQ(file3_info.smallest_key, Key(300));
  984. ASSERT_EQ(file3_info.largest_key, Key(399));
  985. // check that we have change the old key
  986. ASSERT_EQ(Get(Key(300)), "NOT_FOUND");
  987. const Snapshot* s2 = db_->GetSnapshot();
  988. ASSERT_OK(DeprecatedAddFile({file3}, false, true));
  989. ASSERT_EQ(Get(Key(300)), Key(300) + ("_val"));
  990. ASSERT_EQ(Get(Key(300), s2), Key(300) + ("_val"));
  991. db_->ReleaseSnapshot(s2);
  992. }
  993. TEST_F(ExternalSSTFileTest, MultiThreaded) {
  994. env_->skip_fsync_ = true;
  995. // Bulk load 10 files every file contain 1000 keys
  996. int num_files = 10;
  997. int keys_per_file = 1000;
  998. // Generate file names
  999. std::vector<std::string> file_names;
  1000. for (int i = 0; i < num_files; i++) {
  1001. std::string file_name = "file_" + std::to_string(i) + ".sst";
  1002. file_names.push_back(sst_files_dir_ + file_name);
  1003. }
  1004. do {
  1005. Options options = CurrentOptions();
  1006. options.disable_auto_compactions = true;
  1007. std::atomic<int> thread_num(0);
  1008. std::function<void()> write_file_func = [&]() {
  1009. int file_idx = thread_num.fetch_add(1);
  1010. int range_start = file_idx * keys_per_file;
  1011. int range_end = range_start + keys_per_file;
  1012. SstFileWriter sst_file_writer(EnvOptions(), options);
  1013. ASSERT_OK(sst_file_writer.Open(file_names[file_idx]));
  1014. for (int k = range_start; k < range_end; k++) {
  1015. ASSERT_OK(sst_file_writer.Put(Key(k), Key(k)));
  1016. }
  1017. ASSERT_OK(sst_file_writer.Finish());
  1018. };
  1019. // Write num_files files in parallel
  1020. std::vector<port::Thread> sst_writer_threads;
  1021. for (int i = 0; i < num_files; ++i) {
  1022. sst_writer_threads.emplace_back(write_file_func);
  1023. }
  1024. for (auto& t : sst_writer_threads) {
  1025. t.join();
  1026. }
  1027. fprintf(stderr, "Wrote %d files (%d keys)\n", num_files,
  1028. num_files * keys_per_file);
  1029. thread_num.store(0);
  1030. std::atomic<int> files_added(0);
  1031. // Thread 0 -> Load {f0,f1}
  1032. // Thread 1 -> Load {f0,f1}
  1033. // Thread 2 -> Load {f2,f3}
  1034. // Thread 3 -> Load {f2,f3}
  1035. // Thread 4 -> Load {f4,f5}
  1036. // Thread 5 -> Load {f4,f5}
  1037. // ...
  1038. std::function<void()> load_file_func = [&]() {
  1039. // We intentionally add every file twice, and assert that it was added
  1040. // only once and the other add failed
  1041. int thread_id = thread_num.fetch_add(1);
  1042. int file_idx = (thread_id / 2) * 2;
  1043. // sometimes we use copy, sometimes link .. the result should be the same
  1044. bool move_file = (thread_id % 3 == 0);
  1045. std::vector<std::string> files_to_add;
  1046. files_to_add = {file_names[file_idx]};
  1047. if (static_cast<size_t>(file_idx + 1) < file_names.size()) {
  1048. files_to_add.push_back(file_names[file_idx + 1]);
  1049. }
  1050. Status s = DeprecatedAddFile(files_to_add, move_file);
  1051. if (s.ok()) {
  1052. files_added += static_cast<int>(files_to_add.size());
  1053. }
  1054. };
  1055. // Bulk load num_files files in parallel
  1056. std::vector<port::Thread> add_file_threads;
  1057. DestroyAndReopen(options);
  1058. for (int i = 0; i < num_files; ++i) {
  1059. add_file_threads.emplace_back(load_file_func);
  1060. }
  1061. for (auto& t : add_file_threads) {
  1062. t.join();
  1063. }
  1064. ASSERT_EQ(files_added.load(), num_files);
  1065. fprintf(stderr, "Loaded %d files (%d keys)\n", num_files,
  1066. num_files * keys_per_file);
  1067. // Overwrite values of keys divisible by 100
  1068. for (int k = 0; k < num_files * keys_per_file; k += 100) {
  1069. std::string key = Key(k);
  1070. ASSERT_OK(Put(key, key + "_new"));
  1071. }
  1072. for (int i = 0; i < 2; i++) {
  1073. // Make sure the values are correct before and after flush/compaction
  1074. for (int k = 0; k < num_files * keys_per_file; ++k) {
  1075. std::string key = Key(k);
  1076. std::string value = (k % 100 == 0) ? (key + "_new") : key;
  1077. ASSERT_EQ(Get(key), value);
  1078. }
  1079. ASSERT_OK(Flush());
  1080. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  1081. }
  1082. fprintf(stderr, "Verified %d values\n", num_files * keys_per_file);
  1083. DestroyAndRecreateExternalSSTFilesDir();
  1084. } while (ChangeOptions(kSkipPlainTable | kSkipFIFOCompaction));
  1085. }
  1086. TEST_F(ExternalSSTFileTest, OverlappingRanges) {
  1087. env_->skip_fsync_ = true;
  1088. Random rnd(301);
  1089. SequenceNumber assigned_seqno = 0;
  1090. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1091. "ExternalSstFileIngestionJob::Run", [&assigned_seqno](void* arg) {
  1092. ASSERT_TRUE(arg != nullptr);
  1093. assigned_seqno = *(static_cast<SequenceNumber*>(arg));
  1094. });
  1095. bool need_flush = false;
  1096. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1097. "DBImpl::IngestExternalFile:NeedFlush", [&need_flush](void* arg) {
  1098. ASSERT_TRUE(arg != nullptr);
  1099. need_flush = *(static_cast<bool*>(arg));
  1100. });
  1101. bool overlap_with_db = false;
  1102. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1103. "ExternalSstFileIngestionJob::AssignLevelAndSeqnoForIngestedFile",
  1104. [&overlap_with_db](void* arg) {
  1105. ASSERT_TRUE(arg != nullptr);
  1106. overlap_with_db = *(static_cast<bool*>(arg));
  1107. });
  1108. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  1109. do {
  1110. Options options = CurrentOptions();
  1111. env_->skip_fsync_ = true;
  1112. DestroyAndReopen(options);
  1113. SstFileWriter sst_file_writer(EnvOptions(), options);
  1114. printf("Option config = %d\n", option_config_);
  1115. std::vector<std::pair<int, int>> key_ranges;
  1116. for (int i = 0; i < 100; i++) {
  1117. int range_start = rnd.Uniform(20000);
  1118. int keys_per_range = 10 + rnd.Uniform(41);
  1119. key_ranges.emplace_back(range_start, range_start + keys_per_range);
  1120. }
  1121. int memtable_add = 0;
  1122. int success_add_file = 0;
  1123. int failed_add_file = 0;
  1124. std::map<std::string, std::string> true_data;
  1125. for (size_t i = 0; i < key_ranges.size(); i++) {
  1126. int range_start = key_ranges[i].first;
  1127. int range_end = key_ranges[i].second;
  1128. Status s;
  1129. std::string range_val = "range_" + std::to_string(i);
  1130. // For 20% of ranges we use DB::Put, for 80% we use DB::AddFile
  1131. if (i && i % 5 == 0) {
  1132. // Use DB::Put to insert range (insert into memtable)
  1133. range_val += "_put";
  1134. for (int k = range_start; k <= range_end; k++) {
  1135. s = Put(Key(k), range_val);
  1136. ASSERT_OK(s);
  1137. }
  1138. memtable_add++;
  1139. } else {
  1140. // Use DB::AddFile to insert range
  1141. range_val += "_add_file";
  1142. // Generate the file containing the range
  1143. std::string file_name = sst_files_dir_ + env_->GenerateUniqueId();
  1144. s = sst_file_writer.Open(file_name);
  1145. ASSERT_OK(s);
  1146. for (int k = range_start; k <= range_end; k++) {
  1147. s = sst_file_writer.Put(Key(k), range_val);
  1148. ASSERT_OK(s);
  1149. }
  1150. ExternalSstFileInfo file_info;
  1151. s = sst_file_writer.Finish(&file_info);
  1152. ASSERT_OK(s);
  1153. // Insert the generated file
  1154. s = DeprecatedAddFile({file_name});
  1155. auto it = true_data.lower_bound(Key(range_start));
  1156. if (option_config_ != kUniversalCompaction &&
  1157. option_config_ != kUniversalCompactionMultiLevel &&
  1158. option_config_ != kUniversalSubcompactions) {
  1159. if (it != true_data.end() && it->first <= Key(range_end)) {
  1160. // This range overlap with data already exist in DB
  1161. ASSERT_NOK(s);
  1162. failed_add_file++;
  1163. } else {
  1164. ASSERT_OK(s);
  1165. success_add_file++;
  1166. }
  1167. } else {
  1168. if ((it != true_data.end() && it->first <= Key(range_end)) ||
  1169. need_flush || assigned_seqno > 0 || overlap_with_db) {
  1170. // This range overlap with data already exist in DB
  1171. ASSERT_NOK(s);
  1172. failed_add_file++;
  1173. } else {
  1174. ASSERT_OK(s);
  1175. success_add_file++;
  1176. }
  1177. }
  1178. }
  1179. if (s.ok()) {
  1180. // Update true_data map to include the new inserted data
  1181. for (int k = range_start; k <= range_end; k++) {
  1182. true_data[Key(k)] = range_val;
  1183. }
  1184. }
  1185. // Flush / Compact the DB
  1186. if (i && i % 50 == 0) {
  1187. ASSERT_OK(Flush());
  1188. }
  1189. if (i && i % 75 == 0) {
  1190. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  1191. }
  1192. }
  1193. printf("Total: %" ROCKSDB_PRIszt
  1194. " ranges\n"
  1195. "AddFile()|Success: %d ranges\n"
  1196. "AddFile()|RangeConflict: %d ranges\n"
  1197. "Put(): %d ranges\n",
  1198. key_ranges.size(), success_add_file, failed_add_file, memtable_add);
  1199. // Verify the correctness of the data
  1200. for (const auto& kv : true_data) {
  1201. ASSERT_EQ(Get(kv.first), kv.second);
  1202. }
  1203. printf("keys/values verified\n");
  1204. DestroyAndRecreateExternalSSTFilesDir();
  1205. } while (ChangeOptions(kSkipPlainTable | kSkipFIFOCompaction));
  1206. }
  1207. TEST_P(ExternalSSTFileTest, PickedLevel) {
  1208. env_->skip_fsync_ = true;
  1209. Options options = CurrentOptions();
  1210. options.disable_auto_compactions = false;
  1211. options.level0_file_num_compaction_trigger = 4;
  1212. options.num_levels = 4;
  1213. DestroyAndReopen(options);
  1214. std::map<std::string, std::string> true_data;
  1215. // File 0 will go to last level (L3)
  1216. ASSERT_OK(GenerateAndAddExternalFile(options, {1, 10}, -1, false, false, true,
  1217. false, false, &true_data));
  1218. EXPECT_EQ(FilesPerLevel(), "0,0,0,1");
  1219. // File 1 will go to level L2 (since it overlap with file 0 in L3)
  1220. ASSERT_OK(GenerateAndAddExternalFile(options, {2, 9}, -1, false, false, true,
  1221. false, false, &true_data));
  1222. EXPECT_EQ(FilesPerLevel(), "0,0,1,1");
  1223. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency({
  1224. {"ExternalSSTFileTest::PickedLevel:0", "BackgroundCallCompaction:0"},
  1225. {"DBImpl::BackgroundCompaction:Start",
  1226. "ExternalSSTFileTest::PickedLevel:1"},
  1227. {"ExternalSSTFileTest::PickedLevel:2",
  1228. "DBImpl::BackgroundCompaction:NonTrivial:AfterRun"},
  1229. });
  1230. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  1231. // Flush 4 files containing the same keys
  1232. for (int i = 0; i < 4; i++) {
  1233. ASSERT_OK(Put(Key(3), Key(3) + "put"));
  1234. ASSERT_OK(Put(Key(8), Key(8) + "put"));
  1235. true_data[Key(3)] = Key(3) + "put";
  1236. true_data[Key(8)] = Key(8) + "put";
  1237. ASSERT_OK(Flush());
  1238. }
  1239. // Wait for BackgroundCompaction() to be called
  1240. TEST_SYNC_POINT("ExternalSSTFileTest::PickedLevel:0");
  1241. TEST_SYNC_POINT("ExternalSSTFileTest::PickedLevel:1");
  1242. EXPECT_EQ(FilesPerLevel(), "4,0,1,1");
  1243. // This file overlaps with file 0 (L3), file 1 (L2) and the
  1244. // output of compaction going to L1
  1245. ASSERT_OK(GenerateAndAddExternalFile(options, {4, 7}, -1,
  1246. true /* allow_global_seqno */, false,
  1247. true, false, false, &true_data));
  1248. EXPECT_EQ(FilesPerLevel(), "5,0,1,1");
  1249. // This file does not overlap with any file or with the running compaction
  1250. ASSERT_OK(GenerateAndAddExternalFile(options, {9000, 9001}, -1, false, false,
  1251. false, false, false, &true_data));
  1252. EXPECT_EQ(FilesPerLevel(), "5,0,1,2");
  1253. // Hold compaction from finishing
  1254. TEST_SYNC_POINT("ExternalSSTFileTest::PickedLevel:2");
  1255. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  1256. EXPECT_EQ(FilesPerLevel(), "1,1,1,2");
  1257. size_t kcnt = 0;
  1258. VerifyDBFromMap(true_data, &kcnt, false);
  1259. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  1260. }
  1261. TEST_F(ExternalSSTFileTest, IngestNonExistingFile) {
  1262. Options options = CurrentOptions();
  1263. DestroyAndReopen(options);
  1264. Status s = db_->IngestExternalFile({"non_existing_file"},
  1265. IngestExternalFileOptions());
  1266. ASSERT_NOK(s);
  1267. // Verify file deletion is not impacted (verify a bug fix)
  1268. ASSERT_OK(Put(Key(1), Key(1)));
  1269. ASSERT_OK(Put(Key(9), Key(9)));
  1270. ASSERT_OK(Flush());
  1271. ASSERT_OK(Put(Key(1), Key(1)));
  1272. ASSERT_OK(Put(Key(9), Key(9)));
  1273. ASSERT_OK(Flush());
  1274. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  1275. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  1276. // After full compaction, there should be only 1 file.
  1277. std::vector<std::string> files;
  1278. ASSERT_OK(env_->GetChildren(dbname_, &files));
  1279. int num_sst_files = 0;
  1280. for (auto& f : files) {
  1281. uint64_t number;
  1282. FileType type;
  1283. if (ParseFileName(f, &number, &type) && type == kTableFile) {
  1284. num_sst_files++;
  1285. }
  1286. }
  1287. ASSERT_EQ(1, num_sst_files);
  1288. }
  1289. #if !defined(ROCKSDB_VALGRIND_RUN) || defined(ROCKSDB_FULL_VALGRIND_RUN)
  1290. TEST_F(ExternalSSTFileTest, CompactDuringAddFileRandom) {
  1291. env_->skip_fsync_ = true;
  1292. Options options = CurrentOptions();
  1293. options.disable_auto_compactions = false;
  1294. options.level0_file_num_compaction_trigger = 2;
  1295. options.num_levels = 2;
  1296. DestroyAndReopen(options);
  1297. std::function<void()> bg_compact = [&]() {
  1298. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  1299. };
  1300. int range_id = 0;
  1301. std::vector<int> file_keys;
  1302. std::function<void()> bg_addfile = [&]() {
  1303. ASSERT_OK(GenerateAndAddExternalFile(options, file_keys, range_id,
  1304. true /* allow_global_seqno */));
  1305. };
  1306. const int num_of_ranges = 1000;
  1307. std::vector<port::Thread> threads;
  1308. while (range_id < num_of_ranges) {
  1309. int range_start = range_id * 10;
  1310. int range_end = range_start + 10;
  1311. file_keys.clear();
  1312. for (int k = range_start + 1; k < range_end; k++) {
  1313. file_keys.push_back(k);
  1314. }
  1315. ASSERT_OK(Put(Key(range_start), Key(range_start)));
  1316. ASSERT_OK(Put(Key(range_end), Key(range_end)));
  1317. ASSERT_OK(Flush());
  1318. if (range_id % 10 == 0) {
  1319. threads.emplace_back(bg_compact);
  1320. }
  1321. threads.emplace_back(bg_addfile);
  1322. for (auto& t : threads) {
  1323. t.join();
  1324. }
  1325. threads.clear();
  1326. range_id++;
  1327. }
  1328. for (int rid = 0; rid < num_of_ranges; rid++) {
  1329. int range_start = rid * 10;
  1330. int range_end = range_start + 10;
  1331. ASSERT_EQ(Get(Key(range_start)), Key(range_start)) << rid;
  1332. ASSERT_EQ(Get(Key(range_end)), Key(range_end)) << rid;
  1333. for (int k = range_start + 1; k < range_end; k++) {
  1334. std::string v = Key(k) + std::to_string(rid);
  1335. ASSERT_EQ(Get(Key(k)), v) << rid;
  1336. }
  1337. }
  1338. }
  1339. #endif // !defined(ROCKSDB_VALGRIND_RUN) || defined(ROCKSDB_FULL_VALGRIND_RUN)
  1340. TEST_F(ExternalSSTFileTest, PickedLevelDynamic) {
  1341. env_->skip_fsync_ = true;
  1342. Options options = CurrentOptions();
  1343. options.disable_auto_compactions = false;
  1344. options.level0_file_num_compaction_trigger = 4;
  1345. options.level_compaction_dynamic_level_bytes = true;
  1346. options.num_levels = 4;
  1347. DestroyAndReopen(options);
  1348. std::map<std::string, std::string> true_data;
  1349. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency({
  1350. {"ExternalSSTFileTest::PickedLevelDynamic:0",
  1351. "BackgroundCallCompaction:0"},
  1352. {"DBImpl::BackgroundCompaction:Start",
  1353. "ExternalSSTFileTest::PickedLevelDynamic:1"},
  1354. {"ExternalSSTFileTest::PickedLevelDynamic:2",
  1355. "DBImpl::BackgroundCompaction:NonTrivial:AfterRun"},
  1356. });
  1357. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  1358. // Flush 4 files containing the same keys
  1359. for (int i = 0; i < 4; i++) {
  1360. for (int k = 20; k <= 30; k++) {
  1361. ASSERT_OK(Put(Key(k), Key(k) + "put"));
  1362. true_data[Key(k)] = Key(k) + "put";
  1363. }
  1364. for (int k = 50; k <= 60; k++) {
  1365. ASSERT_OK(Put(Key(k), Key(k) + "put"));
  1366. true_data[Key(k)] = Key(k) + "put";
  1367. }
  1368. ASSERT_OK(Flush());
  1369. }
  1370. // Wait for BackgroundCompaction() to be called
  1371. TEST_SYNC_POINT("ExternalSSTFileTest::PickedLevelDynamic:0");
  1372. TEST_SYNC_POINT("ExternalSSTFileTest::PickedLevelDynamic:1");
  1373. // This file overlaps with the output of the compaction (going to L3)
  1374. // so the file will be added to L0 since L3 is the base level
  1375. ASSERT_OK(GenerateAndAddExternalFile(options, {31, 32, 33, 34}, -1,
  1376. true /* allow_global_seqno */, false,
  1377. true, false, false, &true_data));
  1378. EXPECT_EQ(FilesPerLevel(), "5");
  1379. // This file does not overlap with the current running compactiong
  1380. ASSERT_OK(GenerateAndAddExternalFile(options, {9000, 9001}, -1, false, false,
  1381. true, false, false, &true_data));
  1382. EXPECT_EQ(FilesPerLevel(), "5,0,0,1");
  1383. // Hold compaction from finishing
  1384. TEST_SYNC_POINT("ExternalSSTFileTest::PickedLevelDynamic:2");
  1385. // Output of the compaction will go to L3
  1386. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  1387. EXPECT_EQ(FilesPerLevel(), "1,0,0,2");
  1388. Close();
  1389. options.disable_auto_compactions = true;
  1390. Reopen(options);
  1391. ASSERT_OK(GenerateAndAddExternalFile(options, {1, 15, 19}, -1, false, false,
  1392. true, false, false, &true_data));
  1393. ASSERT_EQ(FilesPerLevel(), "1,0,0,3");
  1394. ASSERT_OK(GenerateAndAddExternalFile(options, {1000, 1001, 1002}, -1, false,
  1395. false, true, false, false, &true_data));
  1396. ASSERT_EQ(FilesPerLevel(), "1,0,0,4");
  1397. ASSERT_OK(GenerateAndAddExternalFile(options, {500, 600, 700}, -1, false,
  1398. false, true, false, false, &true_data));
  1399. ASSERT_EQ(FilesPerLevel(), "1,0,0,5");
  1400. // File 5 overlaps with file 2 (L3 / base level)
  1401. ASSERT_OK(GenerateAndAddExternalFile(options, {2, 10}, -1, false, false, true,
  1402. false, false, &true_data));
  1403. ASSERT_EQ(FilesPerLevel(), "2,0,0,5");
  1404. // File 6 overlaps with file 2 (L3 / base level) and file 5 (L0)
  1405. ASSERT_OK(GenerateAndAddExternalFile(options, {3, 9}, -1, false, false, true,
  1406. false, false, &true_data));
  1407. ASSERT_EQ(FilesPerLevel(), "3,0,0,5");
  1408. // Verify data in files
  1409. size_t kcnt = 0;
  1410. VerifyDBFromMap(true_data, &kcnt, false);
  1411. // Write range [5 => 10] to L0
  1412. for (int i = 5; i <= 10; i++) {
  1413. std::string k = Key(i);
  1414. std::string v = k + "put";
  1415. ASSERT_OK(Put(k, v));
  1416. true_data[k] = v;
  1417. }
  1418. ASSERT_OK(Flush());
  1419. ASSERT_EQ(FilesPerLevel(), "4,0,0,5");
  1420. // File 7 overlaps with file 4 (L3)
  1421. ASSERT_OK(GenerateAndAddExternalFile(options, {650, 651, 652}, -1, false,
  1422. false, true, false, false, &true_data));
  1423. ASSERT_EQ(FilesPerLevel(), "5,0,0,5");
  1424. VerifyDBFromMap(true_data, &kcnt, false);
  1425. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  1426. }
  1427. TEST_F(ExternalSSTFileTest, AddExternalSstFileWithCustomCompartor) {
  1428. Options options = CurrentOptions();
  1429. options.comparator = ReverseBytewiseComparator();
  1430. DestroyAndReopen(options);
  1431. SstFileWriter sst_file_writer(EnvOptions(), options);
  1432. // Generate files with these key ranges
  1433. // {14 -> 0}
  1434. // {24 -> 10}
  1435. // {34 -> 20}
  1436. // {44 -> 30}
  1437. // ..
  1438. std::vector<std::string> generated_files;
  1439. for (int i = 0; i < 10; i++) {
  1440. std::string file_name = sst_files_dir_ + env_->GenerateUniqueId();
  1441. ASSERT_OK(sst_file_writer.Open(file_name));
  1442. int range_end = i * 10;
  1443. int range_start = range_end + 15;
  1444. for (int k = (range_start - 1); k >= range_end; k--) {
  1445. ASSERT_OK(sst_file_writer.Put(Key(k), Key(k)));
  1446. }
  1447. ExternalSstFileInfo file_info;
  1448. ASSERT_OK(sst_file_writer.Finish(&file_info));
  1449. generated_files.push_back(file_name);
  1450. }
  1451. std::vector<std::string> in_files;
  1452. // These 2nd and 3rd files overlap with each other
  1453. in_files = {generated_files[0], generated_files[4], generated_files[5],
  1454. generated_files[7]};
  1455. ASSERT_NOK(DeprecatedAddFile(in_files));
  1456. // These 2 files don't overlap with each other
  1457. in_files = {generated_files[0], generated_files[2]};
  1458. ASSERT_OK(DeprecatedAddFile(in_files));
  1459. // These 2 files don't overlap with each other but overlap with keys in DB
  1460. in_files = {generated_files[3], generated_files[7]};
  1461. ASSERT_NOK(DeprecatedAddFile(in_files));
  1462. // Files don't overlap and don't overlap with DB key range
  1463. in_files = {generated_files[4], generated_files[6], generated_files[8]};
  1464. ASSERT_OK(DeprecatedAddFile(in_files));
  1465. for (int i = 0; i < 100; i++) {
  1466. if (i % 20 <= 14) {
  1467. ASSERT_EQ(Get(Key(i)), Key(i));
  1468. } else {
  1469. ASSERT_EQ(Get(Key(i)), "NOT_FOUND");
  1470. }
  1471. }
  1472. }
  1473. TEST_F(ExternalSSTFileTest, AddFileTrivialMoveBug) {
  1474. Options options = CurrentOptions();
  1475. options.num_levels = 3;
  1476. options.IncreaseParallelism(20);
  1477. DestroyAndReopen(options);
  1478. ASSERT_OK(GenerateAndAddExternalFile(options, {1, 4}, 1)); // L3
  1479. ASSERT_OK(GenerateAndAddExternalFile(options, {2, 3}, 2)); // L2
  1480. ASSERT_OK(GenerateAndAddExternalFile(options, {10, 14}, 3)); // L3
  1481. ASSERT_OK(GenerateAndAddExternalFile(options, {12, 13}, 4)); // L2
  1482. ASSERT_OK(GenerateAndAddExternalFile(options, {20, 24}, 5)); // L3
  1483. ASSERT_OK(GenerateAndAddExternalFile(options, {22, 23}, 6)); // L2
  1484. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1485. "CompactionJob::Run():Start", [&](void* /*arg*/) {
  1486. // Fit in L3 but will overlap with the compaction output so will be
  1487. // added to L2. Prior to the fix, a compaction will then trivially move
  1488. // this file to L3 and break LSM consistency
  1489. static std::atomic<bool> called = {false};
  1490. if (!called) {
  1491. called = true;
  1492. ASSERT_OK(dbfull()->SetOptions({{"max_bytes_for_level_base", "1"}}));
  1493. ASSERT_OK(GenerateAndAddExternalFile(options, {15, 16}, 7,
  1494. true /* allow_global_seqno */));
  1495. }
  1496. });
  1497. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  1498. CompactRangeOptions cro;
  1499. cro.exclusive_manual_compaction = false;
  1500. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  1501. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  1502. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  1503. }
  1504. TEST_F(ExternalSSTFileTest, CompactAddedFiles) {
  1505. Options options = CurrentOptions();
  1506. options.num_levels = 3;
  1507. DestroyAndReopen(options);
  1508. ASSERT_OK(GenerateAndAddExternalFile(options, {1, 10}, 1)); // L3
  1509. ASSERT_OK(GenerateAndAddExternalFile(options, {2, 9}, 2)); // L2
  1510. ASSERT_OK(GenerateAndAddExternalFile(options, {3, 8}, 3)); // L1
  1511. ASSERT_OK(GenerateAndAddExternalFile(options, {4, 7}, 4)); // L0
  1512. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  1513. }
  1514. TEST_F(ExternalSSTFileTest, SstFileWriterNonSharedKeys) {
  1515. Options options = CurrentOptions();
  1516. DestroyAndReopen(options);
  1517. std::string file_path = sst_files_dir_ + "/not_shared";
  1518. SstFileWriter sst_file_writer(EnvOptions(), options);
  1519. std::string suffix(100, 'X');
  1520. ASSERT_OK(sst_file_writer.Open(file_path));
  1521. ASSERT_OK(sst_file_writer.Put("A" + suffix, "VAL"));
  1522. ASSERT_OK(sst_file_writer.Put("BB" + suffix, "VAL"));
  1523. ASSERT_OK(sst_file_writer.Put("CC" + suffix, "VAL"));
  1524. ASSERT_OK(sst_file_writer.Put("CXD" + suffix, "VAL"));
  1525. ASSERT_OK(sst_file_writer.Put("CZZZ" + suffix, "VAL"));
  1526. ASSERT_OK(sst_file_writer.Put("ZAAAX" + suffix, "VAL"));
  1527. ASSERT_OK(sst_file_writer.Finish());
  1528. ASSERT_OK(DeprecatedAddFile({file_path}));
  1529. }
  1530. TEST_F(ExternalSSTFileTest, WithUnorderedWrite) {
  1531. SyncPoint::GetInstance()->DisableProcessing();
  1532. SyncPoint::GetInstance()->LoadDependency(
  1533. {{"DBImpl::WriteImpl:UnorderedWriteAfterWriteWAL",
  1534. "ExternalSSTFileTest::WithUnorderedWrite:WaitWriteWAL"},
  1535. {"DBImpl::WaitForPendingWrites:BeforeBlock",
  1536. "DBImpl::WriteImpl:BeforeUnorderedWriteMemtable"}});
  1537. SyncPoint::GetInstance()->SetCallBack(
  1538. "DBImpl::IngestExternalFile:NeedFlush",
  1539. [&](void* need_flush) { ASSERT_TRUE(*static_cast<bool*>(need_flush)); });
  1540. Options options = CurrentOptions();
  1541. options.unordered_write = true;
  1542. DestroyAndReopen(options);
  1543. ASSERT_OK(Put("foo", "v1"));
  1544. SyncPoint::GetInstance()->EnableProcessing();
  1545. port::Thread writer([&]() { ASSERT_OK(Put("bar", "v2")); });
  1546. TEST_SYNC_POINT("ExternalSSTFileTest::WithUnorderedWrite:WaitWriteWAL");
  1547. ASSERT_OK(GenerateAndAddExternalFile(options, {{"bar", "v3"}}, -1,
  1548. true /* allow_global_seqno */));
  1549. ASSERT_EQ(Get("bar"), "v3");
  1550. writer.join();
  1551. SyncPoint::GetInstance()->DisableProcessing();
  1552. SyncPoint::GetInstance()->ClearAllCallBacks();
  1553. }
  1554. #if !defined(ROCKSDB_VALGRIND_RUN) || defined(ROCKSDB_FULL_VALGRIND_RUN)
  1555. TEST_P(ExternalSSTFileTest, IngestFileWithGlobalSeqnoRandomized) {
  1556. env_->skip_fsync_ = true;
  1557. Options options = CurrentOptions();
  1558. options.IncreaseParallelism(20);
  1559. options.level0_slowdown_writes_trigger = 256;
  1560. options.level0_stop_writes_trigger = 256;
  1561. bool write_global_seqno = std::get<0>(GetParam());
  1562. bool verify_checksums_before_ingest = std::get<1>(GetParam());
  1563. for (int iter = 0; iter < 2; iter++) {
  1564. bool write_to_memtable = (iter == 0);
  1565. DestroyAndReopen(options);
  1566. Random rnd(301);
  1567. std::map<std::string, std::string> true_data;
  1568. for (int i = 0; i < 500; i++) {
  1569. std::vector<std::pair<std::string, std::string>> random_data;
  1570. for (int j = 0; j < 100; j++) {
  1571. std::string k = rnd.RandomString(rnd.Next() % 20);
  1572. std::string v = rnd.RandomString(rnd.Next() % 50);
  1573. random_data.emplace_back(k, v);
  1574. }
  1575. if (write_to_memtable && rnd.OneIn(4)) {
  1576. // 25% of writes go through memtable
  1577. for (auto& entry : random_data) {
  1578. ASSERT_OK(Put(entry.first, entry.second));
  1579. true_data[entry.first] = entry.second;
  1580. }
  1581. } else {
  1582. ASSERT_OK(GenerateAndAddExternalFile(
  1583. options, random_data, -1, true, write_global_seqno,
  1584. verify_checksums_before_ingest, false, true, &true_data));
  1585. }
  1586. }
  1587. size_t kcnt = 0;
  1588. VerifyDBFromMap(true_data, &kcnt, false);
  1589. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  1590. VerifyDBFromMap(true_data, &kcnt, false);
  1591. }
  1592. }
  1593. #endif // !defined(ROCKSDB_VALGRIND_RUN) || defined(ROCKSDB_FULL_VALGRIND_RUN)
  1594. TEST_P(ExternalSSTFileTest, IngestFileWithGlobalSeqnoAssignedLevel) {
  1595. Options options = CurrentOptions();
  1596. options.num_levels = 5;
  1597. options.disable_auto_compactions = true;
  1598. DestroyAndReopen(options);
  1599. std::vector<std::pair<std::string, std::string>> file_data;
  1600. std::map<std::string, std::string> true_data;
  1601. // Insert 100 -> 200 into the memtable
  1602. for (int i = 100; i <= 200; i++) {
  1603. ASSERT_OK(Put(Key(i), "memtable"));
  1604. true_data[Key(i)] = "memtable";
  1605. }
  1606. // Insert 0 -> 20 using AddFile
  1607. file_data.clear();
  1608. for (int i = 0; i <= 20; i++) {
  1609. file_data.emplace_back(Key(i), "L4");
  1610. }
  1611. bool write_global_seqno = std::get<0>(GetParam());
  1612. bool verify_checksums_before_ingest = std::get<1>(GetParam());
  1613. ASSERT_OK(GenerateAndAddExternalFile(
  1614. options, file_data, -1, true, write_global_seqno,
  1615. verify_checksums_before_ingest, false, false, &true_data));
  1616. // This file don't overlap with anything in the DB, will go to L4
  1617. ASSERT_EQ("0,0,0,0,1", FilesPerLevel());
  1618. // Insert 80 -> 130 using AddFile
  1619. file_data.clear();
  1620. for (int i = 80; i <= 130; i++) {
  1621. file_data.emplace_back(Key(i), "L0");
  1622. }
  1623. ASSERT_OK(GenerateAndAddExternalFile(
  1624. options, file_data, -1, true, write_global_seqno,
  1625. verify_checksums_before_ingest, false, false, &true_data));
  1626. // This file overlap with the memtable, so it will flush it and add
  1627. // it self to L0
  1628. ASSERT_EQ("2,0,0,0,1", FilesPerLevel());
  1629. // Insert 30 -> 50 using AddFile
  1630. file_data.clear();
  1631. for (int i = 30; i <= 50; i++) {
  1632. file_data.emplace_back(Key(i), "L4");
  1633. }
  1634. ASSERT_OK(GenerateAndAddExternalFile(
  1635. options, file_data, -1, true, write_global_seqno,
  1636. verify_checksums_before_ingest, false, false, &true_data));
  1637. // This file don't overlap with anything in the DB and fit in L4 as well
  1638. ASSERT_EQ("2,0,0,0,2", FilesPerLevel());
  1639. // Insert 10 -> 40 using AddFile
  1640. file_data.clear();
  1641. for (int i = 10; i <= 40; i++) {
  1642. file_data.emplace_back(Key(i), "L3");
  1643. }
  1644. ASSERT_OK(GenerateAndAddExternalFile(
  1645. options, file_data, -1, true, write_global_seqno,
  1646. verify_checksums_before_ingest, false, false, &true_data));
  1647. // This file overlap with files in L4, we will ingest it in L3
  1648. ASSERT_EQ("2,0,0,1,2", FilesPerLevel());
  1649. size_t kcnt = 0;
  1650. VerifyDBFromMap(true_data, &kcnt, false);
  1651. }
  1652. TEST_P(ExternalSSTFileTest, IngestFileWithGlobalSeqnoAssignedUniversal) {
  1653. bool write_global_seqno = std::get<0>(GetParam());
  1654. bool verify_checksums_before_ingest = std::get<1>(GetParam());
  1655. Options options = CurrentOptions();
  1656. options.num_levels = 5;
  1657. options.compaction_style = kCompactionStyleUniversal;
  1658. options.disable_auto_compactions = true;
  1659. DestroyAndReopen(options);
  1660. std::vector<std::pair<std::string, std::string>> file_data;
  1661. std::map<std::string, std::string> true_data;
  1662. // Write 200 -> 250 into the bottommost level
  1663. for (int i = 200; i <= 250; i++) {
  1664. ASSERT_OK(Put(Key(i), "bottommost"));
  1665. true_data[Key(i)] = "bottommost";
  1666. }
  1667. CompactRangeOptions cro;
  1668. cro.bottommost_level_compaction = BottommostLevelCompaction::kForce;
  1669. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  1670. ASSERT_EQ("0,0,0,0,1", FilesPerLevel());
  1671. // Take a snapshot to enforce global sequence number.
  1672. const Snapshot* snap = db_->GetSnapshot();
  1673. // Insert 100 -> 200 into the memtable
  1674. for (int i = 100; i <= 200; i++) {
  1675. ASSERT_OK(Put(Key(i), "memtable"));
  1676. true_data[Key(i)] = "memtable";
  1677. }
  1678. // Insert 0 -> 20 using AddFile
  1679. file_data.clear();
  1680. for (int i = 0; i <= 20; i++) {
  1681. file_data.emplace_back(Key(i), "L4");
  1682. }
  1683. ASSERT_OK(GenerateAndAddExternalFile(
  1684. options, file_data, -1, true, write_global_seqno,
  1685. verify_checksums_before_ingest, false, false, &true_data));
  1686. // This file don't overlap with anything in the DB, will go to L4
  1687. ASSERT_EQ("0,0,0,0,2", FilesPerLevel());
  1688. // Insert 80 -> 130 using AddFile
  1689. file_data.clear();
  1690. for (int i = 80; i <= 130; i++) {
  1691. file_data.emplace_back(Key(i), "L0");
  1692. }
  1693. ASSERT_OK(GenerateAndAddExternalFile(
  1694. options, file_data, -1, true, write_global_seqno,
  1695. verify_checksums_before_ingest, false, false, &true_data));
  1696. // This file overlap with the memtable, so it will flush it and add
  1697. // it self to L0
  1698. ASSERT_EQ("2,0,0,0,2", FilesPerLevel());
  1699. // Insert 30 -> 50 using AddFile
  1700. file_data.clear();
  1701. for (int i = 30; i <= 50; i++) {
  1702. file_data.emplace_back(Key(i), "L4");
  1703. }
  1704. ASSERT_OK(GenerateAndAddExternalFile(
  1705. options, file_data, -1, true, write_global_seqno,
  1706. verify_checksums_before_ingest, false, false, &true_data));
  1707. // This file don't overlap with anything in the DB and fit in L4 as well
  1708. ASSERT_EQ("2,0,0,0,3", FilesPerLevel());
  1709. // Insert 10 -> 40 using AddFile
  1710. file_data.clear();
  1711. for (int i = 10; i <= 40; i++) {
  1712. file_data.emplace_back(Key(i), "L3");
  1713. }
  1714. ASSERT_OK(GenerateAndAddExternalFile(
  1715. options, file_data, -1, true, write_global_seqno,
  1716. verify_checksums_before_ingest, false, false, &true_data));
  1717. // This file overlap with files in L4, we will ingest it into the closest
  1718. // non-overlapping level, in this case, it's L3.
  1719. ASSERT_EQ("2,0,0,1,3", FilesPerLevel());
  1720. size_t kcnt = 0;
  1721. VerifyDBFromMap(true_data, &kcnt, false);
  1722. db_->ReleaseSnapshot(snap);
  1723. }
  1724. TEST_P(ExternalSSTFileTest, IngestFileWithGlobalSeqnoMemtableFlush) {
  1725. Options options = CurrentOptions();
  1726. DestroyAndReopen(options);
  1727. uint64_t entries_in_memtable;
  1728. std::map<std::string, std::string> true_data;
  1729. for (int k : {10, 20, 40, 80}) {
  1730. ASSERT_OK(Put(Key(k), "memtable"));
  1731. true_data[Key(k)] = "memtable";
  1732. }
  1733. ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumEntriesActiveMemTable,
  1734. &entries_in_memtable));
  1735. ASSERT_GE(entries_in_memtable, 1);
  1736. bool write_global_seqno = std::get<0>(GetParam());
  1737. bool verify_checksums_before_ingest = std::get<1>(GetParam());
  1738. // No need for flush
  1739. ASSERT_OK(GenerateAndAddExternalFile(
  1740. options, {90, 100, 110}, -1, true, write_global_seqno,
  1741. verify_checksums_before_ingest, false, false, &true_data));
  1742. ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumEntriesActiveMemTable,
  1743. &entries_in_memtable));
  1744. ASSERT_GE(entries_in_memtable, 1);
  1745. // This file will flush the memtable
  1746. ASSERT_OK(GenerateAndAddExternalFile(
  1747. options, {19, 20, 21}, -1, true, write_global_seqno,
  1748. verify_checksums_before_ingest, false, false, &true_data));
  1749. ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumEntriesActiveMemTable,
  1750. &entries_in_memtable));
  1751. ASSERT_EQ(entries_in_memtable, 0);
  1752. for (int k : {200, 201, 205, 206}) {
  1753. ASSERT_OK(Put(Key(k), "memtable"));
  1754. true_data[Key(k)] = "memtable";
  1755. }
  1756. ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumEntriesActiveMemTable,
  1757. &entries_in_memtable));
  1758. ASSERT_GE(entries_in_memtable, 1);
  1759. // No need for flush, this file keys fit between the memtable keys
  1760. ASSERT_OK(GenerateAndAddExternalFile(
  1761. options, {202, 203, 204}, -1, true, write_global_seqno,
  1762. verify_checksums_before_ingest, false, false, &true_data));
  1763. ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumEntriesActiveMemTable,
  1764. &entries_in_memtable));
  1765. ASSERT_GE(entries_in_memtable, 1);
  1766. // This file will flush the memtable
  1767. ASSERT_OK(GenerateAndAddExternalFile(
  1768. options, {206, 207}, -1, true, write_global_seqno,
  1769. verify_checksums_before_ingest, false, false, &true_data));
  1770. ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumEntriesActiveMemTable,
  1771. &entries_in_memtable));
  1772. ASSERT_EQ(entries_in_memtable, 0);
  1773. size_t kcnt = 0;
  1774. VerifyDBFromMap(true_data, &kcnt, false);
  1775. }
  1776. TEST_P(ExternalSSTFileTest, L0SortingIssue) {
  1777. Options options = CurrentOptions();
  1778. options.num_levels = 2;
  1779. DestroyAndReopen(options);
  1780. std::map<std::string, std::string> true_data;
  1781. ASSERT_OK(Put(Key(1), "memtable"));
  1782. ASSERT_OK(Put(Key(10), "memtable"));
  1783. bool write_global_seqno = std::get<0>(GetParam());
  1784. bool verify_checksums_before_ingest = std::get<1>(GetParam());
  1785. // No Flush needed, No global seqno needed, Ingest in L1
  1786. ASSERT_OK(
  1787. GenerateAndAddExternalFile(options, {7, 8}, -1, true, write_global_seqno,
  1788. verify_checksums_before_ingest, false, false));
  1789. // No Flush needed, but need a global seqno, Ingest in L0
  1790. ASSERT_OK(
  1791. GenerateAndAddExternalFile(options, {7, 8}, -1, true, write_global_seqno,
  1792. verify_checksums_before_ingest, false, false));
  1793. printf("%s\n", FilesPerLevel().c_str());
  1794. // Overwrite what we added using external files
  1795. ASSERT_OK(Put(Key(7), "memtable"));
  1796. ASSERT_OK(Put(Key(8), "memtable"));
  1797. // Read values from memtable
  1798. ASSERT_EQ(Get(Key(7)), "memtable");
  1799. ASSERT_EQ(Get(Key(8)), "memtable");
  1800. // Flush and read from L0
  1801. ASSERT_OK(Flush());
  1802. printf("%s\n", FilesPerLevel().c_str());
  1803. ASSERT_EQ(Get(Key(7)), "memtable");
  1804. ASSERT_EQ(Get(Key(8)), "memtable");
  1805. }
  1806. TEST_F(ExternalSSTFileTest, CompactionDeadlock) {
  1807. Options options = CurrentOptions();
  1808. options.num_levels = 2;
  1809. options.level0_file_num_compaction_trigger = 4;
  1810. options.level0_slowdown_writes_trigger = 4;
  1811. options.level0_stop_writes_trigger = 4;
  1812. DestroyAndReopen(options);
  1813. // atomic conter of currently running bg threads
  1814. std::atomic<int> running_threads(0);
  1815. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency({
  1816. {"DBImpl::DelayWrite:Wait", "ExternalSSTFileTest::DeadLock:0"},
  1817. {"ExternalSSTFileTest::DeadLock:1", "DBImpl::AddFile:Start"},
  1818. {"DBImpl::AddFile:MutexLock", "ExternalSSTFileTest::DeadLock:2"},
  1819. {"ExternalSSTFileTest::DeadLock:3", "BackgroundCallCompaction:0"},
  1820. });
  1821. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  1822. // Start ingesting and extrnal file in the background
  1823. ROCKSDB_NAMESPACE::port::Thread bg_ingest_file([&]() {
  1824. running_threads += 1;
  1825. ASSERT_OK(GenerateAndAddExternalFile(options, {5, 6}));
  1826. running_threads -= 1;
  1827. });
  1828. ASSERT_OK(Put(Key(1), "memtable"));
  1829. ASSERT_OK(Flush());
  1830. ASSERT_OK(Put(Key(2), "memtable"));
  1831. ASSERT_OK(Flush());
  1832. ASSERT_OK(Put(Key(3), "memtable"));
  1833. ASSERT_OK(Flush());
  1834. ASSERT_OK(Put(Key(4), "memtable"));
  1835. ASSERT_OK(Flush());
  1836. // This thread will try to insert into the memtable but since we have 4 L0
  1837. // files this thread will be blocked and hold the writer thread
  1838. ROCKSDB_NAMESPACE::port::Thread bg_block_put([&]() {
  1839. running_threads += 1;
  1840. ASSERT_OK(Put(Key(10), "memtable"));
  1841. running_threads -= 1;
  1842. });
  1843. // Make sure DelayWrite is called first
  1844. TEST_SYNC_POINT("ExternalSSTFileTest::DeadLock:0");
  1845. // `DBImpl::AddFile:Start` will wait until we be here
  1846. TEST_SYNC_POINT("ExternalSSTFileTest::DeadLock:1");
  1847. // Wait for IngestExternalFile() to start and aquire mutex
  1848. TEST_SYNC_POINT("ExternalSSTFileTest::DeadLock:2");
  1849. // Now let compaction start
  1850. TEST_SYNC_POINT("ExternalSSTFileTest::DeadLock:3");
  1851. // Wait for max 5 seconds, if we did not finish all bg threads
  1852. // then we hit the deadlock bug
  1853. for (int i = 0; i < 10; i++) {
  1854. if (running_threads.load() == 0) {
  1855. break;
  1856. }
  1857. // Make sure we do a "real sleep", not a mock one.
  1858. SystemClock::Default()->SleepForMicroseconds(500000);
  1859. }
  1860. ASSERT_EQ(running_threads.load(), 0);
  1861. bg_ingest_file.join();
  1862. bg_block_put.join();
  1863. }
  1864. TEST_F(ExternalSSTFileTest, DirtyExit) {
  1865. Options options = CurrentOptions();
  1866. DestroyAndReopen(options);
  1867. std::string file_path = sst_files_dir_ + "/dirty_exit";
  1868. std::unique_ptr<SstFileWriter> sst_file_writer;
  1869. // Destruct SstFileWriter without calling Finish()
  1870. sst_file_writer.reset(new SstFileWriter(EnvOptions(), options));
  1871. ASSERT_OK(sst_file_writer->Open(file_path));
  1872. sst_file_writer.reset();
  1873. // Destruct SstFileWriter with a failing Finish
  1874. sst_file_writer.reset(new SstFileWriter(EnvOptions(), options));
  1875. ASSERT_OK(sst_file_writer->Open(file_path));
  1876. ASSERT_NOK(sst_file_writer->Finish());
  1877. }
  1878. TEST_F(ExternalSSTFileTest, FileWithCFInfo) {
  1879. Options options = CurrentOptions();
  1880. CreateAndReopenWithCF({"koko", "toto"}, options);
  1881. SstFileWriter sfw_default(EnvOptions(), options, handles_[0]);
  1882. SstFileWriter sfw_cf1(EnvOptions(), options, handles_[1]);
  1883. SstFileWriter sfw_cf2(EnvOptions(), options, handles_[2]);
  1884. SstFileWriter sfw_unknown(EnvOptions(), options);
  1885. // default_cf.sst
  1886. const std::string cf_default_sst = sst_files_dir_ + "/default_cf.sst";
  1887. ASSERT_OK(sfw_default.Open(cf_default_sst));
  1888. ASSERT_OK(sfw_default.Put("K1", "V1"));
  1889. ASSERT_OK(sfw_default.Put("K2", "V2"));
  1890. ASSERT_OK(sfw_default.Finish());
  1891. // cf1.sst
  1892. const std::string cf1_sst = sst_files_dir_ + "/cf1.sst";
  1893. ASSERT_OK(sfw_cf1.Open(cf1_sst));
  1894. ASSERT_OK(sfw_cf1.Put("K3", "V1"));
  1895. ASSERT_OK(sfw_cf1.Put("K4", "V2"));
  1896. ASSERT_OK(sfw_cf1.Finish());
  1897. // cf_unknown.sst
  1898. const std::string unknown_sst = sst_files_dir_ + "/cf_unknown.sst";
  1899. ASSERT_OK(sfw_unknown.Open(unknown_sst));
  1900. ASSERT_OK(sfw_unknown.Put("K5", "V1"));
  1901. ASSERT_OK(sfw_unknown.Put("K6", "V2"));
  1902. ASSERT_OK(sfw_unknown.Finish());
  1903. IngestExternalFileOptions ifo;
  1904. // SST CF don't match
  1905. ASSERT_NOK(db_->IngestExternalFile(handles_[0], {cf1_sst}, ifo));
  1906. // SST CF don't match
  1907. ASSERT_NOK(db_->IngestExternalFile(handles_[2], {cf1_sst}, ifo));
  1908. // SST CF match
  1909. ASSERT_OK(db_->IngestExternalFile(handles_[1], {cf1_sst}, ifo));
  1910. // SST CF don't match
  1911. ASSERT_NOK(db_->IngestExternalFile(handles_[1], {cf_default_sst}, ifo));
  1912. // SST CF don't match
  1913. ASSERT_NOK(db_->IngestExternalFile(handles_[2], {cf_default_sst}, ifo));
  1914. // SST CF match
  1915. ASSERT_OK(db_->IngestExternalFile(handles_[0], {cf_default_sst}, ifo));
  1916. // SST CF unknown
  1917. ASSERT_OK(db_->IngestExternalFile(handles_[1], {unknown_sst}, ifo));
  1918. // SST CF unknown
  1919. ASSERT_OK(db_->IngestExternalFile(handles_[2], {unknown_sst}, ifo));
  1920. // SST CF unknown
  1921. ASSERT_OK(db_->IngestExternalFile(handles_[0], {unknown_sst}, ifo));
  1922. // Cannot ingest a file into a dropped CF
  1923. ASSERT_OK(db_->DropColumnFamily(handles_[1]));
  1924. ASSERT_NOK(db_->IngestExternalFile(handles_[1], {unknown_sst}, ifo));
  1925. // CF was not dropped, ok to Ingest
  1926. ASSERT_OK(db_->IngestExternalFile(handles_[2], {unknown_sst}, ifo));
  1927. }
  1928. /*
  1929. * Test and verify the functionality of ingestion_options.move_files and
  1930. * ingestion_options.failed_move_fall_back_to_copy
  1931. */
  1932. TEST_P(ExternSSTFileLinkFailFallbackTest, LinkFailFallBackExternalSst) {
  1933. const bool fail_link = std::get<0>(GetParam());
  1934. const bool failed_move_fall_back_to_copy = std::get<1>(GetParam());
  1935. fs_->set_fail_link(fail_link);
  1936. const EnvOptions env_options;
  1937. DestroyAndReopen(options_);
  1938. const int kNumKeys = 10000;
  1939. IngestExternalFileOptions ifo;
  1940. ifo.move_files = std::get<2>(GetParam());
  1941. ifo.link_files = !ifo.move_files;
  1942. ifo.failed_move_fall_back_to_copy = failed_move_fall_back_to_copy;
  1943. std::string file_path = sst_files_dir_ + "file1.sst";
  1944. // Create SstFileWriter for default column family
  1945. SstFileWriter sst_file_writer(env_options, options_);
  1946. ASSERT_OK(sst_file_writer.Open(file_path));
  1947. for (int i = 0; i < kNumKeys; i++) {
  1948. ASSERT_OK(sst_file_writer.Put(Key(i), Key(i) + "_value"));
  1949. }
  1950. ASSERT_OK(sst_file_writer.Finish());
  1951. uint64_t file_size = 0;
  1952. ASSERT_OK(env_->GetFileSize(file_path, &file_size));
  1953. bool copyfile = false;
  1954. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1955. "ExternalSstFileIngestionJob::Prepare:CopyFile",
  1956. [&](void* /* arg */) { copyfile = true; });
  1957. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  1958. const Status s = db_->IngestExternalFile({file_path}, ifo);
  1959. ColumnFamilyHandleImpl* cfh =
  1960. static_cast<ColumnFamilyHandleImpl*>(dbfull()->DefaultColumnFamily());
  1961. ColumnFamilyData* cfd = cfh->cfd();
  1962. const InternalStats* internal_stats_ptr = cfd->internal_stats();
  1963. const std::vector<InternalStats::CompactionStats>& comp_stats =
  1964. internal_stats_ptr->TEST_GetCompactionStats();
  1965. uint64_t bytes_copied = 0;
  1966. uint64_t bytes_moved = 0;
  1967. for (const auto& stats : comp_stats) {
  1968. bytes_copied += stats.bytes_written;
  1969. bytes_moved += stats.bytes_moved;
  1970. }
  1971. if (!fail_link) {
  1972. // Link operation succeeds. External SST should be moved.
  1973. ASSERT_OK(s);
  1974. ASSERT_EQ(0, bytes_copied);
  1975. ASSERT_EQ(file_size, bytes_moved);
  1976. ASSERT_FALSE(copyfile);
  1977. Status es = env_->FileExists(file_path);
  1978. if (ifo.move_files) {
  1979. ASSERT_TRUE(es.IsNotFound());
  1980. } else {
  1981. ASSERT_OK(es);
  1982. }
  1983. } else {
  1984. // Link operation fails.
  1985. ASSERT_EQ(0, bytes_moved);
  1986. if (failed_move_fall_back_to_copy) {
  1987. ASSERT_OK(s);
  1988. // Copy file is true since a failed link falls back to copy file.
  1989. ASSERT_TRUE(copyfile);
  1990. ASSERT_EQ(file_size, bytes_copied);
  1991. } else {
  1992. ASSERT_TRUE(s.IsNotSupported());
  1993. // Copy file is false since a failed link does not fall back to copy file.
  1994. ASSERT_FALSE(copyfile);
  1995. ASSERT_EQ(0, bytes_copied);
  1996. }
  1997. }
  1998. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  1999. }
  2000. INSTANTIATE_TEST_CASE_P(ExternSSTFileLinkFailFallbackTest,
  2001. ExternSSTFileLinkFailFallbackTest,
  2002. testing::Combine(testing::Bool(), testing::Bool(),
  2003. testing::Bool()));
  2004. class TestIngestExternalFileListener : public EventListener {
  2005. public:
  2006. void OnExternalFileIngested(DB* /*db*/,
  2007. const ExternalFileIngestionInfo& info) override {
  2008. ingested_files.push_back(info);
  2009. }
  2010. std::vector<ExternalFileIngestionInfo> ingested_files;
  2011. };
  2012. TEST_P(ExternalSSTFileTest, IngestionListener) {
  2013. Options options = CurrentOptions();
  2014. TestIngestExternalFileListener* listener =
  2015. new TestIngestExternalFileListener();
  2016. options.listeners.emplace_back(listener);
  2017. CreateAndReopenWithCF({"koko", "toto"}, options);
  2018. bool write_global_seqno = std::get<0>(GetParam());
  2019. bool verify_checksums_before_ingest = std::get<1>(GetParam());
  2020. // Ingest into default cf
  2021. ASSERT_OK(GenerateAndAddExternalFile(
  2022. options, {1, 2}, -1, true, write_global_seqno,
  2023. verify_checksums_before_ingest, false, true, nullptr, handles_[0]));
  2024. ASSERT_EQ(listener->ingested_files.size(), 1);
  2025. ASSERT_EQ(listener->ingested_files.back().cf_name, "default");
  2026. ASSERT_EQ(listener->ingested_files.back().global_seqno, 0);
  2027. ASSERT_EQ(listener->ingested_files.back().table_properties.column_family_id,
  2028. 0);
  2029. ASSERT_EQ(listener->ingested_files.back().table_properties.column_family_name,
  2030. "default");
  2031. // Ingest into cf1
  2032. ASSERT_OK(GenerateAndAddExternalFile(
  2033. options, {1, 2}, -1, true, write_global_seqno,
  2034. verify_checksums_before_ingest, false, true, nullptr, handles_[1]));
  2035. ASSERT_EQ(listener->ingested_files.size(), 2);
  2036. ASSERT_EQ(listener->ingested_files.back().cf_name, "koko");
  2037. ASSERT_EQ(listener->ingested_files.back().global_seqno, 0);
  2038. ASSERT_EQ(listener->ingested_files.back().table_properties.column_family_id,
  2039. 1);
  2040. ASSERT_EQ(listener->ingested_files.back().table_properties.column_family_name,
  2041. "koko");
  2042. // Ingest into cf2
  2043. ASSERT_OK(GenerateAndAddExternalFile(
  2044. options, {1, 2}, -1, true, write_global_seqno,
  2045. verify_checksums_before_ingest, false, true, nullptr, handles_[2]));
  2046. ASSERT_EQ(listener->ingested_files.size(), 3);
  2047. ASSERT_EQ(listener->ingested_files.back().cf_name, "toto");
  2048. ASSERT_EQ(listener->ingested_files.back().global_seqno, 0);
  2049. ASSERT_EQ(listener->ingested_files.back().table_properties.column_family_id,
  2050. 2);
  2051. ASSERT_EQ(listener->ingested_files.back().table_properties.column_family_name,
  2052. "toto");
  2053. }
  2054. TEST_F(ExternalSSTFileTest, SnapshotInconsistencyBug) {
  2055. Options options = CurrentOptions();
  2056. DestroyAndReopen(options);
  2057. const int kNumKeys = 10000;
  2058. // Insert keys using normal path and take a snapshot
  2059. for (int i = 0; i < kNumKeys; i++) {
  2060. ASSERT_OK(Put(Key(i), Key(i) + "_V1"));
  2061. }
  2062. const Snapshot* snap = db_->GetSnapshot();
  2063. // Overwrite all keys using IngestExternalFile
  2064. std::string sst_file_path = sst_files_dir_ + "file1.sst";
  2065. SstFileWriter sst_file_writer(EnvOptions(), options);
  2066. ASSERT_OK(sst_file_writer.Open(sst_file_path));
  2067. for (int i = 0; i < kNumKeys; i++) {
  2068. ASSERT_OK(sst_file_writer.Put(Key(i), Key(i) + "_V2"));
  2069. }
  2070. ASSERT_OK(sst_file_writer.Finish());
  2071. IngestExternalFileOptions ifo;
  2072. ifo.move_files = true;
  2073. ASSERT_OK(db_->IngestExternalFile({sst_file_path}, ifo));
  2074. for (int i = 0; i < kNumKeys; i++) {
  2075. ASSERT_EQ(Get(Key(i), snap), Key(i) + "_V1");
  2076. ASSERT_EQ(Get(Key(i)), Key(i) + "_V2");
  2077. }
  2078. db_->ReleaseSnapshot(snap);
  2079. }
  2080. TEST_P(ExternalSSTFileTest, IngestBehind) {
  2081. for (bool cf_option : {false, true}) {
  2082. SCOPED_TRACE("cf_option = " + std::to_string(cf_option));
  2083. Options options = CurrentOptions();
  2084. options.compaction_style = kCompactionStyleUniversal;
  2085. options.num_levels = 3;
  2086. options.disable_auto_compactions = false;
  2087. DestroyAndReopen(options);
  2088. std::vector<std::pair<std::string, std::string>> file_data;
  2089. std::map<std::string, std::string> true_data;
  2090. // Insert 100 -> 200 into the memtable
  2091. for (int i = 100; i <= 200; i++) {
  2092. ASSERT_OK(Put(Key(i), "memtable"));
  2093. }
  2094. // Insert 100 -> 200 using IngestExternalFile
  2095. file_data.clear();
  2096. for (int i = 0; i <= 20; i++) {
  2097. file_data.emplace_back(Key(i), "ingest_behind");
  2098. true_data[Key(i)] = "ingest_behind";
  2099. }
  2100. bool allow_global_seqno = true;
  2101. bool ingest_behind = true;
  2102. bool write_global_seqno = std::get<0>(GetParam());
  2103. bool verify_checksums_before_ingest = std::get<1>(GetParam());
  2104. // Can't ingest behind since allow_ingest_behind isn't set to true
  2105. ASSERT_NOK(GenerateAndAddExternalFile(
  2106. options, file_data, -1, allow_global_seqno, write_global_seqno,
  2107. verify_checksums_before_ingest, ingest_behind, false /*sort_data*/,
  2108. &true_data));
  2109. if (cf_option) {
  2110. options.cf_allow_ingest_behind = true;
  2111. } else {
  2112. options.allow_ingest_behind = true;
  2113. }
  2114. // check that we still can open the DB, as num_levels should be
  2115. // sanitized to 3
  2116. options.num_levels = 2;
  2117. DestroyAndReopen(options);
  2118. options.num_levels = 3;
  2119. DestroyAndReopen(options);
  2120. true_data.clear();
  2121. // Insert 100 -> 200 into the memtable
  2122. for (int i = 100; i <= 200; i++) {
  2123. ASSERT_OK(Put(Key(i), "memtable"));
  2124. true_data[Key(i)] = "memtable";
  2125. }
  2126. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  2127. // Universal picker should go at second from the bottom level
  2128. ASSERT_EQ("0,1", FilesPerLevel());
  2129. ASSERT_OK(GenerateAndAddExternalFile(
  2130. options, file_data, -1, allow_global_seqno, write_global_seqno,
  2131. verify_checksums_before_ingest, true /*ingest_behind*/,
  2132. false /*sort_data*/, &true_data));
  2133. ASSERT_EQ("0,1,1", FilesPerLevel());
  2134. // this time ingest should fail as the file doesn't fit to the bottom level
  2135. ASSERT_NOK(GenerateAndAddExternalFile(
  2136. options, file_data, -1, allow_global_seqno, write_global_seqno,
  2137. verify_checksums_before_ingest, true /*ingest_behind*/,
  2138. false /*sort_data*/, &true_data));
  2139. ASSERT_EQ("0,1,1", FilesPerLevel());
  2140. std::vector<std::vector<FileMetaData>> level_to_files;
  2141. dbfull()->TEST_GetFilesMetaData(db_->DefaultColumnFamily(),
  2142. &level_to_files);
  2143. uint64_t ingested_file_number = level_to_files[2][0].fd.GetNumber();
  2144. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  2145. // Last level should not be compacted
  2146. ASSERT_EQ("0,1,1", FilesPerLevel());
  2147. dbfull()->TEST_GetFilesMetaData(db_->DefaultColumnFamily(),
  2148. &level_to_files);
  2149. ASSERT_EQ(ingested_file_number, level_to_files[2][0].fd.GetNumber());
  2150. size_t kcnt = 0;
  2151. VerifyDBFromMap(true_data, &kcnt, false);
  2152. // Auto-compaction should not include the last level.
  2153. // Trigger compaction if size amplification exceeds 110%.
  2154. options.compaction_options_universal.max_size_amplification_percent = 110;
  2155. options.level0_file_num_compaction_trigger = 4;
  2156. ASSERT_OK(TryReopen(options));
  2157. Random rnd(301);
  2158. for (int i = 0; i < 4; ++i) {
  2159. for (int j = 0; j < 10; j++) {
  2160. true_data[Key(j)] = rnd.RandomString(1000);
  2161. ASSERT_OK(Put(Key(j), true_data[Key(j)]));
  2162. }
  2163. ASSERT_OK(Flush());
  2164. }
  2165. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  2166. dbfull()->TEST_GetFilesMetaData(db_->DefaultColumnFamily(),
  2167. &level_to_files);
  2168. ASSERT_EQ(1, level_to_files[2].size());
  2169. ASSERT_EQ(ingested_file_number, level_to_files[2][0].fd.GetNumber());
  2170. // Turning off the option allows DB to compact ingested files.
  2171. if (cf_option) {
  2172. // Test that another CF does not allow ingest behind
  2173. ColumnFamilyHandle* new_cfh;
  2174. Options new_cf_option;
  2175. ASSERT_OK(db_->CreateColumnFamily(new_cf_option, "new_cf", &new_cfh));
  2176. ASSERT_TRUE(GenerateAndAddExternalFile(
  2177. new_cf_option, file_data, -1, allow_global_seqno,
  2178. write_global_seqno, verify_checksums_before_ingest,
  2179. true /*ingest_behind*/, false /*sort_data*/, nullptr,
  2180. /*cfh=*/new_cfh)
  2181. .IsInvalidArgument());
  2182. ASSERT_OK(db_->DropColumnFamily(new_cfh));
  2183. ASSERT_OK(db_->DestroyColumnFamilyHandle(new_cfh));
  2184. options.cf_allow_ingest_behind = false;
  2185. } else {
  2186. options.allow_ingest_behind = false;
  2187. }
  2188. ASSERT_OK(TryReopen(options));
  2189. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  2190. dbfull()->TEST_GetFilesMetaData(db_->DefaultColumnFamily(),
  2191. &level_to_files);
  2192. ASSERT_EQ(1, level_to_files[2].size());
  2193. ASSERT_NE(ingested_file_number, level_to_files[2][0].fd.GetNumber());
  2194. VerifyDBFromMap(true_data, &kcnt, false);
  2195. }
  2196. }
  2197. TEST_F(ExternalSSTFileTest, SkipBloomFilter) {
  2198. Options options = CurrentOptions();
  2199. BlockBasedTableOptions table_options;
  2200. table_options.filter_policy.reset(NewBloomFilterPolicy(10));
  2201. table_options.cache_index_and_filter_blocks = true;
  2202. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2203. // Create external SST file and include bloom filters
  2204. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  2205. DestroyAndReopen(options);
  2206. {
  2207. std::string file_path = sst_files_dir_ + "sst_with_bloom.sst";
  2208. SstFileWriter sst_file_writer(EnvOptions(), options);
  2209. ASSERT_OK(sst_file_writer.Open(file_path));
  2210. ASSERT_OK(sst_file_writer.Put("Key1", "Value1"));
  2211. ASSERT_OK(sst_file_writer.Finish());
  2212. ASSERT_OK(
  2213. db_->IngestExternalFile({file_path}, IngestExternalFileOptions()));
  2214. ASSERT_EQ(Get("Key1"), "Value1");
  2215. ASSERT_GE(
  2216. options.statistics->getTickerCount(Tickers::BLOCK_CACHE_FILTER_ADD), 1);
  2217. }
  2218. // Create external SST file but skip bloom filters
  2219. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  2220. DestroyAndReopen(options);
  2221. {
  2222. std::string file_path = sst_files_dir_ + "sst_with_no_bloom.sst";
  2223. SstFileWriter sst_file_writer(EnvOptions(), options, nullptr, true,
  2224. Env::IOPriority::IO_TOTAL,
  2225. true /* skip_filters */);
  2226. ASSERT_OK(sst_file_writer.Open(file_path));
  2227. ASSERT_OK(sst_file_writer.Put("Key1", "Value1"));
  2228. ASSERT_OK(sst_file_writer.Finish());
  2229. ASSERT_OK(
  2230. db_->IngestExternalFile({file_path}, IngestExternalFileOptions()));
  2231. ASSERT_EQ(Get("Key1"), "Value1");
  2232. ASSERT_EQ(
  2233. options.statistics->getTickerCount(Tickers::BLOCK_CACHE_FILTER_ADD), 0);
  2234. }
  2235. }
  2236. TEST_F(ExternalSSTFileTest, IngestFileWrittenWithCompressionDictionary) {
  2237. if (!ZSTD_Supported()) {
  2238. return;
  2239. }
  2240. const int kNumEntries = 1 << 10;
  2241. const int kNumBytesPerEntry = 1 << 10;
  2242. Options options = CurrentOptions();
  2243. options.compression = kZSTD;
  2244. options.compression_opts.max_dict_bytes = 1 << 14; // 16KB
  2245. options.compression_opts.zstd_max_train_bytes = 1 << 18; // 256KB
  2246. DestroyAndReopen(options);
  2247. std::atomic<int> num_compression_dicts(0);
  2248. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  2249. "BlockBasedTableBuilder::WriteCompressionDictBlock:RawDict",
  2250. [&](void* /* arg */) { ++num_compression_dicts; });
  2251. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  2252. Random rnd(301);
  2253. std::vector<std::pair<std::string, std::string>> random_data;
  2254. for (int i = 0; i < kNumEntries; i++) {
  2255. std::string val = rnd.RandomString(kNumBytesPerEntry);
  2256. random_data.emplace_back(Key(i), std::move(val));
  2257. }
  2258. ASSERT_OK(GenerateAndAddExternalFile(options, std::move(random_data)));
  2259. ASSERT_EQ(1, num_compression_dicts);
  2260. }
  2261. class ExternalSSTBlockChecksumTest
  2262. : public ExternalSSTFileTestBase,
  2263. public testing::WithParamInterface<uint32_t> {};
  2264. INSTANTIATE_TEST_CASE_P(FormatVersions, ExternalSSTBlockChecksumTest,
  2265. testing::ValuesIn(test::kFooterFormatVersionsToTest));
  2266. // Very slow, not worth the cost to run regularly
  2267. TEST_P(ExternalSSTBlockChecksumTest, DISABLED_HugeBlockChecksum) {
  2268. BlockBasedTableOptions table_options;
  2269. table_options.format_version = GetParam();
  2270. for (auto t : GetSupportedChecksums()) {
  2271. table_options.checksum = t;
  2272. Options options = CurrentOptions();
  2273. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2274. SstFileWriter sst_file_writer(EnvOptions(), options);
  2275. // 2^32 - 1, will lead to data block with more than 2^32 bytes
  2276. size_t huge_size = std::numeric_limits<uint32_t>::max();
  2277. std::string f = sst_files_dir_ + "f.sst";
  2278. ASSERT_OK(sst_file_writer.Open(f));
  2279. {
  2280. Random64 r(123);
  2281. std::string huge(huge_size, 0);
  2282. for (size_t j = 0; j + 7 < huge_size; j += 8) {
  2283. EncodeFixed64(&huge[j], r.Next());
  2284. }
  2285. ASSERT_OK(sst_file_writer.Put("Huge", huge));
  2286. }
  2287. ExternalSstFileInfo f_info;
  2288. ASSERT_OK(sst_file_writer.Finish(&f_info));
  2289. ASSERT_GT(f_info.file_size, uint64_t{huge_size} + 10);
  2290. SstFileReader sst_file_reader(options);
  2291. ASSERT_OK(sst_file_reader.Open(f));
  2292. ASSERT_OK(sst_file_reader.VerifyChecksum());
  2293. }
  2294. }
  2295. TEST_P(ExternalSSTFileTest, IngestFilesIntoMultipleColumnFamilies_Success) {
  2296. std::unique_ptr<FaultInjectionTestEnv> fault_injection_env(
  2297. new FaultInjectionTestEnv(env_));
  2298. Options options = CurrentOptions();
  2299. options.env = fault_injection_env.get();
  2300. CreateAndReopenWithCF({"pikachu", "eevee"}, options);
  2301. // Exercise different situations in different column families: two are empty
  2302. // (so no new sequence number is needed), but at least one overlaps with the
  2303. // DB and needs to bump the sequence number.
  2304. ASSERT_OK(db_->Put(WriteOptions(), "foo1", "oldvalue"));
  2305. std::vector<ColumnFamilyHandle*> column_families;
  2306. column_families.push_back(handles_[0]);
  2307. column_families.push_back(handles_[1]);
  2308. column_families.push_back(handles_[2]);
  2309. std::vector<IngestExternalFileOptions> ifos(column_families.size());
  2310. for (auto& ifo : ifos) {
  2311. ifo.allow_global_seqno = true; // Always allow global_seqno
  2312. // May or may not write global_seqno
  2313. ifo.write_global_seqno = std::get<0>(GetParam());
  2314. // Whether to verify checksums before ingestion
  2315. ifo.verify_checksums_before_ingest = std::get<1>(GetParam());
  2316. }
  2317. std::vector<std::vector<std::pair<std::string, std::string>>> data;
  2318. data.push_back(
  2319. {std::make_pair("foo1", "fv1"), std::make_pair("foo2", "fv2")});
  2320. data.push_back(
  2321. {std::make_pair("bar1", "bv1"), std::make_pair("bar2", "bv2")});
  2322. data.push_back(
  2323. {std::make_pair("bar3", "bv3"), std::make_pair("bar4", "bv4")});
  2324. // Resize the true_data vector upon construction to avoid re-alloc
  2325. std::vector<std::map<std::string, std::string>> true_data(
  2326. column_families.size());
  2327. ASSERT_OK(GenerateAndAddExternalFiles(options, column_families, ifos, data,
  2328. -1, true, true_data));
  2329. Close();
  2330. ReopenWithColumnFamilies({kDefaultColumnFamilyName, "pikachu", "eevee"},
  2331. options);
  2332. ASSERT_EQ(3, handles_.size());
  2333. int cf = 0;
  2334. for (const auto& verify_map : true_data) {
  2335. for (const auto& elem : verify_map) {
  2336. const std::string& key = elem.first;
  2337. const std::string& value = elem.second;
  2338. ASSERT_EQ(value, Get(cf, key));
  2339. }
  2340. ++cf;
  2341. }
  2342. Close();
  2343. Destroy(options, true /* delete_cf_paths */);
  2344. }
  2345. TEST_P(ExternalSSTFileTest,
  2346. IngestFilesIntoMultipleColumnFamilies_NoMixedStateWithSnapshot) {
  2347. std::unique_ptr<FaultInjectionTestEnv> fault_injection_env(
  2348. new FaultInjectionTestEnv(env_));
  2349. SyncPoint::GetInstance()->DisableProcessing();
  2350. SyncPoint::GetInstance()->ClearAllCallBacks();
  2351. SyncPoint::GetInstance()->LoadDependency({
  2352. {"DBImpl::IngestExternalFiles:InstallSVForFirstCF:0",
  2353. "ExternalSSTFileTest::IngestFilesIntoMultipleColumnFamilies_MixedState:"
  2354. "BeforeRead"},
  2355. {"ExternalSSTFileTest::IngestFilesIntoMultipleColumnFamilies_MixedState:"
  2356. "AfterRead",
  2357. "DBImpl::IngestExternalFiles:InstallSVForFirstCF:1"},
  2358. });
  2359. SyncPoint::GetInstance()->EnableProcessing();
  2360. Options options = CurrentOptions();
  2361. options.env = fault_injection_env.get();
  2362. CreateAndReopenWithCF({"pikachu", "eevee"}, options);
  2363. const std::vector<std::map<std::string, std::string>> data_before_ingestion =
  2364. {{{"foo1", "fv1_0"}, {"foo2", "fv2_0"}, {"foo3", "fv3_0"}},
  2365. {{"bar1", "bv1_0"}, {"bar2", "bv2_0"}, {"bar3", "bv3_0"}},
  2366. {{"bar4", "bv4_0"}, {"bar5", "bv5_0"}, {"bar6", "bv6_0"}}};
  2367. for (size_t i = 0; i != handles_.size(); ++i) {
  2368. int cf = static_cast<int>(i);
  2369. const auto& orig_data = data_before_ingestion[i];
  2370. for (const auto& kv : orig_data) {
  2371. ASSERT_OK(Put(cf, kv.first, kv.second));
  2372. }
  2373. ASSERT_OK(Flush(cf));
  2374. }
  2375. std::vector<ColumnFamilyHandle*> column_families;
  2376. column_families.push_back(handles_[0]);
  2377. column_families.push_back(handles_[1]);
  2378. column_families.push_back(handles_[2]);
  2379. std::vector<IngestExternalFileOptions> ifos(column_families.size());
  2380. for (auto& ifo : ifos) {
  2381. ifo.allow_global_seqno = true; // Always allow global_seqno
  2382. // May or may not write global_seqno
  2383. ifo.write_global_seqno = std::get<0>(GetParam());
  2384. // Whether to verify checksums before ingestion
  2385. ifo.verify_checksums_before_ingest = std::get<1>(GetParam());
  2386. }
  2387. std::vector<std::vector<std::pair<std::string, std::string>>> data;
  2388. data.push_back(
  2389. {std::make_pair("foo1", "fv1"), std::make_pair("foo2", "fv2")});
  2390. data.push_back(
  2391. {std::make_pair("bar1", "bv1"), std::make_pair("bar2", "bv2")});
  2392. data.push_back(
  2393. {std::make_pair("bar3", "bv3"), std::make_pair("bar4", "bv4")});
  2394. // Resize the true_data vector upon construction to avoid re-alloc
  2395. std::vector<std::map<std::string, std::string>> true_data(
  2396. column_families.size());
  2397. // Take snapshot before ingestion starts
  2398. ReadOptions read_opts;
  2399. read_opts.total_order_seek = true;
  2400. read_opts.snapshot = dbfull()->GetSnapshot();
  2401. std::vector<Iterator*> iters(handles_.size());
  2402. // Range scan checks first kv of each CF before ingestion starts.
  2403. for (size_t i = 0; i != handles_.size(); ++i) {
  2404. iters[i] = dbfull()->NewIterator(read_opts, handles_[i]);
  2405. iters[i]->SeekToFirst();
  2406. ASSERT_TRUE(iters[i]->Valid());
  2407. const std::string& key = iters[i]->key().ToString();
  2408. const std::string& value = iters[i]->value().ToString();
  2409. const std::map<std::string, std::string>& orig_data =
  2410. data_before_ingestion[i];
  2411. std::map<std::string, std::string>::const_iterator it = orig_data.find(key);
  2412. ASSERT_NE(orig_data.end(), it);
  2413. ASSERT_EQ(it->second, value);
  2414. iters[i]->Next();
  2415. }
  2416. port::Thread ingest_thread([&]() {
  2417. ASSERT_OK(GenerateAndAddExternalFiles(options, column_families, ifos, data,
  2418. -1, true, true_data));
  2419. });
  2420. TEST_SYNC_POINT(
  2421. "ExternalSSTFileTest::IngestFilesIntoMultipleColumnFamilies_MixedState:"
  2422. "BeforeRead");
  2423. // Should see only data before ingestion
  2424. for (size_t i = 0; i != handles_.size(); ++i) {
  2425. const auto& orig_data = data_before_ingestion[i];
  2426. for (; iters[i]->Valid(); iters[i]->Next()) {
  2427. const std::string& key = iters[i]->key().ToString();
  2428. const std::string& value = iters[i]->value().ToString();
  2429. std::map<std::string, std::string>::const_iterator it =
  2430. orig_data.find(key);
  2431. ASSERT_NE(orig_data.end(), it);
  2432. ASSERT_EQ(it->second, value);
  2433. }
  2434. }
  2435. TEST_SYNC_POINT(
  2436. "ExternalSSTFileTest::IngestFilesIntoMultipleColumnFamilies_MixedState:"
  2437. "AfterRead");
  2438. ingest_thread.join();
  2439. for (auto* iter : iters) {
  2440. ASSERT_OK(iter->status());
  2441. delete iter;
  2442. }
  2443. iters.clear();
  2444. dbfull()->ReleaseSnapshot(read_opts.snapshot);
  2445. Close();
  2446. ReopenWithColumnFamilies({kDefaultColumnFamilyName, "pikachu", "eevee"},
  2447. options);
  2448. // Should see consistent state after ingestion for all column families even
  2449. // without snapshot.
  2450. ASSERT_EQ(3, handles_.size());
  2451. int cf = 0;
  2452. for (const auto& verify_map : true_data) {
  2453. for (const auto& elem : verify_map) {
  2454. const std::string& key = elem.first;
  2455. const std::string& value = elem.second;
  2456. ASSERT_EQ(value, Get(cf, key));
  2457. }
  2458. ++cf;
  2459. }
  2460. Close();
  2461. Destroy(options, true /* delete_cf_paths */);
  2462. }
  2463. TEST_P(ExternalSSTFileTest, IngestFilesIntoMultipleColumnFamilies_PrepareFail) {
  2464. std::unique_ptr<FaultInjectionTestEnv> fault_injection_env(
  2465. new FaultInjectionTestEnv(env_));
  2466. Options options = CurrentOptions();
  2467. options.env = fault_injection_env.get();
  2468. SyncPoint::GetInstance()->DisableProcessing();
  2469. SyncPoint::GetInstance()->ClearAllCallBacks();
  2470. SyncPoint::GetInstance()->LoadDependency({
  2471. {"DBImpl::IngestExternalFiles:BeforeLastJobPrepare:0",
  2472. "ExternalSSTFileTest::IngestFilesIntoMultipleColumnFamilies_PrepareFail:"
  2473. "0"},
  2474. {"ExternalSSTFileTest::IngestFilesIntoMultipleColumnFamilies:PrepareFail:"
  2475. "1",
  2476. "DBImpl::IngestExternalFiles:BeforeLastJobPrepare:1"},
  2477. });
  2478. SyncPoint::GetInstance()->EnableProcessing();
  2479. CreateAndReopenWithCF({"pikachu", "eevee"}, options);
  2480. std::vector<ColumnFamilyHandle*> column_families;
  2481. column_families.push_back(handles_[0]);
  2482. column_families.push_back(handles_[1]);
  2483. column_families.push_back(handles_[2]);
  2484. std::vector<IngestExternalFileOptions> ifos(column_families.size());
  2485. for (auto& ifo : ifos) {
  2486. ifo.allow_global_seqno = true; // Always allow global_seqno
  2487. // May or may not write global_seqno
  2488. ifo.write_global_seqno = std::get<0>(GetParam());
  2489. // Whether to verify block checksums before ingest
  2490. ifo.verify_checksums_before_ingest = std::get<1>(GetParam());
  2491. }
  2492. std::vector<std::vector<std::pair<std::string, std::string>>> data;
  2493. data.push_back(
  2494. {std::make_pair("foo1", "fv1"), std::make_pair("foo2", "fv2")});
  2495. data.push_back(
  2496. {std::make_pair("bar1", "bv1"), std::make_pair("bar2", "bv2")});
  2497. data.push_back(
  2498. {std::make_pair("bar3", "bv3"), std::make_pair("bar4", "bv4")});
  2499. // Resize the true_data vector upon construction to avoid re-alloc
  2500. std::vector<std::map<std::string, std::string>> true_data(
  2501. column_families.size());
  2502. port::Thread ingest_thread([&]() {
  2503. ASSERT_NOK(GenerateAndAddExternalFiles(options, column_families, ifos, data,
  2504. -1, true, true_data));
  2505. });
  2506. TEST_SYNC_POINT(
  2507. "ExternalSSTFileTest::IngestFilesIntoMultipleColumnFamilies_PrepareFail:"
  2508. "0");
  2509. fault_injection_env->SetFilesystemActive(false);
  2510. TEST_SYNC_POINT(
  2511. "ExternalSSTFileTest::IngestFilesIntoMultipleColumnFamilies:PrepareFail:"
  2512. "1");
  2513. ingest_thread.join();
  2514. fault_injection_env->SetFilesystemActive(true);
  2515. Close();
  2516. ReopenWithColumnFamilies({kDefaultColumnFamilyName, "pikachu", "eevee"},
  2517. options);
  2518. ASSERT_EQ(3, handles_.size());
  2519. int cf = 0;
  2520. for (const auto& verify_map : true_data) {
  2521. for (const auto& elem : verify_map) {
  2522. const std::string& key = elem.first;
  2523. ASSERT_EQ("NOT_FOUND", Get(cf, key));
  2524. }
  2525. ++cf;
  2526. }
  2527. Close();
  2528. Destroy(options, true /* delete_cf_paths */);
  2529. }
  2530. TEST_P(ExternalSSTFileTest, IngestFilesIntoMultipleColumnFamilies_CommitFail) {
  2531. std::unique_ptr<FaultInjectionTestEnv> fault_injection_env(
  2532. new FaultInjectionTestEnv(env_));
  2533. Options options = CurrentOptions();
  2534. options.env = fault_injection_env.get();
  2535. SyncPoint::GetInstance()->DisableProcessing();
  2536. SyncPoint::GetInstance()->ClearAllCallBacks();
  2537. SyncPoint::GetInstance()->LoadDependency({
  2538. {"DBImpl::IngestExternalFiles:BeforeJobsRun:0",
  2539. "ExternalSSTFileTest::IngestFilesIntoMultipleColumnFamilies_CommitFail:"
  2540. "0"},
  2541. {"ExternalSSTFileTest::IngestFilesIntoMultipleColumnFamilies_CommitFail:"
  2542. "1",
  2543. "DBImpl::IngestExternalFiles:BeforeJobsRun:1"},
  2544. });
  2545. SyncPoint::GetInstance()->EnableProcessing();
  2546. CreateAndReopenWithCF({"pikachu", "eevee"}, options);
  2547. std::vector<ColumnFamilyHandle*> column_families;
  2548. column_families.push_back(handles_[0]);
  2549. column_families.push_back(handles_[1]);
  2550. column_families.push_back(handles_[2]);
  2551. std::vector<IngestExternalFileOptions> ifos(column_families.size());
  2552. for (auto& ifo : ifos) {
  2553. ifo.allow_global_seqno = true; // Always allow global_seqno
  2554. // May or may not write global_seqno
  2555. ifo.write_global_seqno = std::get<0>(GetParam());
  2556. // Whether to verify block checksums before ingestion
  2557. ifo.verify_checksums_before_ingest = std::get<1>(GetParam());
  2558. }
  2559. std::vector<std::vector<std::pair<std::string, std::string>>> data;
  2560. data.push_back(
  2561. {std::make_pair("foo1", "fv1"), std::make_pair("foo2", "fv2")});
  2562. data.push_back(
  2563. {std::make_pair("bar1", "bv1"), std::make_pair("bar2", "bv2")});
  2564. data.push_back(
  2565. {std::make_pair("bar3", "bv3"), std::make_pair("bar4", "bv4")});
  2566. // Resize the true_data vector upon construction to avoid re-alloc
  2567. std::vector<std::map<std::string, std::string>> true_data(
  2568. column_families.size());
  2569. port::Thread ingest_thread([&]() {
  2570. ASSERT_NOK(GenerateAndAddExternalFiles(options, column_families, ifos, data,
  2571. -1, true, true_data));
  2572. });
  2573. TEST_SYNC_POINT(
  2574. "ExternalSSTFileTest::IngestFilesIntoMultipleColumnFamilies_CommitFail:"
  2575. "0");
  2576. fault_injection_env->SetFilesystemActive(false);
  2577. TEST_SYNC_POINT(
  2578. "ExternalSSTFileTest::IngestFilesIntoMultipleColumnFamilies_CommitFail:"
  2579. "1");
  2580. ingest_thread.join();
  2581. fault_injection_env->SetFilesystemActive(true);
  2582. Close();
  2583. ReopenWithColumnFamilies({kDefaultColumnFamilyName, "pikachu", "eevee"},
  2584. options);
  2585. ASSERT_EQ(3, handles_.size());
  2586. int cf = 0;
  2587. for (const auto& verify_map : true_data) {
  2588. for (const auto& elem : verify_map) {
  2589. const std::string& key = elem.first;
  2590. ASSERT_EQ("NOT_FOUND", Get(cf, key));
  2591. }
  2592. ++cf;
  2593. }
  2594. Close();
  2595. Destroy(options, true /* delete_cf_paths */);
  2596. }
  2597. TEST_P(ExternalSSTFileTest,
  2598. IngestFilesIntoMultipleColumnFamilies_PartialManifestWriteFail) {
  2599. std::unique_ptr<FaultInjectionTestEnv> fault_injection_env(
  2600. new FaultInjectionTestEnv(env_));
  2601. Options options = CurrentOptions();
  2602. options.env = fault_injection_env.get();
  2603. CreateAndReopenWithCF({"pikachu", "eevee"}, options);
  2604. SyncPoint::GetInstance()->ClearTrace();
  2605. SyncPoint::GetInstance()->DisableProcessing();
  2606. SyncPoint::GetInstance()->ClearAllCallBacks();
  2607. SyncPoint::GetInstance()->LoadDependency({
  2608. {"VersionSet::ProcessManifestWrites:BeforeWriteLastVersionEdit:0",
  2609. "ExternalSSTFileTest::IngestFilesIntoMultipleColumnFamilies_"
  2610. "PartialManifestWriteFail:0"},
  2611. {"ExternalSSTFileTest::IngestFilesIntoMultipleColumnFamilies_"
  2612. "PartialManifestWriteFail:1",
  2613. "VersionSet::ProcessManifestWrites:BeforeWriteLastVersionEdit:1"},
  2614. });
  2615. SyncPoint::GetInstance()->EnableProcessing();
  2616. std::vector<ColumnFamilyHandle*> column_families;
  2617. column_families.push_back(handles_[0]);
  2618. column_families.push_back(handles_[1]);
  2619. column_families.push_back(handles_[2]);
  2620. std::vector<IngestExternalFileOptions> ifos(column_families.size());
  2621. for (auto& ifo : ifos) {
  2622. ifo.allow_global_seqno = true; // Always allow global_seqno
  2623. // May or may not write global_seqno
  2624. ifo.write_global_seqno = std::get<0>(GetParam());
  2625. // Whether to verify block checksums before ingestion
  2626. ifo.verify_checksums_before_ingest = std::get<1>(GetParam());
  2627. }
  2628. std::vector<std::vector<std::pair<std::string, std::string>>> data;
  2629. data.push_back(
  2630. {std::make_pair("foo1", "fv1"), std::make_pair("foo2", "fv2")});
  2631. data.push_back(
  2632. {std::make_pair("bar1", "bv1"), std::make_pair("bar2", "bv2")});
  2633. data.push_back(
  2634. {std::make_pair("bar3", "bv3"), std::make_pair("bar4", "bv4")});
  2635. // Resize the true_data vector upon construction to avoid re-alloc
  2636. std::vector<std::map<std::string, std::string>> true_data(
  2637. column_families.size());
  2638. port::Thread ingest_thread([&]() {
  2639. ASSERT_NOK(GenerateAndAddExternalFiles(options, column_families, ifos, data,
  2640. -1, true, true_data));
  2641. });
  2642. TEST_SYNC_POINT(
  2643. "ExternalSSTFileTest::IngestFilesIntoMultipleColumnFamilies_"
  2644. "PartialManifestWriteFail:0");
  2645. fault_injection_env->SetFilesystemActive(false);
  2646. TEST_SYNC_POINT(
  2647. "ExternalSSTFileTest::IngestFilesIntoMultipleColumnFamilies_"
  2648. "PartialManifestWriteFail:1");
  2649. ingest_thread.join();
  2650. ASSERT_OK(fault_injection_env->DropUnsyncedFileData());
  2651. fault_injection_env->SetFilesystemActive(true);
  2652. Close();
  2653. ReopenWithColumnFamilies({kDefaultColumnFamilyName, "pikachu", "eevee"},
  2654. options);
  2655. ASSERT_EQ(3, handles_.size());
  2656. int cf = 0;
  2657. for (const auto& verify_map : true_data) {
  2658. for (const auto& elem : verify_map) {
  2659. const std::string& key = elem.first;
  2660. ASSERT_EQ("NOT_FOUND", Get(cf, key));
  2661. }
  2662. ++cf;
  2663. }
  2664. Close();
  2665. Destroy(options, true /* delete_cf_paths */);
  2666. }
  2667. TEST_P(ExternalSSTFileTest, IngestFilesTriggerFlushingWithTwoWriteQueue) {
  2668. Options options = CurrentOptions();
  2669. // Use large buffer to avoid memtable flush
  2670. options.write_buffer_size = 1024 * 1024;
  2671. options.two_write_queues = true;
  2672. DestroyAndReopen(options);
  2673. ASSERT_OK(dbfull()->Put(WriteOptions(), "1000", "v1"));
  2674. ASSERT_OK(dbfull()->Put(WriteOptions(), "1001", "v1"));
  2675. ASSERT_OK(dbfull()->Put(WriteOptions(), "9999", "v1"));
  2676. // Put one key which is overlap with keys in memtable.
  2677. // It will trigger flushing memtable and require this thread is
  2678. // currently at the front of the 2nd writer queue. We must make
  2679. // sure that it won't enter the 2nd writer queue for the second time.
  2680. std::vector<std::pair<std::string, std::string>> data;
  2681. data.emplace_back("1001", "v2");
  2682. ASSERT_OK(GenerateAndAddExternalFile(options, data, -1, true));
  2683. }
  2684. TEST_P(ExternalSSTFileTest, DeltaEncodingWhileGlobalSeqnoPresent) {
  2685. Options options = CurrentOptions();
  2686. DestroyAndReopen(options);
  2687. constexpr size_t kValueSize = 8;
  2688. Random rnd(301);
  2689. std::string value = rnd.RandomString(kValueSize);
  2690. // Write some key to make global seqno larger than zero
  2691. for (int i = 0; i < 10; i++) {
  2692. ASSERT_OK(Put("ab" + Key(i), value));
  2693. }
  2694. // Get a Snapshot to make RocksDB assign global seqno to ingested sst files.
  2695. auto snap = dbfull()->GetSnapshot();
  2696. std::string fname = sst_files_dir_ + "test_file";
  2697. ROCKSDB_NAMESPACE::SstFileWriter writer(EnvOptions(), options);
  2698. ASSERT_OK(writer.Open(fname));
  2699. std::string key1 = "ab";
  2700. std::string key2 = "ab";
  2701. // Make the prefix of key2 is same with key1 add zero seqno. The tail of every
  2702. // key is composed as (seqno << 8 | value_type), and here `1` represents
  2703. // ValueType::kTypeValue
  2704. PutFixed64(&key2, PackSequenceAndType(0, kTypeValue));
  2705. key2 += "cdefghijkl";
  2706. ASSERT_OK(writer.Put(key1, value));
  2707. ASSERT_OK(writer.Put(key2, value));
  2708. ExternalSstFileInfo info;
  2709. ASSERT_OK(writer.Finish(&info));
  2710. ASSERT_OK(dbfull()->IngestExternalFile({info.file_path},
  2711. IngestExternalFileOptions()));
  2712. dbfull()->ReleaseSnapshot(snap);
  2713. ASSERT_EQ(value, Get(key1));
  2714. // You will get error here
  2715. ASSERT_EQ(value, Get(key2));
  2716. }
  2717. TEST_P(ExternalSSTFileTest,
  2718. DeltaEncodingWhileGlobalSeqnoPresentIteratorSwitch) {
  2719. // Regression test for bug where global seqno corrupted the shared bytes
  2720. // buffer when switching from reverse iteration to forward iteration.
  2721. constexpr size_t kValueSize = 8;
  2722. Options options = CurrentOptions();
  2723. Random rnd(301);
  2724. std::string value = rnd.RandomString(kValueSize);
  2725. std::string key0 = "aa";
  2726. std::string key1 = "ab";
  2727. // Make the prefix of key2 is same with key1 add zero seqno. The tail of every
  2728. // key is composed as (seqno << 8 | value_type), and here `1` represents
  2729. // ValueType::kTypeValue
  2730. std::string key2 = "ab";
  2731. PutFixed64(&key2, PackSequenceAndType(0, kTypeValue));
  2732. key2 += "cdefghijkl";
  2733. std::string key3 = key2 + "_";
  2734. // Write some key to make global seqno larger than zero
  2735. ASSERT_OK(Put(key0, value));
  2736. std::string fname = sst_files_dir_ + "test_file";
  2737. ROCKSDB_NAMESPACE::SstFileWriter writer(EnvOptions(), options);
  2738. ASSERT_OK(writer.Open(fname));
  2739. // key0 is a dummy to ensure the turnaround point (key1) comes from Prev
  2740. // cache rather than block (restart keys are pinned in block).
  2741. ASSERT_OK(writer.Put(key0, value));
  2742. ASSERT_OK(writer.Put(key1, value));
  2743. ASSERT_OK(writer.Put(key2, value));
  2744. ASSERT_OK(writer.Put(key3, value));
  2745. ExternalSstFileInfo info;
  2746. ASSERT_OK(writer.Finish(&info));
  2747. ASSERT_OK(dbfull()->IngestExternalFile({info.file_path},
  2748. IngestExternalFileOptions()));
  2749. ReadOptions read_opts;
  2750. // Prevents Seek() when switching directions, which circumvents the bug.
  2751. read_opts.total_order_seek = true;
  2752. Iterator* iter = db_->NewIterator(read_opts);
  2753. // Scan backwards to key2. File iterator will then be positioned at key1.
  2754. iter->Seek(key3);
  2755. ASSERT_EQ(key3, iter->key());
  2756. iter->Prev();
  2757. ASSERT_EQ(key2, iter->key());
  2758. // Scan forwards and make sure key3 is present. Previously key3 would be
  2759. // corrupted by the global seqno from key1.
  2760. iter->Next();
  2761. ASSERT_EQ(key3, iter->key());
  2762. delete iter;
  2763. }
  2764. TEST_F(ExternalSSTFileTest, FIFOCompaction) {
  2765. // FIFO always ingests SST files to L0 and assign latest sequence number.
  2766. Options options = CurrentOptions();
  2767. options.num_levels = 1;
  2768. options.compaction_style = kCompactionStyleFIFO;
  2769. options.max_open_files = -1;
  2770. DestroyAndReopen(options);
  2771. std::map<std::string, std::string> true_data;
  2772. for (int i = 0; i < 100; ++i) {
  2773. ASSERT_OK(Put(Key(i), Key(i) + "_val"));
  2774. true_data[Key(i)] = Key(i) + "_val";
  2775. }
  2776. ASSERT_OK(Flush());
  2777. ASSERT_EQ("1", FilesPerLevel());
  2778. std::vector<std::pair<std::string, std::string>> file_data;
  2779. for (int i = 0; i <= 20; i++) {
  2780. file_data.emplace_back(Key(i), Key(i) + "_ingest");
  2781. }
  2782. // Overlaps with memtable, will trigger flush
  2783. ASSERT_OK(GenerateAndAddExternalFile(options, file_data, -1,
  2784. /*allow_global_seqno=*/true, true, false,
  2785. false, false, &true_data));
  2786. ASSERT_EQ("2", FilesPerLevel());
  2787. file_data.clear();
  2788. for (int i = 100; i <= 120; i++) {
  2789. file_data.emplace_back(Key(i), Key(i) + "_ingest");
  2790. }
  2791. // global sequence number is always assigned, so this will fail
  2792. ASSERT_NOK(GenerateAndAddExternalFile(options, file_data, -1,
  2793. /*allow_global_seqno=*/false, true,
  2794. false, false, false, &true_data));
  2795. ASSERT_OK(GenerateAndAddExternalFile(options, file_data, -1,
  2796. /*allow_global_seqno=*/true, true, false,
  2797. false, false, &true_data));
  2798. // Compact to data to lower level to test multi-level FIFO later
  2799. options.num_levels = 7;
  2800. options.compaction_style = kCompactionStyleUniversal;
  2801. ASSERT_OK(TryReopen(options));
  2802. CompactRangeOptions cro;
  2803. cro.bottommost_level_compaction = BottommostLevelCompaction::kForceOptimized;
  2804. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  2805. ASSERT_EQ("0,0,0,0,0,0,1", FilesPerLevel());
  2806. options.num_levels = 7;
  2807. options.compaction_style = kCompactionStyleFIFO;
  2808. ASSERT_OK(TryReopen(options));
  2809. file_data.clear();
  2810. for (int i = 200; i <= 220; i++) {
  2811. file_data.emplace_back(Key(i), Key(i) + "_ingest");
  2812. }
  2813. // Files are ingested into L0 for multi-level FIFO
  2814. ASSERT_OK(GenerateAndAddExternalFile(options, file_data, -1,
  2815. /*allow_global_seqno=*/true, true, false,
  2816. false, false, &true_data));
  2817. ASSERT_EQ("1,0,0,0,0,0,1", FilesPerLevel());
  2818. VerifyDBFromMap(true_data);
  2819. }
  2820. class ExternalSSTFileWithTimestampTest : public ExternalSSTFileTest {
  2821. public:
  2822. ExternalSSTFileWithTimestampTest() = default;
  2823. static const std::string kValueNotFound;
  2824. static const std::string kTsNotFound;
  2825. std::string EncodeAsUint64(uint64_t v) {
  2826. std::string dst;
  2827. PutFixed64(&dst, v);
  2828. return dst;
  2829. }
  2830. Status IngestExternalUDTFile(const std::vector<std::string>& files,
  2831. bool allow_global_seqno = true) {
  2832. IngestExternalFileOptions opts;
  2833. opts.snapshot_consistency = true;
  2834. opts.allow_global_seqno = allow_global_seqno;
  2835. return db_->IngestExternalFile(files, opts);
  2836. }
  2837. void VerifyValueAndTs(const std::string& key,
  2838. const std::string& read_timestamp,
  2839. const std::string& expected_value,
  2840. const std::string& expected_timestamp) {
  2841. Slice read_ts = read_timestamp;
  2842. ReadOptions read_options;
  2843. read_options.timestamp = &read_ts;
  2844. std::string value;
  2845. std::string timestamp;
  2846. Status s = db_->Get(read_options, key, &value, &timestamp);
  2847. if (s.ok()) {
  2848. ASSERT_EQ(value, expected_value);
  2849. ASSERT_EQ(timestamp, expected_timestamp);
  2850. } else if (s.IsNotFound()) {
  2851. ASSERT_EQ(kValueNotFound, expected_value);
  2852. ASSERT_EQ(kTsNotFound, expected_timestamp);
  2853. } else {
  2854. assert(false);
  2855. }
  2856. }
  2857. };
  2858. const std::string ExternalSSTFileWithTimestampTest::kValueNotFound =
  2859. "NOT_FOUND";
  2860. const std::string ExternalSSTFileWithTimestampTest::kTsNotFound =
  2861. "NOT_FOUND_TS";
  2862. TEST_F(ExternalSSTFileWithTimestampTest, Basic) {
  2863. do {
  2864. Options options = CurrentOptions();
  2865. options.comparator = test::BytewiseComparatorWithU64TsWrapper();
  2866. options.persist_user_defined_timestamps = true;
  2867. DestroyAndReopen(options);
  2868. SstFileWriter sst_file_writer(EnvOptions(), options);
  2869. // Current file size should be 0 after sst_file_writer init and before open
  2870. // a file.
  2871. ASSERT_EQ(sst_file_writer.FileSize(), 0);
  2872. // file1.sst [0, 50)
  2873. std::string file1 = sst_files_dir_ + "file1.sst";
  2874. ASSERT_OK(sst_file_writer.Open(file1));
  2875. for (int k = 0; k < 50; k++) {
  2876. // write 3 versions of values for each key, write newer version first
  2877. // they are treated as logically smaller by the comparator.
  2878. for (int version = 3; version > 0; version--) {
  2879. ASSERT_OK(
  2880. sst_file_writer.Put(Key(k), EncodeAsUint64(k + version),
  2881. Key(k) + "_val" + std::to_string(version)));
  2882. }
  2883. }
  2884. ExternalSstFileInfo file1_info;
  2885. ASSERT_OK(sst_file_writer.Finish(&file1_info));
  2886. // sst_file_writer already finished, cannot add this value
  2887. ASSERT_NOK(sst_file_writer.Put(Key(100), EncodeAsUint64(1), "bad_val"));
  2888. ASSERT_EQ(file1_info.file_path, file1);
  2889. ASSERT_EQ(file1_info.num_entries, 150);
  2890. ASSERT_EQ(file1_info.smallest_key, Key(0) + EncodeAsUint64(0 + 3));
  2891. ASSERT_EQ(file1_info.largest_key, Key(49) + EncodeAsUint64(49 + 1));
  2892. ASSERT_EQ(db_->GetLatestSequenceNumber(), 0U);
  2893. // Add file using file path
  2894. ASSERT_OK(IngestExternalUDTFile({file1}));
  2895. ASSERT_EQ(db_->GetLatestSequenceNumber(), 0U);
  2896. for (int k = 0; k < 50; k++) {
  2897. for (int version = 3; version > 0; version--) {
  2898. VerifyValueAndTs(Key(k), EncodeAsUint64(k + version),
  2899. Key(k) + "_val" + std::to_string(version),
  2900. EncodeAsUint64(k + version));
  2901. }
  2902. }
  2903. // file2.sst [50, 200)
  2904. // Put [key=k, ts=k, value=k_val] for k in [50, 200)
  2905. // RangeDelete[start_key=75, end_key=125, ts=100]
  2906. std::string file2 = sst_files_dir_ + "file2.sst";
  2907. int range_del_begin = 75, range_del_end = 125, range_del_ts = 100;
  2908. ASSERT_OK(sst_file_writer.Open(file2));
  2909. for (int k = 50; k < 200; k++) {
  2910. ASSERT_OK(
  2911. sst_file_writer.Put(Key(k), EncodeAsUint64(k), Key(k) + "_val"));
  2912. if (k == range_del_ts) {
  2913. ASSERT_OK(sst_file_writer.DeleteRange(
  2914. Key(range_del_begin), Key(range_del_end), EncodeAsUint64(k)));
  2915. }
  2916. }
  2917. ExternalSstFileInfo file2_info;
  2918. ASSERT_OK(sst_file_writer.Finish(&file2_info));
  2919. // Current file size should be non-zero after success write.
  2920. ASSERT_GT(sst_file_writer.FileSize(), 0);
  2921. ASSERT_EQ(file2_info.file_path, file2);
  2922. ASSERT_EQ(file2_info.num_entries, 150);
  2923. ASSERT_EQ(file2_info.smallest_key, Key(50) + EncodeAsUint64(50));
  2924. ASSERT_EQ(file2_info.largest_key, Key(199) + EncodeAsUint64(199));
  2925. ASSERT_EQ(file2_info.num_range_del_entries, 1);
  2926. ASSERT_EQ(file2_info.smallest_range_del_key,
  2927. Key(range_del_begin) + EncodeAsUint64(range_del_ts));
  2928. ASSERT_EQ(file2_info.largest_range_del_key,
  2929. Key(range_del_end) + EncodeAsUint64(range_del_ts));
  2930. // Add file using file path
  2931. ASSERT_OK(IngestExternalUDTFile({file2}));
  2932. ASSERT_EQ(db_->GetLatestSequenceNumber(), 0U);
  2933. for (int k = 50; k < 200; k++) {
  2934. if (k < range_del_begin || k >= range_del_end) {
  2935. VerifyValueAndTs(Key(k), EncodeAsUint64(k), Key(k) + "_val",
  2936. EncodeAsUint64(k));
  2937. }
  2938. // else {
  2939. // // FIXME(yuzhangyu): when range tombstone and point data has the
  2940. // // same seq, on read path, make range tombstone overrides point
  2941. // // data if it has a newer user-defined timestamp. This is how
  2942. // // we determine point data's overriding relationship, so we
  2943. // // should keep it consistent.
  2944. // VerifyValueAndTs(Key(k), EncodeAsUint64(k), Key(k) + "_val",
  2945. // EncodeAsUint64(k));
  2946. // VerifyValueAndTs(Key(k), EncodeAsUint64(range_del_ts),
  2947. // kValueNotFound,
  2948. // kTsNotFound);
  2949. // }
  2950. }
  2951. // file3.sst [100, 200), key range overlap with db
  2952. std::string file3 = sst_files_dir_ + "file3.sst";
  2953. ASSERT_OK(sst_file_writer.Open(file3));
  2954. for (int k = 100; k < 200; k++) {
  2955. ASSERT_OK(
  2956. sst_file_writer.Put(Key(k), EncodeAsUint64(k + 1), Key(k) + "_val1"));
  2957. }
  2958. ExternalSstFileInfo file3_info;
  2959. ASSERT_OK(sst_file_writer.Finish(&file3_info));
  2960. ASSERT_EQ(file3_info.file_path, file3);
  2961. ASSERT_EQ(file3_info.num_entries, 100);
  2962. ASSERT_EQ(file3_info.smallest_key, Key(100) + EncodeAsUint64(101));
  2963. ASSERT_EQ(file3_info.largest_key, Key(199) + EncodeAsUint64(200));
  2964. // Allowing ingesting a file containing overlap key range with the db is
  2965. // not safe without verifying the overlapped key has a higher timestamp
  2966. // than what the db contains, so we do not allow this regardless of
  2967. // whether global sequence number is allowed.
  2968. ASSERT_NOK(IngestExternalUDTFile({file2}));
  2969. ASSERT_NOK(IngestExternalUDTFile({file2}, /*allow_global_seqno*/ false));
  2970. // Write [0, 50)
  2971. // Write to DB newer versions to cover ingested data and move sequence
  2972. // number forward.
  2973. for (int k = 0; k < 50; k++) {
  2974. ASSERT_OK(dbfull()->Put(WriteOptions(), Key(k), EncodeAsUint64(k + 4),
  2975. Key(k) + "_val" + std::to_string(4)));
  2976. }
  2977. // Read all 4 versions (3 from ingested, 1 from live writes).
  2978. for (int k = 0; k < 50; k++) {
  2979. for (int version = 4; version > 0; version--) {
  2980. VerifyValueAndTs(Key(k), EncodeAsUint64(k + version),
  2981. Key(k) + "_val" + std::to_string(version),
  2982. EncodeAsUint64(k + version));
  2983. }
  2984. }
  2985. SequenceNumber seq_num_before_ingestion = db_->GetLatestSequenceNumber();
  2986. ASSERT_GT(seq_num_before_ingestion, 0U);
  2987. // file4.sst [200, 250)
  2988. std::string file4 = sst_files_dir_ + "file4.sst";
  2989. ASSERT_OK(sst_file_writer.Open(file4));
  2990. for (int k = 200; k < 250; k++) {
  2991. ASSERT_OK(
  2992. sst_file_writer.Put(Key(k), EncodeAsUint64(k), Key(k) + "_val"));
  2993. }
  2994. ExternalSstFileInfo file4_info;
  2995. ASSERT_OK(sst_file_writer.Finish(&file4_info));
  2996. // Current file size should be non-zero after success write.
  2997. ASSERT_GT(sst_file_writer.FileSize(), 0);
  2998. ASSERT_EQ(file4_info.file_path, file4);
  2999. ASSERT_EQ(file4_info.num_entries, 50);
  3000. ASSERT_EQ(file4_info.smallest_key, Key(200) + EncodeAsUint64(200));
  3001. ASSERT_EQ(file4_info.largest_key, Key(249) + EncodeAsUint64(249));
  3002. ASSERT_EQ(file4_info.num_range_del_entries, 0);
  3003. ASSERT_EQ(file4_info.smallest_range_del_key, "");
  3004. ASSERT_EQ(file4_info.largest_range_del_key, "");
  3005. ASSERT_OK(IngestExternalUDTFile({file4}));
  3006. for (int k = 200; k < 250; k++) {
  3007. VerifyValueAndTs(Key(k), EncodeAsUint64(k), Key(k) + "_val",
  3008. EncodeAsUint64(k));
  3009. }
  3010. // In UDT mode, any external file that can be successfully ingested also
  3011. // should not overlap with the db. As a result, they can always get the
  3012. // seq 0 assigned.
  3013. ASSERT_EQ(db_->GetLatestSequenceNumber(), seq_num_before_ingestion);
  3014. // file5.sst (Key(200), ts = 199)
  3015. // While DB has (Key(200), ts = 200) => user key without timestamp overlaps
  3016. std::string file5 = sst_files_dir_ + "file5.sst";
  3017. ASSERT_OK(sst_file_writer.Open(file5));
  3018. ASSERT_OK(
  3019. sst_file_writer.Put(Key(200), EncodeAsUint64(199), Key(200) + "_val"));
  3020. ExternalSstFileInfo file5_info;
  3021. ASSERT_OK(sst_file_writer.Finish(&file5_info));
  3022. ASSERT_TRUE(IngestExternalUDTFile({file5}).IsInvalidArgument());
  3023. // file6.sst (Key(200), ts = 201)
  3024. // While DB has (Key(200), ts = 200) => user key without timestamp overlaps
  3025. std::string file6 = sst_files_dir_ + "file6.sst";
  3026. ASSERT_OK(sst_file_writer.Open(file6));
  3027. ASSERT_OK(
  3028. sst_file_writer.Put(Key(200), EncodeAsUint64(201), Key(0) + "_val"));
  3029. ExternalSstFileInfo file6_info;
  3030. ASSERT_OK(sst_file_writer.Finish(&file6_info));
  3031. ASSERT_TRUE(IngestExternalUDTFile({file6}).IsInvalidArgument());
  3032. // Check memtable overlap.
  3033. ASSERT_OK(dbfull()->Put(WriteOptions(), Key(250), EncodeAsUint64(250),
  3034. Key(250) + "_val"));
  3035. std::string file7 = sst_files_dir_ + "file7.sst";
  3036. ASSERT_OK(sst_file_writer.Open(file7));
  3037. ASSERT_OK(
  3038. sst_file_writer.Put(Key(250), EncodeAsUint64(249), Key(250) + "_val2"));
  3039. ExternalSstFileInfo file7_info;
  3040. ASSERT_OK(sst_file_writer.Finish(&file7_info));
  3041. ASSERT_TRUE(IngestExternalUDTFile({file7}).IsInvalidArgument());
  3042. std::string file8 = sst_files_dir_ + "file8.sst";
  3043. ASSERT_OK(sst_file_writer.Open(file8));
  3044. ASSERT_OK(
  3045. sst_file_writer.Put(Key(250), EncodeAsUint64(251), Key(250) + "_val3"));
  3046. ExternalSstFileInfo file8_info;
  3047. ASSERT_OK(sst_file_writer.Finish(&file8_info));
  3048. ASSERT_TRUE(IngestExternalUDTFile({file8}).IsInvalidArgument());
  3049. DestroyAndRecreateExternalSSTFilesDir();
  3050. } while (ChangeOptions(kSkipPlainTable | kSkipFIFOCompaction |
  3051. kRangeDelSkipConfigs));
  3052. }
  3053. TEST_F(ExternalSSTFileWithTimestampTest, SanityCheck) {
  3054. Options options = CurrentOptions();
  3055. options.comparator = test::BytewiseComparatorWithU64TsWrapper();
  3056. options.persist_user_defined_timestamps = true;
  3057. DestroyAndReopen(options);
  3058. SstFileWriter sst_file_writer(EnvOptions(), options);
  3059. // file1.sst [0, 100)
  3060. std::string file1 = sst_files_dir_ + "file1.sst";
  3061. ASSERT_OK(sst_file_writer.Open(file1));
  3062. for (int k = 0; k < 100; k++) {
  3063. ASSERT_OK(sst_file_writer.Put(Key(k), EncodeAsUint64(k), Key(k) + "_val"));
  3064. }
  3065. ExternalSstFileInfo file1_info;
  3066. ASSERT_OK(sst_file_writer.Finish(&file1_info));
  3067. // file2.sst [50, 75)
  3068. std::string file2 = sst_files_dir_ + "file2.sst";
  3069. ASSERT_OK(sst_file_writer.Open(file2));
  3070. for (int k = 50; k < 75; k++) {
  3071. ASSERT_OK(
  3072. sst_file_writer.Put(Key(k), EncodeAsUint64(k + 2), Key(k) + "_val"));
  3073. }
  3074. ExternalSstFileInfo file2_info;
  3075. ASSERT_OK(sst_file_writer.Finish(&file2_info));
  3076. // Cannot ingest when files' user key range overlaps. There is no
  3077. // straightforward way to assign sequence number to the files so that they
  3078. // meet the user-defined timestamps invariant: for the same user provided key,
  3079. // the entry with a higher sequence number should not have a smaller
  3080. // timestamp. In this case: file1 has (key=k, ts=k) for k in [50, 75),
  3081. // file2 has (key=k, ts=k+2) for k in [50, 75).
  3082. // The invariant is only met if file2 is ingested after file1. In other cases
  3083. // when user key ranges are interleaved in files, no order of ingestion can
  3084. // guarantee this invariant. So we do not allow ingesting files with
  3085. // overlapping key ranges.
  3086. ASSERT_TRUE(IngestExternalUDTFile({file1, file2}).IsNotSupported());
  3087. for (bool cf_option : {false, true}) {
  3088. SCOPED_TRACE("cf_option = " + std::to_string(cf_option));
  3089. if (cf_option) {
  3090. options.cf_allow_ingest_behind = true;
  3091. } else {
  3092. options.allow_ingest_behind = true;
  3093. }
  3094. DestroyAndReopen(options);
  3095. IngestExternalFileOptions opts;
  3096. // TODO(yuzhangyu): support ingestion behind for user-defined timestamps?
  3097. // Ingesting external files with user-defined timestamps requires searching
  3098. // through the whole lsm tree to make sure there is no key range overlap
  3099. // with the db. Ingestion behind currently is doing a simply placing it at
  3100. // the bottom level step without a search, so we don't allow it either.
  3101. opts.ingest_behind = true;
  3102. ASSERT_TRUE(db_->IngestExternalFile({file1}, opts).IsNotSupported());
  3103. DestroyAndRecreateExternalSSTFilesDir();
  3104. }
  3105. }
  3106. TEST_F(ExternalSSTFileWithTimestampTest, UDTSettingsCompatibilityCheck) {
  3107. Options options = CurrentOptions();
  3108. Options disable_udt_options = options;
  3109. Options not_persist_udt_options = options;
  3110. Options persist_udt_options = options;
  3111. disable_udt_options.comparator = BytewiseComparator();
  3112. not_persist_udt_options.comparator =
  3113. test::BytewiseComparatorWithU64TsWrapper();
  3114. not_persist_udt_options.persist_user_defined_timestamps = false;
  3115. not_persist_udt_options.allow_concurrent_memtable_write = false;
  3116. persist_udt_options.comparator = test::BytewiseComparatorWithU64TsWrapper();
  3117. persist_udt_options.persist_user_defined_timestamps = true;
  3118. EnvOptions env_options = EnvOptions();
  3119. SstFileWriter disable_udt_sst_writer(env_options, disable_udt_options);
  3120. SstFileWriter not_persist_udt_sst_writer(env_options,
  3121. not_persist_udt_options);
  3122. SstFileWriter persist_udt_sst_writer(env_options, persist_udt_options);
  3123. // File1: [0, 50), contains no timestamps
  3124. // comparator name: leveldb.BytewiseComparator
  3125. // user_defined_timestamps_persisted: true
  3126. std::string disable_udt_sst_file = sst_files_dir_ + "file1.sst";
  3127. ASSERT_OK(disable_udt_sst_writer.Open(disable_udt_sst_file));
  3128. for (int k = 0; k < 50; k++) {
  3129. ASSERT_NOK(
  3130. disable_udt_sst_writer.Put(Key(k), EncodeAsUint64(1), Key(k) + "_val"));
  3131. ASSERT_OK(disable_udt_sst_writer.Put(Key(k), Key(k) + "_val"));
  3132. }
  3133. ASSERT_OK(disable_udt_sst_writer.Finish());
  3134. // File2: [50, 100), contains no timestamps
  3135. // comparator name: leveldb.BytewiseComparator.u64ts
  3136. // user_defined_timestamps_persisted: false
  3137. std::string not_persist_udt_sst_file = sst_files_dir_ + "file2.sst";
  3138. ASSERT_OK(not_persist_udt_sst_writer.Open(not_persist_udt_sst_file));
  3139. for (int k = 50; k < 100; k++) {
  3140. ASSERT_NOK(not_persist_udt_sst_writer.Put(Key(k), Key(k) + "_val"));
  3141. ASSERT_NOK(not_persist_udt_sst_writer.Put(Key(k), EncodeAsUint64(k),
  3142. Key(k) + "_val"));
  3143. ASSERT_OK(not_persist_udt_sst_writer.Put(Key(k), EncodeAsUint64(0),
  3144. Key(k) + "_val"));
  3145. }
  3146. ASSERT_OK(not_persist_udt_sst_writer.Finish());
  3147. // File3: [100, 150), contains timestamp
  3148. // comparator name: leveldb.BytewiseComparator.u64ts
  3149. // user_defined_timestamps_persisted: true
  3150. std::string persist_udt_sst_file = sst_files_dir_ + "file3.sst";
  3151. ASSERT_OK(persist_udt_sst_writer.Open(persist_udt_sst_file));
  3152. for (int k = 100; k < 150; k++) {
  3153. ASSERT_NOK(persist_udt_sst_writer.Put(Key(k), Key(k) + "_val"));
  3154. ASSERT_OK(
  3155. persist_udt_sst_writer.Put(Key(k), EncodeAsUint64(k), Key(k) + "_val"));
  3156. }
  3157. ASSERT_OK(persist_udt_sst_writer.Finish());
  3158. DestroyAndReopen(disable_udt_options);
  3159. ASSERT_OK(
  3160. IngestExternalUDTFile({disable_udt_sst_file, not_persist_udt_sst_file}));
  3161. ASSERT_NOK(IngestExternalUDTFile({persist_udt_sst_file}));
  3162. for (int k = 0; k < 100; k++) {
  3163. ASSERT_EQ(Get(Key(k)), Key(k) + "_val");
  3164. }
  3165. DestroyAndReopen(not_persist_udt_options);
  3166. ASSERT_OK(
  3167. IngestExternalUDTFile({disable_udt_sst_file, not_persist_udt_sst_file}));
  3168. ASSERT_NOK(IngestExternalUDTFile({persist_udt_sst_file}));
  3169. for (int k = 0; k < 100; k++) {
  3170. VerifyValueAndTs(Key(k), EncodeAsUint64(0), Key(k) + "_val",
  3171. EncodeAsUint64(0));
  3172. }
  3173. DestroyAndReopen(persist_udt_options);
  3174. ASSERT_NOK(
  3175. IngestExternalUDTFile({disable_udt_sst_file, not_persist_udt_sst_file}));
  3176. ASSERT_OK(IngestExternalUDTFile({persist_udt_sst_file}));
  3177. for (int k = 100; k < 150; k++) {
  3178. VerifyValueAndTs(Key(k), EncodeAsUint64(k), Key(k) + "_val",
  3179. EncodeAsUint64(k));
  3180. }
  3181. DestroyAndRecreateExternalSSTFilesDir();
  3182. }
  3183. TEST_F(ExternalSSTFileWithTimestampTest, TimestampsNotPersistedBasic) {
  3184. do {
  3185. Options options = CurrentOptions();
  3186. options.comparator = test::BytewiseComparatorWithU64TsWrapper();
  3187. options.persist_user_defined_timestamps = false;
  3188. options.allow_concurrent_memtable_write = false;
  3189. DestroyAndReopen(options);
  3190. SstFileWriter sst_file_writer(EnvOptions(), options);
  3191. // file1.sst [0, 50)
  3192. std::string file1 = sst_files_dir_ + "file1.sst";
  3193. ASSERT_OK(sst_file_writer.Open(file1));
  3194. for (int k = 0; k < 50; k++) {
  3195. // Attempting to write 2 versions of values for each key, only the version
  3196. // with timestamp 0 goes through.
  3197. for (int version = 1; version >= 0; version--) {
  3198. if (version == 1) {
  3199. ASSERT_NOK(
  3200. sst_file_writer.Put(Key(k), EncodeAsUint64(version),
  3201. Key(k) + "_val" + std::to_string(version)));
  3202. } else {
  3203. ASSERT_OK(
  3204. sst_file_writer.Put(Key(k), EncodeAsUint64(version),
  3205. Key(k) + "_val" + std::to_string(version)));
  3206. }
  3207. }
  3208. }
  3209. ExternalSstFileInfo file1_info;
  3210. ASSERT_OK(sst_file_writer.Finish(&file1_info));
  3211. // sst_file_writer already finished, cannot add this value
  3212. ASSERT_NOK(sst_file_writer.Put(Key(100), EncodeAsUint64(0), "bad_val"));
  3213. ASSERT_EQ(file1_info.file_path, file1);
  3214. ASSERT_EQ(file1_info.num_entries, 50);
  3215. ASSERT_EQ(file1_info.smallest_key, Key(0));
  3216. ASSERT_EQ(file1_info.largest_key, Key(49));
  3217. ASSERT_EQ(db_->GetLatestSequenceNumber(), 0U);
  3218. // Add file using file path
  3219. ASSERT_OK(IngestExternalUDTFile({file1}));
  3220. ASSERT_EQ(db_->GetLatestSequenceNumber(), 0U);
  3221. // Read ingested file: all data contain minimum timestamps.
  3222. for (int k = 0; k < 50; k++) {
  3223. VerifyValueAndTs(Key(k), EncodeAsUint64(0),
  3224. Key(k) + "_val" + std::to_string(0), EncodeAsUint64(0));
  3225. }
  3226. // file2.sst [50, 200)
  3227. // Put [key=k, ts=0, value=k_val0] for k in [50, 200)
  3228. // RangeDelete[start_key=75, end_key=125, ts=0]
  3229. std::string file2 = sst_files_dir_ + "file2.sst";
  3230. int range_del_begin = 75, range_del_end = 125;
  3231. ASSERT_OK(sst_file_writer.Open(file2));
  3232. for (int k = 50; k < 200; k++) {
  3233. // All these timestamps will later be effectively 0
  3234. ASSERT_OK(
  3235. sst_file_writer.Put(Key(k), EncodeAsUint64(0), Key(k) + "_val0"));
  3236. }
  3237. ASSERT_OK(sst_file_writer.DeleteRange(
  3238. Key(range_del_begin), Key(range_del_end), EncodeAsUint64(0)));
  3239. ExternalSstFileInfo file2_info;
  3240. ASSERT_OK(sst_file_writer.Finish(&file2_info));
  3241. // Current file size should be non-zero after success write.
  3242. ASSERT_GT(sst_file_writer.FileSize(), 0);
  3243. ASSERT_EQ(file2_info.file_path, file2);
  3244. ASSERT_EQ(file2_info.num_entries, 150);
  3245. ASSERT_EQ(file2_info.smallest_key, Key(50));
  3246. ASSERT_EQ(file2_info.largest_key, Key(199));
  3247. ASSERT_EQ(file2_info.num_range_del_entries, 1);
  3248. ASSERT_EQ(file2_info.smallest_range_del_key, Key(range_del_begin));
  3249. ASSERT_EQ(file2_info.largest_range_del_key, Key(range_del_end));
  3250. // Add file using file path
  3251. ASSERT_OK(IngestExternalUDTFile({file2}));
  3252. ASSERT_EQ(db_->GetLatestSequenceNumber(), 0U);
  3253. // Range deletion covering point data in the same file is over-written.
  3254. for (int k = 50; k < 200; k++) {
  3255. VerifyValueAndTs(Key(k), EncodeAsUint64(0), Key(k) + "_val0",
  3256. EncodeAsUint64(0));
  3257. }
  3258. // file3.sst [100, 200), key range overlap with db
  3259. std::string file3 = sst_files_dir_ + "file3.sst";
  3260. ASSERT_OK(sst_file_writer.Open(file3));
  3261. for (int k = 100; k < 200; k++) {
  3262. ASSERT_OK(
  3263. sst_file_writer.Put(Key(k), EncodeAsUint64(0), Key(k) + "_val0"));
  3264. }
  3265. ExternalSstFileInfo file3_info;
  3266. ASSERT_OK(sst_file_writer.Finish(&file3_info));
  3267. ASSERT_EQ(file3_info.file_path, file3);
  3268. ASSERT_EQ(file3_info.num_entries, 100);
  3269. ASSERT_EQ(file3_info.smallest_key, Key(100));
  3270. ASSERT_EQ(file3_info.largest_key, Key(199));
  3271. // In UDT mode, file with overlapping key range cannot be ingested.
  3272. ASSERT_NOK(IngestExternalUDTFile({file3}));
  3273. ASSERT_NOK(IngestExternalUDTFile({file3}, /*allow_global_seqno*/ false));
  3274. // Write [0, 50)
  3275. // Write to DB newer versions to cover ingested data and move sequence
  3276. // number forward.
  3277. for (int k = 0; k < 50; k++) {
  3278. for (int version = 1; version < 3; version++) {
  3279. ASSERT_OK(dbfull()->Put(WriteOptions(), Key(k), EncodeAsUint64(version),
  3280. Key(k) + "_val" + std::to_string(version)));
  3281. }
  3282. }
  3283. // Read three versions (1 from ingested, 2 from live writes)
  3284. for (int k = 0; k < 50; k++) {
  3285. for (int version = 0; version < 3; version++) {
  3286. VerifyValueAndTs(Key(k), EncodeAsUint64(version),
  3287. Key(k) + "_val" + std::to_string(version),
  3288. EncodeAsUint64(version));
  3289. }
  3290. }
  3291. SequenceNumber seq_num_before_ingestion = db_->GetLatestSequenceNumber();
  3292. ASSERT_GT(seq_num_before_ingestion, 0U);
  3293. // file4.sst [200, 250)
  3294. std::string file4 = sst_files_dir_ + "file4.sst";
  3295. ASSERT_OK(sst_file_writer.Open(file4));
  3296. for (int k = 200; k < 250; k++) {
  3297. ASSERT_OK(
  3298. sst_file_writer.Put(Key(k), EncodeAsUint64(0), Key(k) + "_val"));
  3299. }
  3300. ExternalSstFileInfo file4_info;
  3301. ASSERT_OK(sst_file_writer.Finish(&file4_info));
  3302. // Current file size should be non-zero after success write.
  3303. ASSERT_GT(sst_file_writer.FileSize(), 0);
  3304. ASSERT_EQ(file4_info.file_path, file4);
  3305. ASSERT_EQ(file4_info.num_entries, 50);
  3306. ASSERT_EQ(file4_info.smallest_key, Key(200));
  3307. ASSERT_EQ(file4_info.largest_key, Key(249));
  3308. ASSERT_EQ(file4_info.num_range_del_entries, 0);
  3309. ASSERT_EQ(file4_info.smallest_range_del_key, "");
  3310. ASSERT_EQ(file4_info.largest_range_del_key, "");
  3311. ASSERT_OK(IngestExternalUDTFile({file4}));
  3312. // Ingested files do not overlap with db, they can always have global seqno
  3313. // 0 assigned.
  3314. ASSERT_EQ(db_->GetLatestSequenceNumber(), seq_num_before_ingestion);
  3315. DestroyAndRecreateExternalSSTFilesDir();
  3316. } while (ChangeOptions(kSkipPlainTable | kSkipFIFOCompaction |
  3317. kRangeDelSkipConfigs));
  3318. }
  3319. INSTANTIATE_TEST_CASE_P(ExternalSSTFileTest, ExternalSSTFileTest,
  3320. testing::Combine(testing::Bool(), testing::Bool()));
  3321. class IngestDBGeneratedFileTest
  3322. : public ExternalSSTFileTestBase,
  3323. public ::testing::WithParamInterface<std::tuple<bool, bool>> {
  3324. public:
  3325. IngestDBGeneratedFileTest() {
  3326. ingest_opts.allow_db_generated_files = true;
  3327. ingest_opts.link_files = std::get<0>(GetParam());
  3328. ingest_opts.verify_checksums_before_ingest = std::get<1>(GetParam());
  3329. ingest_opts.snapshot_consistency = false;
  3330. }
  3331. protected:
  3332. IngestExternalFileOptions ingest_opts;
  3333. };
  3334. INSTANTIATE_TEST_CASE_P(BasicMultiConfig, IngestDBGeneratedFileTest,
  3335. testing::Combine(testing::Bool(), testing::Bool()));
  3336. TEST_P(IngestDBGeneratedFileTest, FailureCase) {
  3337. if (encrypted_env_ && ingest_opts.link_files) {
  3338. // FIXME: should fail ingestion or support this combination.
  3339. ROCKSDB_GTEST_SKIP(
  3340. "Encrypted env and link_files do not work together, as we reopen the "
  3341. "file after linking it which appends an extra encryption prefix.");
  3342. return;
  3343. }
  3344. // Ingesting overlapping data should always fail.
  3345. do {
  3346. SCOPED_TRACE("option_config_ = " + std::to_string(option_config_));
  3347. Options options = CurrentOptions();
  3348. CreateAndReopenWithCF({"toto"}, options);
  3349. // Fill CFs with overlapping keys. Will try to ingest CF1 into default CF.
  3350. for (int k = 0; k < 50; ++k) {
  3351. ASSERT_OK(Put(Key(k), "default_cf_" + Key(k)));
  3352. }
  3353. for (int k = 49; k < 100; ++k) {
  3354. ASSERT_OK(Put(1, Key(k), "cf1_" + Key(k)));
  3355. }
  3356. ASSERT_OK(Flush(/*cf=*/1));
  3357. Status s;
  3358. CompactRangeOptions cro;
  3359. cro.bottommost_level_compaction =
  3360. BottommostLevelCompaction::kForceOptimized;
  3361. ASSERT_OK(db_->CompactRange(cro, handles_[1], nullptr, nullptr));
  3362. std::vector<LiveFileMetaData> live_meta;
  3363. std::vector<std::string> to_ingest_files;
  3364. db_->GetLiveFilesMetaData(&live_meta);
  3365. ASSERT_EQ(live_meta.size(), 1);
  3366. ASSERT_EQ(live_meta[0].column_family_name, "toto");
  3367. ASSERT_EQ(0, live_meta[0].largest_seqno);
  3368. to_ingest_files.emplace_back(live_meta[0].directory + "/" +
  3369. live_meta[0].relative_filename);
  3370. // Ingesting a DB generated file with allow_db_generated_files = false
  3371. ingest_opts.allow_db_generated_files = false;
  3372. s = db_->IngestExternalFile(to_ingest_files, ingest_opts);
  3373. ASSERT_TRUE(s.ToString().find("External file version not found") !=
  3374. std::string::npos);
  3375. ASSERT_NOK(s);
  3376. const std::string err =
  3377. "An ingested file overlaps with existing data in the DB and has been "
  3378. "assigned a non-zero sequence number";
  3379. ingest_opts.allow_db_generated_files = true;
  3380. s = db_->IngestExternalFile(to_ingest_files, ingest_opts);
  3381. ASSERT_TRUE(s.ToString().find(err) != std::string::npos);
  3382. ASSERT_NOK(s);
  3383. if (options.num_levels > 1) {
  3384. ingest_opts.fail_if_not_bottommost_level = true;
  3385. s = db_->IngestExternalFile(to_ingest_files, ingest_opts);
  3386. ASSERT_NOK(s);
  3387. ASSERT_TRUE(s.ToString().find("Files cannot be ingested to Lmax") !=
  3388. std::string::npos);
  3389. ingest_opts.fail_if_not_bottommost_level = false;
  3390. }
  3391. ingest_opts.write_global_seqno = true;
  3392. s = db_->IngestExternalFile(to_ingest_files, ingest_opts);
  3393. ASSERT_TRUE(s.ToString().find("write_global_seqno is deprecated and does "
  3394. "not work with allow_db_generated_files") !=
  3395. std::string::npos);
  3396. ASSERT_NOK(s);
  3397. ingest_opts.write_global_seqno = false;
  3398. // Delete the overlapping key.
  3399. ASSERT_OK(db_->Delete(WriteOptions(), handles_[1], Key(49)));
  3400. ASSERT_OK(db_->CompactRange(cro, handles_[1], nullptr, nullptr));
  3401. live_meta.clear();
  3402. db_->GetLiveFilesMetaData(&live_meta);
  3403. bool cf1_file_found = false;
  3404. for (const auto& f : live_meta) {
  3405. if (f.column_family_name == "toto") {
  3406. ASSERT_FALSE(cf1_file_found);
  3407. cf1_file_found = true;
  3408. ASSERT_EQ(0, f.largest_seqno);
  3409. to_ingest_files[0] = f.directory + "/" + f.relative_filename;
  3410. }
  3411. }
  3412. ASSERT_TRUE(cf1_file_found);
  3413. const Snapshot* snapshot = db_->GetSnapshot();
  3414. ingest_opts.snapshot_consistency = true;
  3415. s = db_->IngestExternalFile(to_ingest_files, ingest_opts);
  3416. // snapshot_consistency with snapshot will assign a newest sequence number.
  3417. ASSERT_TRUE(s.ToString().find(err) != std::string::npos);
  3418. ASSERT_NOK(s);
  3419. ingest_opts.snapshot_consistency = false;
  3420. ASSERT_OK(db_->IngestExternalFile(to_ingest_files, ingest_opts));
  3421. db_->ReleaseSnapshot(snapshot);
  3422. // Verify default CF content.
  3423. std::string val;
  3424. for (int k = 0; k < 100; ++k) {
  3425. ASSERT_OK(db_->Get(ReadOptions(), Key(k), &val));
  3426. if (k < 50) {
  3427. ASSERT_EQ(val, "default_cf_" + Key(k));
  3428. } else {
  3429. ASSERT_EQ(val, "cf1_" + Key(k));
  3430. }
  3431. }
  3432. } while (ChangeOptions(kSkipPlainTable | kSkipFIFOCompaction));
  3433. }
  3434. class IngestDBGeneratedFileTest2
  3435. : public ExternalSSTFileTestBase,
  3436. public ::testing::WithParamInterface<
  3437. std::tuple<bool, bool, bool, bool, bool>> {
  3438. public:
  3439. IngestDBGeneratedFileTest2() = default;
  3440. };
  3441. INSTANTIATE_TEST_CASE_P(VaryingOptions, IngestDBGeneratedFileTest2,
  3442. testing::Combine(testing::Bool(), testing::Bool(),
  3443. testing::Bool(), testing::Bool(),
  3444. testing::Bool()));
  3445. TEST_P(IngestDBGeneratedFileTest2, NotOverlapWithDB) {
  3446. // Use a separate column family to sort some data, generate multiple SST
  3447. // files. Then ingest these files into another column family or DB. The data
  3448. // to be ingested does not overlap with existing data.
  3449. IngestExternalFileOptions ingest_opts;
  3450. ingest_opts.allow_db_generated_files = true;
  3451. ingest_opts.snapshot_consistency = std::get<0>(GetParam());
  3452. ingest_opts.allow_global_seqno = std::get<1>(GetParam());
  3453. ingest_opts.allow_blocking_flush = std::get<2>(GetParam());
  3454. ingest_opts.fail_if_not_bottommost_level = std::get<3>(GetParam());
  3455. ingest_opts.link_files = std::get<4>(GetParam());
  3456. do {
  3457. SCOPED_TRACE("option_config_ = " + std::to_string(option_config_));
  3458. Options options = CurrentOptions();
  3459. // vector memtable for temp CF does not support concurrent write
  3460. options.allow_concurrent_memtable_write = false;
  3461. CreateAndReopenWithCF({"toto"}, options);
  3462. // non-empty bottommost level
  3463. WriteOptions wo;
  3464. for (int k = 0; k < 50; ++k) {
  3465. ASSERT_OK(db_->Put(wo, handles_[1], Key(k), "base_val_" + Key(k)));
  3466. }
  3467. ASSERT_OK(Flush());
  3468. CompactRangeOptions cro;
  3469. cro.bottommost_level_compaction =
  3470. BottommostLevelCompaction::kForceOptimized;
  3471. ASSERT_OK(db_->CompactRange(cro, handles_[1], nullptr, nullptr));
  3472. // non-empty memtable
  3473. for (int k = 50; k < 100; ++k) {
  3474. ASSERT_OK(db_->Put(wo, handles_[1], Key(k), "base_val_" + Key(k)));
  3475. }
  3476. // load external data to sort, generate multiple files
  3477. Options temp_cf_opts;
  3478. ColumnFamilyHandle* temp_cfh;
  3479. temp_cf_opts.target_file_size_base = 4 << 10;
  3480. temp_cf_opts.memtable_factory.reset(new VectorRepFactory());
  3481. temp_cf_opts.allow_concurrent_memtable_write = false;
  3482. temp_cf_opts.compaction_style = kCompactionStyleUniversal;
  3483. ASSERT_OK(db_->CreateColumnFamily(temp_cf_opts, "temp_cf", &temp_cfh));
  3484. Random rnd(301);
  3485. std::vector<std::string> expected_value;
  3486. expected_value.resize(100);
  3487. // Out of order insertion of keys from 100 to 199.
  3488. for (int k = 99; k >= 0; --k) {
  3489. expected_value[k] = rnd.RandomString(200);
  3490. ASSERT_OK(db_->Put(wo, temp_cfh, Key(k + 100), expected_value[k]));
  3491. }
  3492. ASSERT_OK(db_->CompactRange(cro, temp_cfh, nullptr, nullptr));
  3493. std::vector<std::string> sst_file_paths;
  3494. ColumnFamilyMetaData cf_meta;
  3495. db_->GetColumnFamilyMetaData(temp_cfh, &cf_meta);
  3496. ASSERT_GT(cf_meta.file_count, 1);
  3497. for (const auto& level_meta : cf_meta.levels) {
  3498. if (level_meta.level + 1 < temp_cf_opts.num_levels) {
  3499. ASSERT_EQ(0, level_meta.files.size());
  3500. } else {
  3501. ASSERT_GT(level_meta.files.size(), 1);
  3502. for (const auto& meta : level_meta.files) {
  3503. ASSERT_EQ(0, meta.largest_seqno);
  3504. sst_file_paths.emplace_back(meta.directory + "/" +
  3505. meta.relative_filename);
  3506. }
  3507. }
  3508. }
  3509. ASSERT_OK(
  3510. db_->IngestExternalFile(handles_[1], sst_file_paths, ingest_opts));
  3511. // Verify state of the CF1
  3512. ReadOptions ro;
  3513. std::string val;
  3514. for (int k = 0; k < 100; ++k) {
  3515. ASSERT_OK(db_->Get(ro, handles_[1], Key(k), &val));
  3516. ASSERT_EQ(val, "base_val_" + Key(k));
  3517. ASSERT_OK(db_->Get(ro, handles_[1], Key(100 + k), &val));
  3518. ASSERT_EQ(val, expected_value[k]);
  3519. }
  3520. // Ingest into another DB.
  3521. if (!encrypted_env_) {
  3522. // Ingestion between encrypted env and non-encrypted env won't work.
  3523. std::string db2_path = test::PerThreadDBPath("DB2");
  3524. Options db2_options;
  3525. db2_options.create_if_missing = true;
  3526. DB* db2 = nullptr;
  3527. ASSERT_OK(DB::Open(db2_options, db2_path, &db2));
  3528. // Write some base data.
  3529. expected_value.emplace_back(rnd.RandomString(100));
  3530. ASSERT_OK(db2->Put(WriteOptions(), Key(200), expected_value.back()));
  3531. ASSERT_OK(db2->CompactRange(cro, nullptr, nullptr));
  3532. expected_value.emplace_back(rnd.RandomString(100));
  3533. ASSERT_OK(db2->Put(WriteOptions(), Key(201), expected_value.back()));
  3534. ASSERT_OK(db2->IngestExternalFile({sst_file_paths}, ingest_opts));
  3535. {
  3536. std::unique_ptr<Iterator> iter{db2->NewIterator(ReadOptions())};
  3537. iter->SeekToFirst();
  3538. // The DB should have keys 100-199 from ingested files, and keys 200 and
  3539. // 201 from itself.
  3540. for (int k = 100; k <= 201; ++k, iter->Next()) {
  3541. ASSERT_TRUE(iter->Valid());
  3542. ASSERT_EQ(iter->key(), Key(k));
  3543. ASSERT_EQ(iter->value(), expected_value[k - 100]);
  3544. }
  3545. ASSERT_FALSE(iter->Valid());
  3546. ASSERT_OK(iter->status());
  3547. }
  3548. // Dropping the original CF should not affect db2, reopening it should not
  3549. // miss SST files.
  3550. ASSERT_OK(db_->DropColumnFamily(temp_cfh));
  3551. ASSERT_OK(db_->DestroyColumnFamilyHandle(temp_cfh));
  3552. ASSERT_OK(db2->Close());
  3553. delete db2;
  3554. ASSERT_OK(DB::Open(db2_options, db2_path, &db2));
  3555. ASSERT_OK(db2->Close());
  3556. delete db2;
  3557. ASSERT_OK(DestroyDB(db2_path, db2_options));
  3558. } else {
  3559. ASSERT_OK(db_->DropColumnFamily(temp_cfh));
  3560. ASSERT_OK(db_->DestroyColumnFamilyHandle(temp_cfh));
  3561. }
  3562. } while (ChangeOptions(kSkipPlainTable | kSkipFIFOCompaction));
  3563. }
  3564. TEST_P(IngestDBGeneratedFileTest2, NonZeroSeqno) {
  3565. // Test ingestion of DB-generated SST files that contain non-zero sequence
  3566. // numbers.
  3567. IngestExternalFileOptions ingest_opts;
  3568. ingest_opts.allow_db_generated_files = true;
  3569. // This only works since we are ingesting without snapshot
  3570. // Failure case will be tested below.
  3571. ingest_opts.snapshot_consistency = std::get<0>(GetParam());
  3572. ingest_opts.allow_global_seqno = std::get<1>(GetParam());
  3573. ingest_opts.allow_blocking_flush = std::get<2>(GetParam());
  3574. ingest_opts.fail_if_not_bottommost_level = std::get<3>(GetParam());
  3575. ingest_opts.link_files = std::get<4>(GetParam());
  3576. Random* rnd = Random::GetTLSInstance();
  3577. rnd->Reset(std::random_device{}());
  3578. std::ostringstream ingest_opts_trace;
  3579. ingest_opts_trace << "ingest_opts params: " << "snapshot_consistency="
  3580. << ingest_opts.snapshot_consistency << ", "
  3581. << "allow_global_seqno=" << ingest_opts.allow_global_seqno
  3582. << ", " << "allow_blocking_flush="
  3583. << ingest_opts.allow_blocking_flush << ", "
  3584. << "fail_if_not_bottommost_level="
  3585. << ingest_opts.fail_if_not_bottommost_level << ", "
  3586. << "link_files=" << ingest_opts.link_files;
  3587. SCOPED_TRACE(ingest_opts_trace.str());
  3588. do {
  3589. SCOPED_TRACE("option_config_ = " + std::to_string(option_config_));
  3590. Options options = CurrentOptions();
  3591. options.statistics = CreateDBStatistics();
  3592. options.allow_concurrent_memtable_write =
  3593. false; // Required for VectorRepFactory
  3594. CreateAndReopenWithCF({"non_overlap", "overlap"}, options);
  3595. ColumnFamilyHandle* non_overlap_cf = handles_[1];
  3596. ColumnFamilyHandle* overlap_cf = handles_[2];
  3597. std::vector<std::string> expected_values;
  3598. expected_values.resize(100);
  3599. WriteOptions wo;
  3600. // Setup target CF with non-overlapping base data Key1 and Key99
  3601. // Will ingest keys [1, 98] below.
  3602. expected_values[0] = rnd->RandomString(100);
  3603. ASSERT_OK(db_->Put(wo, non_overlap_cf, Key(0), expected_values[0]));
  3604. ASSERT_OK(db_->Flush({}, non_overlap_cf));
  3605. expected_values[99] = rnd->RandomString(100);
  3606. ASSERT_OK(db_->Put(wo, non_overlap_cf, Key(99), expected_values[99]));
  3607. // Set up overlapping cf
  3608. ASSERT_OK(db_->Put(wo, overlap_cf, Key(50), rnd->RandomString(100)));
  3609. // Create temp CF/DB
  3610. Options temp_cf_opts;
  3611. ColumnFamilyHandle* temp_cfh = nullptr;
  3612. DB* from_db = nullptr;
  3613. std::string temp_db_name;
  3614. // Using a separate DB also validates that latest sequence number
  3615. // of target db is updated after ingestion (to the max sequence number
  3616. // in ingested files).
  3617. const bool use_temp_db = rnd->OneIn(2);
  3618. SCOPED_TRACE("use_temp_db: " + std::to_string(use_temp_db));
  3619. std::vector<std::string> sst_file_paths;
  3620. // optional L5: files in key range [70, 98]
  3621. // L6: files in key range [1, 79]
  3622. temp_cf_opts.target_file_size_base =
  3623. 20 << 10; // Small files to create multiple SSTs
  3624. temp_cf_opts.num_levels = 7;
  3625. temp_cf_opts.disable_auto_compactions = true; // Manually set up LSM
  3626. temp_cf_opts.env = options.env;
  3627. if (use_temp_db) {
  3628. temp_cf_opts.create_if_missing = true;
  3629. temp_db_name = dbname_ + "/temp_db_" + std::to_string(rnd->Next());
  3630. ASSERT_OK(DB::Open(temp_cf_opts, temp_db_name, &from_db));
  3631. temp_cfh = from_db->DefaultColumnFamily();
  3632. } else {
  3633. from_db = db_;
  3634. ASSERT_OK(
  3635. from_db->CreateColumnFamily(temp_cf_opts, "temp_cf", &temp_cfh));
  3636. }
  3637. // Use snapshot to ensure non-zero sequence numbers after compaction
  3638. const Snapshot* snapshot = from_db->GetSnapshot();
  3639. for (int k = 1; k < 99; ++k) {
  3640. expected_values[k] = rnd->RandomString(2000);
  3641. ASSERT_OK(from_db->Put(wo, temp_cfh, Key(k), expected_values[k]));
  3642. }
  3643. ASSERT_OK(from_db->Flush({}, temp_cfh));
  3644. CompactRangeOptions cro;
  3645. cro.bottommost_level_compaction =
  3646. BottommostLevelCompaction::kForceOptimized;
  3647. ASSERT_OK(from_db->CompactRange(cro, temp_cfh, nullptr, nullptr));
  3648. ASSERT_GT(NumTableFilesAtLevel(6, temp_cfh, from_db), 1);
  3649. const bool multi_level_ingestion = rnd->OneIn(2);
  3650. SCOPED_TRACE("Multi-level ingestion: " +
  3651. std::to_string(multi_level_ingestion));
  3652. if (multi_level_ingestion) {
  3653. for (int k = 80; k < 99; ++k) {
  3654. expected_values[k] = rnd->RandomString(500);
  3655. ASSERT_OK(from_db->Put(wo, temp_cfh, Key(k), expected_values[k]));
  3656. }
  3657. ASSERT_OK(from_db->Flush({}, temp_cfh));
  3658. // Do some overwrites, and overlap with previous L0 to avoid trivial move
  3659. for (int k = 70; k < 82; ++k) {
  3660. expected_values[k] = rnd->RandomString(500);
  3661. ASSERT_OK(from_db->Put(wo, temp_cfh, Key(k), expected_values[k]));
  3662. }
  3663. ASSERT_OK(from_db->Flush({}, temp_cfh));
  3664. if (rnd->OneIn(2)) {
  3665. MoveFilesToLevel(5, temp_cfh, from_db);
  3666. ASSERT_GT(NumTableFilesAtLevel(5, temp_cfh, from_db), 0);
  3667. }
  3668. ASSERT_GT(NumTableFilesAtLevel(6, temp_cfh, from_db), 0);
  3669. }
  3670. SCOPED_TRACE("LSM of from_db " + FilesPerLevel(temp_cfh, from_db));
  3671. ColumnFamilyMetaData cf_meta;
  3672. from_db->GetColumnFamilyMetaData(temp_cfh, &cf_meta);
  3673. // Iterate in reverse since IngestExternalFiles expect files to be ordered
  3674. // from old to new
  3675. for (auto level_meta = cf_meta.levels.rbegin();
  3676. level_meta != cf_meta.levels.rend(); ++level_meta) {
  3677. // L0 files need to be added in reverse order.
  3678. for (auto file_meta = level_meta->files.rbegin();
  3679. file_meta != level_meta->files.rend(); ++file_meta) {
  3680. // Validate that files contain non-zero sequence numbers
  3681. ASSERT_GT(file_meta->smallest_seqno, 0);
  3682. ASSERT_GE(file_meta->largest_seqno, file_meta->smallest_seqno);
  3683. sst_file_paths.emplace_back(file_meta->directory + "/" +
  3684. file_meta->relative_filename);
  3685. }
  3686. }
  3687. from_db->ReleaseSnapshot(snapshot);
  3688. Status s;
  3689. // Perform ingestion and validate results
  3690. if (multi_level_ingestion && options.num_levels > 1) {
  3691. // fail_if_bottommost requres ingesting all files into the last level,
  3692. // so it fails if we are assiging files to multiple levels.
  3693. ingest_opts.fail_if_not_bottommost_level = true;
  3694. s = db_->IngestExternalFile(non_overlap_cf, sst_file_paths, ingest_opts);
  3695. ASSERT_NOK(s);
  3696. ASSERT_TRUE(s.ToString().find("Files cannot be ingested to Lmax") !=
  3697. std::string::npos);
  3698. ingest_opts.fail_if_not_bottommost_level = false;
  3699. }
  3700. if (ingest_opts.snapshot_consistency) {
  3701. // snapshot_consisteny requires global sequence number assignment to
  3702. // ingested files if there is any live snapshot.
  3703. snapshot = db_->GetSnapshot();
  3704. s = db_->IngestExternalFile(non_overlap_cf, sst_file_paths, ingest_opts);
  3705. ASSERT_NOK(s);
  3706. ASSERT_TRUE(s.ToString().find(
  3707. "An ingested file overlaps with existing data in the DB and has been "
  3708. "assigned a non-zero sequence number"));
  3709. db_->ReleaseSnapshot(snapshot);
  3710. }
  3711. std::atomic<int> file_scan_count{0};
  3712. SyncPoint::GetInstance()->SetCallBack(
  3713. "ExternalSstFileIngestionJob::GetSeqnoBoundaryForFile:FileScan",
  3714. [&](void* /*arg*/) { file_scan_count++; });
  3715. SyncPoint::GetInstance()->EnableProcessing();
  3716. ASSERT_OK(
  3717. db_->IngestExternalFile(non_overlap_cf, sst_file_paths, ingest_opts));
  3718. SyncPoint::GetInstance()->DisableProcessing();
  3719. SyncPoint::GetInstance()->ClearAllCallBacks();
  3720. EXPECT_EQ(file_scan_count, 0);
  3721. // Validate ingested data.
  3722. ReadOptions ro;
  3723. std::string val;
  3724. for (int k = 0; k < 100; ++k) {
  3725. s = db_->Get(ro, handles_[1], Key(k), &val);
  3726. ASSERT_OK(s) << "Should find ingested key " << Key(k);
  3727. ASSERT_EQ(val, expected_values[k]) << "key: " << Key(k);
  3728. }
  3729. // Overlap with data in the CF
  3730. if (ingest_opts.allow_blocking_flush) {
  3731. s = db_->IngestExternalFile(overlap_cf, sst_file_paths, ingest_opts);
  3732. ASSERT_NOK(s);
  3733. if (ingest_opts.fail_if_not_bottommost_level) {
  3734. ASSERT_TRUE(s.ToString().find("Files cannot be ingested to Lmax") !=
  3735. std::string::npos)
  3736. << s.ToString();
  3737. } else {
  3738. ASSERT_TRUE(s.ToString().find("An ingested file overlaps with existing "
  3739. "data in the DB and has been "
  3740. "assigned a non-zero sequence number") !=
  3741. std::string::npos)
  3742. << s.ToString();
  3743. }
  3744. }
  3745. // Cleanup
  3746. // FIXME: Without this, the test triggers some data race between dropping
  3747. // CF and background compaction.
  3748. ASSERT_OK(db_->WaitForCompact({}));
  3749. if (use_temp_db) {
  3750. ASSERT_OK(from_db->Close());
  3751. delete from_db;
  3752. ASSERT_OK(DestroyDB(temp_db_name, temp_cf_opts));
  3753. } else {
  3754. ASSERT_OK(db_->DropColumnFamily(temp_cfh));
  3755. ASSERT_OK(db_->DestroyColumnFamilyHandle(temp_cfh));
  3756. }
  3757. } while (ChangeOptions(kSkipPlainTable | kSkipFIFOCompaction));
  3758. }
  3759. std::string GenSecondaryKey(const std::string& pk, const std::string& val) {
  3760. return "index_" + val + "_" + pk;
  3761. };
  3762. TEST_P(IngestDBGeneratedFileTest2, ZeroAndNonZeroSeqno) {
  3763. // Test ingestion of SST files with zero and with non-zero sequence numbers.
  3764. // Generate data using a temp CF and a temp DB:
  3765. // 1. Temp CF with cf_allow_ingest_behind enabled to preserve non-zero seqno.
  3766. // 2. Temp DB with everything compacted to have zero seqno.
  3767. // Then ingest both types of files together into a target CF.
  3768. // This mimics a user case where temp DB contains data read from a
  3769. // snapshot while temp CF contains live writes after a snapshot is taken.
  3770. IngestExternalFileOptions ingest_opts;
  3771. ingest_opts.allow_db_generated_files = true;
  3772. ingest_opts.snapshot_consistency = std::get<0>(GetParam());
  3773. ingest_opts.allow_global_seqno = std::get<1>(GetParam());
  3774. ingest_opts.allow_blocking_flush = std::get<2>(GetParam());
  3775. ingest_opts.fail_if_not_bottommost_level = std::get<3>(GetParam());
  3776. ingest_opts.link_files = std::get<4>(GetParam());
  3777. Random* rnd = Random::GetTLSInstance();
  3778. do {
  3779. SCOPED_TRACE("option_config_ = " + std::to_string(option_config_));
  3780. Options options = CurrentOptions();
  3781. options.allow_concurrent_memtable_write = false;
  3782. // Force more flushes/compactions and more files to be generated
  3783. options.target_file_size_base = 1 << 10; // 1KB
  3784. options.max_bytes_for_level_base = 2 << 10; // 2KB
  3785. options.max_bytes_for_level_multiplier = 2;
  3786. options.level0_file_num_compaction_trigger = 2;
  3787. options.level_compaction_dynamic_level_bytes = true;
  3788. DestroyAndReopen(options);
  3789. CreateAndReopenWithCF({"target_cf"}, options);
  3790. auto* target_cfh = handles_[1];
  3791. Options live_write_cf_opts = options;
  3792. live_write_cf_opts.memtable_factory.reset(new VectorRepFactory());
  3793. live_write_cf_opts.compaction_style = kCompactionStyleUniversal;
  3794. live_write_cf_opts.cf_allow_ingest_behind = true;
  3795. live_write_cf_opts.num_levels = 50;
  3796. ColumnFamilyHandle* live_write_cfh;
  3797. ASSERT_OK(db_->CreateColumnFamily(live_write_cf_opts, "live_write_cf",
  3798. &live_write_cfh));
  3799. // Expected value and key
  3800. std::map<std::string, std::string> expected;
  3801. std::unordered_set<std::string> deleted;
  3802. std::stringstream debug_info;
  3803. // Setup base data in target CF, will ingest keys with different prefixes
  3804. // so they don't overlap with the base data.
  3805. WriteOptions wo;
  3806. for (int k = 0; k < 100; ++k) {
  3807. int random_val = rnd->Uniform(20);
  3808. expected[Key(k)] = std::to_string(random_val);
  3809. ASSERT_OK(db_->Put(wo, target_cfh, Key(k), expected[Key(k)]));
  3810. // Force flush every 20 keys to create multiple SST files
  3811. if (rnd->OneIn(20)) {
  3812. ASSERT_OK(db_->Flush({}, target_cfh));
  3813. debug_info << "Flush after " << k
  3814. << ", LSM state: " << FilesPerLevel(target_cfh) << "\n";
  3815. }
  3816. }
  3817. // Temp DB for snapshot data
  3818. Options temp_db_opts;
  3819. temp_db_opts.create_if_missing = true;
  3820. temp_db_opts.target_file_size_base = 1 << 10;
  3821. temp_db_opts.write_buffer_size = 1 << 10;
  3822. temp_db_opts.memtable_factory.reset(new VectorRepFactory());
  3823. temp_db_opts.allow_concurrent_memtable_write = false;
  3824. temp_db_opts.compaction_style = kCompactionStyleUniversal;
  3825. temp_db_opts.env = env_;
  3826. temp_db_opts.num_levels = 7;
  3827. std::string temp_db_name =
  3828. dbname_ + "/temp_db_" + std::to_string(rnd->Next());
  3829. DB* temp_db = nullptr;
  3830. ASSERT_OK(DB::Open(temp_db_opts, temp_db_name, &temp_db));
  3831. const Snapshot* snapshot = db_->GetSnapshot();
  3832. ReadOptions ro;
  3833. ro.snapshot = snapshot;
  3834. ro.total_order_seek = true;
  3835. std::unique_ptr<Iterator> iter{db_->NewIterator(ro, target_cfh)};
  3836. // transform data read from snapshot and write to temp DB
  3837. // Varying the number of files in temp DB.
  3838. const int kValSize = rnd->Uniform(200);
  3839. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  3840. std::string key = iter->key().ToString();
  3841. std::string value = iter->value().ToString();
  3842. std::string sk = GenSecondaryKey(key, value);
  3843. // Usually value is empty, here we use a larger value to generate
  3844. // multiple SST files in temp_db.
  3845. std::string sk_val = rnd->RandomString(kValSize);
  3846. ASSERT_OK(temp_db->Put(wo, sk, sk_val));
  3847. expected[sk] = sk_val;
  3848. debug_info << "Snapshot data: " << sk << " -> \n";
  3849. }
  3850. ASSERT_OK(iter->status());
  3851. // Do some live writes into target CF and live write CF.
  3852. for (int i = 0; i < 10; ++i) {
  3853. WriteBatch wb;
  3854. for (int j = 0; j < 5; ++j) {
  3855. std::string key = Key(rnd->Uniform(100));
  3856. std::string old_val = expected[key];
  3857. // Value range is 0-19, allow some PK to have the same value.
  3858. int random_val = rnd->Uniform(20);
  3859. std::string new_val = std::to_string(random_val);
  3860. std::string old_index_key = GenSecondaryKey(key, old_val);
  3861. std::string new_index_key = GenSecondaryKey(key, new_val);
  3862. ASSERT_OK(wb.SingleDelete(live_write_cfh, old_index_key));
  3863. std::string sk_val = rnd->RandomString(kValSize);
  3864. ASSERT_OK(wb.Put(live_write_cfh, new_index_key, sk_val));
  3865. ASSERT_OK(wb.Put(target_cfh, key, new_val));
  3866. expected[key] = new_val;
  3867. expected.erase(old_index_key);
  3868. expected[new_index_key] = sk_val;
  3869. deleted.insert(old_index_key);
  3870. deleted.erase(new_index_key);
  3871. debug_info << "Live write: SD " << old_index_key << "\n";
  3872. debug_info << "Live write: " << key << " -> " << new_val << "\n";
  3873. debug_info << "Live write: " << new_index_key << " -> \n";
  3874. }
  3875. ASSERT_OK(db_->Write(wo, &wb));
  3876. if (rnd->OneIn(3)) {
  3877. debug_info << "Flush after " << i << " live writes\n";
  3878. ASSERT_OK(db_->Flush({}, live_write_cfh));
  3879. }
  3880. }
  3881. iter.reset();
  3882. db_->ReleaseSnapshot(snapshot);
  3883. // Compact temp_db to ensure zero sequence numbers
  3884. CompactRangeOptions cro;
  3885. cro.bottommost_level_compaction = BottommostLevelCompaction::kForce;
  3886. ASSERT_OK(temp_db->CompactRange(cro, nullptr, nullptr));
  3887. SCOPED_TRACE("Temp DB LSM: " +
  3888. FilesPerLevel(temp_db->DefaultColumnFamily(), temp_db));
  3889. // Base data from snapshot
  3890. std::vector<std::string> sst_file_paths_zero_seqno;
  3891. // Collect SST file paths with zero sequence numbers
  3892. ASSERT_OK(temp_db->DisableFileDeletions());
  3893. ColumnFamilyMetaData cf_meta_temp_db;
  3894. temp_db->GetColumnFamilyMetaData(&cf_meta_temp_db);
  3895. for (const auto& level_meta : cf_meta_temp_db.levels) {
  3896. if (level_meta.level == 6) {
  3897. for (const auto& file_meta : level_meta.files) {
  3898. // Verify files have zero sequence numbers
  3899. ASSERT_EQ(0, file_meta.largest_seqno)
  3900. << "File " << file_meta.relative_filename
  3901. << " should have zero sequence number\n"
  3902. << debug_info.str();
  3903. sst_file_paths_zero_seqno.emplace_back(file_meta.directory + "/" +
  3904. file_meta.relative_filename);
  3905. }
  3906. } else {
  3907. // All files should be in L6
  3908. ASSERT_EQ(0, level_meta.files.size()) << debug_info.str();
  3909. }
  3910. }
  3911. // Flush remaining catch up writes in memtable
  3912. ASSERT_OK(db_->Flush({}, live_write_cfh));
  3913. SCOPED_TRACE("LSM of live write cfh " + FilesPerLevel(live_write_cfh));
  3914. // Collect SST file paths with non-zero sequence numbers
  3915. ColumnFamilyMetaData live_write_cf_meta;
  3916. ASSERT_OK(db_->DisableFileDeletions());
  3917. db_->GetColumnFamilyMetaData(live_write_cfh, &live_write_cf_meta);
  3918. // Live writes after snapshot
  3919. std::vector<std::string> sst_file_paths_nonzero_seqno;
  3920. for (auto level_meta = live_write_cf_meta.levels.rbegin();
  3921. level_meta != live_write_cf_meta.levels.rend(); ++level_meta) {
  3922. // Reverse order is important for L0, where recent updates are ordered
  3923. // first
  3924. for (auto file_meta = level_meta->files.rbegin();
  3925. file_meta != level_meta->files.rend(); ++file_meta) {
  3926. sst_file_paths_nonzero_seqno.emplace_back(file_meta->directory + "/" +
  3927. file_meta->relative_filename);
  3928. ASSERT_GT(file_meta->smallest_seqno, 0) << debug_info.str();
  3929. }
  3930. if (level_meta->level == 49) {
  3931. // Ingest behind does not compact to the last level
  3932. ASSERT_EQ(level_meta->files.size(), 0) << debug_info.str();
  3933. }
  3934. }
  3935. ASSERT_GT(sst_file_paths_zero_seqno.size(), 0) << debug_info.str();
  3936. ASSERT_GT(sst_file_paths_nonzero_seqno.size(), 0) << debug_info.str();
  3937. // Combine all SST file paths.
  3938. // File ingestion takes files from old to new.
  3939. std::vector<std::string> all_sst_files;
  3940. all_sst_files.insert(all_sst_files.end(), sst_file_paths_zero_seqno.begin(),
  3941. sst_file_paths_zero_seqno.end());
  3942. all_sst_files.insert(all_sst_files.end(),
  3943. sst_file_paths_nonzero_seqno.begin(),
  3944. sst_file_paths_nonzero_seqno.end());
  3945. if (ingest_opts.fail_if_not_bottommost_level && options.num_levels > 1) {
  3946. // overlapping files will be ingested into different levels, including non
  3947. // Lmax
  3948. Status s =
  3949. db_->IngestExternalFile(target_cfh, all_sst_files, ingest_opts);
  3950. ASSERT_NOK(s);
  3951. ASSERT_TRUE(s.ToString().find("Files cannot be ingested to Lmax") !=
  3952. std::string::npos);
  3953. } else {
  3954. ASSERT_OK(
  3955. db_->IngestExternalFile(target_cfh, all_sst_files, ingest_opts));
  3956. debug_info << "Zero seqno files: " << sst_file_paths_zero_seqno.size()
  3957. << "\nNon-zero seqno files: "
  3958. << sst_file_paths_nonzero_seqno.size() << "\n";
  3959. SCOPED_TRACE("Debug info:\n" + debug_info.str());
  3960. VerifyDBFromMap(expected, nullptr, false, nullptr, target_cfh, &deleted);
  3961. }
  3962. // clean up
  3963. ASSERT_OK(db_->EnableFileDeletions());
  3964. ASSERT_OK(temp_db->EnableFileDeletions());
  3965. // FIXME: Without this, the test triggers some data race between dropping
  3966. // CF and background compaction.
  3967. ASSERT_OK(db_->WaitForCompact({}));
  3968. ASSERT_OK(db_->DropColumnFamily(live_write_cfh));
  3969. ASSERT_OK(db_->DestroyColumnFamilyHandle(live_write_cfh));
  3970. ASSERT_OK(temp_db->Close());
  3971. delete temp_db;
  3972. ASSERT_OK(DestroyDB(temp_db_name, temp_db_opts));
  3973. } while (ChangeOptions(kSkipPlainTable | kSkipFIFOCompaction));
  3974. }
  3975. } // namespace ROCKSDB_NAMESPACE
  3976. int main(int argc, char** argv) {
  3977. ROCKSDB_NAMESPACE::port::InstallStackTraceHandler();
  3978. ::testing::InitGoogleTest(&argc, argv);
  3979. return RUN_ALL_TESTS();
  3980. }