db_test.cc 260 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  7. // Use of this source code is governed by a BSD-style license that can be
  8. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  9. // Introduction of SyncPoint effectively disabled building and running this test
  10. // in Release build.
  11. // which is a pity, it is a good test
  12. #include <fcntl.h>
  13. #include <algorithm>
  14. #include <set>
  15. #include <thread>
  16. #include <unordered_set>
  17. #include <utility>
  18. #ifndef OS_WIN
  19. #include <unistd.h>
  20. #endif
  21. #ifdef OS_SOLARIS
  22. #include <alloca.h>
  23. #endif
  24. #include "cache/lru_cache.h"
  25. #include "db/attribute_group_iterator_impl.h"
  26. #include "db/blob/blob_index.h"
  27. #include "db/blob/blob_log_format.h"
  28. #include "db/db_impl/db_impl.h"
  29. #include "db/db_test_util.h"
  30. #include "db/dbformat.h"
  31. #include "db/job_context.h"
  32. #include "db/version_set.h"
  33. #include "db/write_batch_internal.h"
  34. #include "env/mock_env.h"
  35. #include "file/filename.h"
  36. #include "monitoring/thread_status_util.h"
  37. #include "port/port.h"
  38. #include "port/stack_trace.h"
  39. #include "rocksdb/cache.h"
  40. #include "rocksdb/compaction_filter.h"
  41. #include "rocksdb/convenience.h"
  42. #include "rocksdb/db.h"
  43. #include "rocksdb/env.h"
  44. #include "rocksdb/experimental.h"
  45. #include "rocksdb/filter_policy.h"
  46. #include "rocksdb/options.h"
  47. #include "rocksdb/perf_context.h"
  48. #include "rocksdb/slice.h"
  49. #include "rocksdb/slice_transform.h"
  50. #include "rocksdb/snapshot.h"
  51. #include "rocksdb/table.h"
  52. #include "rocksdb/table_properties.h"
  53. #include "rocksdb/thread_status.h"
  54. #include "rocksdb/types.h"
  55. #include "rocksdb/utilities/checkpoint.h"
  56. #include "rocksdb/utilities/optimistic_transaction_db.h"
  57. #include "rocksdb/utilities/write_batch_with_index.h"
  58. #include "table/block_based/block_based_table_factory.h"
  59. #include "table/mock_table.h"
  60. #include "test_util/sync_point.h"
  61. #include "test_util/testharness.h"
  62. #include "test_util/testutil.h"
  63. #include "util/compression.h"
  64. #include "util/defer.h"
  65. #include "util/mutexlock.h"
  66. #include "util/random.h"
  67. #include "util/rate_limiter_impl.h"
  68. #include "util/string_util.h"
  69. #include "utilities/merge_operators.h"
  70. namespace ROCKSDB_NAMESPACE {
  71. // Note that whole DBTest and its child classes disable fsync on files
  72. // and directories for speed.
  73. // If fsync needs to be covered in a test, put it in other places.
  74. class DBTest : public DBTestBase {
  75. public:
  76. DBTest() : DBTestBase("db_test", /*env_do_fsync=*/false) {}
  77. };
  78. class DBTestWithParam
  79. : public DBTest,
  80. public testing::WithParamInterface<std::tuple<uint32_t, bool>> {
  81. public:
  82. DBTestWithParam() {
  83. max_subcompactions_ = std::get<0>(GetParam());
  84. exclusive_manual_compaction_ = std::get<1>(GetParam());
  85. }
  86. // Required if inheriting from testing::WithParamInterface<>
  87. static void SetUpTestCase() {}
  88. static void TearDownTestCase() {}
  89. uint32_t max_subcompactions_;
  90. bool exclusive_manual_compaction_;
  91. };
  92. TEST_F(DBTest, MockEnvTest) {
  93. std::unique_ptr<MockEnv> env{MockEnv::Create(Env::Default())};
  94. Options options;
  95. options.create_if_missing = true;
  96. options.env = env.get();
  97. DB* db;
  98. const Slice keys[] = {Slice("aaa"), Slice("bbb"), Slice("ccc")};
  99. const Slice vals[] = {Slice("foo"), Slice("bar"), Slice("baz")};
  100. ASSERT_OK(DB::Open(options, "/dir/db", &db));
  101. for (size_t i = 0; i < 3; ++i) {
  102. ASSERT_OK(db->Put(WriteOptions(), keys[i], vals[i]));
  103. }
  104. for (size_t i = 0; i < 3; ++i) {
  105. std::string res;
  106. ASSERT_OK(db->Get(ReadOptions(), keys[i], &res));
  107. ASSERT_TRUE(res == vals[i]);
  108. }
  109. Iterator* iterator = db->NewIterator(ReadOptions());
  110. iterator->SeekToFirst();
  111. for (size_t i = 0; i < 3; ++i) {
  112. ASSERT_TRUE(iterator->Valid());
  113. ASSERT_TRUE(keys[i] == iterator->key());
  114. ASSERT_TRUE(vals[i] == iterator->value());
  115. iterator->Next();
  116. }
  117. ASSERT_TRUE(!iterator->Valid());
  118. ASSERT_OK(iterator->status());
  119. delete iterator;
  120. DBImpl* dbi = static_cast_with_check<DBImpl>(db);
  121. ASSERT_OK(dbi->TEST_FlushMemTable());
  122. for (size_t i = 0; i < 3; ++i) {
  123. std::string res;
  124. ASSERT_OK(db->Get(ReadOptions(), keys[i], &res));
  125. ASSERT_TRUE(res == vals[i]);
  126. }
  127. delete db;
  128. }
  129. TEST_F(DBTest, RequestIdPlumbingTest) {
  130. // test that request_id is passed to the filesystem, from
  131. // ReadOptions to IODebugContext
  132. Options options = CurrentOptions();
  133. options.env = env_;
  134. // Create a mock environment to capture IODebugContext during reads
  135. IODebugContext dbgCopy;
  136. const std::string* captured_request_id_dbg;
  137. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  138. "RandomAccessFileReader::Read:IODebugContext", [&](void* arg) {
  139. IODebugContext* dbg = static_cast<IODebugContext*>(arg);
  140. if (dbg == nullptr) {
  141. captured_request_id_dbg = nullptr;
  142. } else {
  143. captured_request_id_dbg = dbg->request_id;
  144. // Test IODebugContext assignment operator
  145. dbgCopy = *dbg;
  146. }
  147. });
  148. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  149. ASSERT_OK(Put("k1", "v1"));
  150. ASSERT_OK(Flush());
  151. // test request_id plumbing during a get
  152. {
  153. const std::string test_request_id = "test_request_id_123";
  154. ReadOptions read_opts;
  155. read_opts.request_id = &test_request_id;
  156. std::string value;
  157. ASSERT_OK(db_->Get(read_opts, "k1", &value));
  158. // Verify the request_id was propagated to the file system
  159. ASSERT_NE(captured_request_id_dbg, nullptr);
  160. ASSERT_EQ(*captured_request_id_dbg, test_request_id);
  161. ASSERT_NE(dbgCopy.request_id, nullptr);
  162. ASSERT_NE(dbgCopy.request_id, captured_request_id_dbg);
  163. ASSERT_EQ(*dbgCopy.request_id, test_request_id);
  164. }
  165. captured_request_id_dbg = nullptr;
  166. // test request_id plumbing during iterator seek
  167. ASSERT_OK(Put("k2", "v2"));
  168. ASSERT_OK(Flush());
  169. {
  170. ReadOptions read_opts;
  171. const std::string request_id = "test_request_id_456";
  172. read_opts.request_id = &request_id;
  173. std::unique_ptr<Iterator> iter(db_->NewIterator(read_opts));
  174. iter->Seek("k2");
  175. ASSERT_TRUE(iter->Valid());
  176. // Verify the request_id was propagated to the file system
  177. ASSERT_NE(captured_request_id_dbg, nullptr);
  178. ASSERT_EQ(*captured_request_id_dbg, request_id);
  179. ASSERT_NE(dbgCopy.request_id, nullptr);
  180. ASSERT_NE(dbgCopy.request_id, captured_request_id_dbg);
  181. ASSERT_EQ(*dbgCopy.request_id, request_id);
  182. // Test IODebugContext copy constructor
  183. IODebugContext dbgCopy2(dbgCopy);
  184. ASSERT_NE(dbgCopy2.request_id, nullptr);
  185. ASSERT_NE(dbgCopy2.request_id, captured_request_id_dbg);
  186. ASSERT_NE(dbgCopy2.request_id, dbgCopy.request_id);
  187. ASSERT_EQ(*dbgCopy2.request_id, request_id);
  188. }
  189. // test request_id plumbing during multiget
  190. captured_request_id_dbg = nullptr;
  191. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();
  192. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  193. "RandomAccessFileReader::MultiRead:IODebugContext", [&](void* arg) {
  194. IODebugContext* dbg = static_cast<IODebugContext*>(arg);
  195. if (dbg == nullptr) {
  196. captured_request_id_dbg = nullptr;
  197. } else {
  198. captured_request_id_dbg = dbg->request_id;
  199. }
  200. });
  201. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  202. ASSERT_OK(Put("k3", "v3"));
  203. ASSERT_OK(Put("k4", "v4"));
  204. ASSERT_OK(Flush());
  205. {
  206. ReadOptions read_opts;
  207. const std::string multiget_request_id = "test_request_id_789";
  208. read_opts.request_id = &multiget_request_id;
  209. std::vector<std::string> values;
  210. std::vector<Slice> keys = {Slice("k3"), Slice("k4")};
  211. values.resize(keys.size());
  212. std::vector<ColumnFamilyHandle*> cfhs(keys.size(),
  213. db_->DefaultColumnFamily());
  214. db_->MultiGet(read_opts, cfhs, keys, &values);
  215. ASSERT_NE(captured_request_id_dbg, nullptr);
  216. ASSERT_EQ(*captured_request_id_dbg, multiget_request_id);
  217. }
  218. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  219. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();
  220. }
  221. TEST_F(DBTest, MemEnvTest) {
  222. std::unique_ptr<Env> env{NewMemEnv(Env::Default())};
  223. Options options;
  224. options.create_if_missing = true;
  225. options.env = env.get();
  226. DB* db;
  227. const Slice keys[] = {Slice("aaa"), Slice("bbb"), Slice("ccc")};
  228. const Slice vals[] = {Slice("foo"), Slice("bar"), Slice("baz")};
  229. ASSERT_OK(DB::Open(options, "/dir/db", &db));
  230. for (size_t i = 0; i < 3; ++i) {
  231. ASSERT_OK(db->Put(WriteOptions(), keys[i], vals[i]));
  232. }
  233. for (size_t i = 0; i < 3; ++i) {
  234. std::string res;
  235. ASSERT_OK(db->Get(ReadOptions(), keys[i], &res));
  236. ASSERT_TRUE(res == vals[i]);
  237. }
  238. Iterator* iterator = db->NewIterator(ReadOptions());
  239. iterator->SeekToFirst();
  240. for (size_t i = 0; i < 3; ++i) {
  241. ASSERT_TRUE(iterator->Valid());
  242. ASSERT_TRUE(keys[i] == iterator->key());
  243. ASSERT_TRUE(vals[i] == iterator->value());
  244. iterator->Next();
  245. }
  246. ASSERT_TRUE(!iterator->Valid());
  247. ASSERT_OK(iterator->status());
  248. delete iterator;
  249. DBImpl* dbi = static_cast_with_check<DBImpl>(db);
  250. ASSERT_OK(dbi->TEST_FlushMemTable());
  251. for (size_t i = 0; i < 3; ++i) {
  252. std::string res;
  253. ASSERT_OK(db->Get(ReadOptions(), keys[i], &res));
  254. ASSERT_TRUE(res == vals[i]);
  255. }
  256. delete db;
  257. options.create_if_missing = false;
  258. ASSERT_OK(DB::Open(options, "/dir/db", &db));
  259. for (size_t i = 0; i < 3; ++i) {
  260. std::string res;
  261. ASSERT_OK(db->Get(ReadOptions(), keys[i], &res));
  262. ASSERT_TRUE(res == vals[i]);
  263. }
  264. delete db;
  265. }
  266. TEST_F(DBTest, WriteEmptyBatch) {
  267. Options options = CurrentOptions();
  268. options.env = env_;
  269. options.write_buffer_size = 100000;
  270. CreateAndReopenWithCF({"pikachu"}, options);
  271. ASSERT_OK(Put(1, "foo", "bar"));
  272. WriteOptions wo;
  273. wo.sync = true;
  274. wo.disableWAL = false;
  275. WriteBatch empty_batch;
  276. ASSERT_OK(dbfull()->Write(wo, &empty_batch));
  277. // make sure we can re-open it.
  278. ASSERT_OK(TryReopenWithColumnFamilies({"default", "pikachu"}, options));
  279. ASSERT_EQ("bar", Get(1, "foo"));
  280. }
  281. TEST_F(DBTest, SkipDelay) {
  282. Options options = CurrentOptions();
  283. options.env = env_;
  284. options.write_buffer_size = 100000;
  285. CreateAndReopenWithCF({"pikachu"}, options);
  286. for (bool sync : {true, false}) {
  287. for (bool disableWAL : {true, false}) {
  288. if (sync && disableWAL) {
  289. // sync and disableWAL is incompatible.
  290. continue;
  291. }
  292. // Use a small number to ensure a large delay that is still effective
  293. // when we do Put
  294. // TODO(myabandeh): this is time dependent and could potentially make
  295. // the test flaky
  296. auto token = dbfull()->TEST_write_controler().GetDelayToken(1);
  297. std::atomic<int> sleep_count(0);
  298. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  299. "DBImpl::DelayWrite:Sleep",
  300. [&](void* /*arg*/) { sleep_count.fetch_add(1); });
  301. std::atomic<int> wait_count(0);
  302. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  303. "DBImpl::DelayWrite:Wait",
  304. [&](void* /*arg*/) { wait_count.fetch_add(1); });
  305. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  306. WriteOptions wo;
  307. wo.sync = sync;
  308. wo.disableWAL = disableWAL;
  309. wo.no_slowdown = true;
  310. // Large enough to exceed allowance for one time interval
  311. std::string large_value(1024, 'x');
  312. // Perhaps ideally this first write would fail because of delay, but
  313. // the current implementation does not guarantee that.
  314. dbfull()->Put(wo, "foo", large_value).PermitUncheckedError();
  315. // We need the 2nd write to trigger delay. This is because delay is
  316. // estimated based on the last write size which is 0 for the first write.
  317. ASSERT_NOK(dbfull()->Put(wo, "foo2", large_value));
  318. ASSERT_GE(sleep_count.load(), 0);
  319. ASSERT_GE(wait_count.load(), 0);
  320. token.reset();
  321. token = dbfull()->TEST_write_controler().GetDelayToken(1000000);
  322. wo.no_slowdown = false;
  323. ASSERT_OK(dbfull()->Put(wo, "foo3", large_value));
  324. ASSERT_GE(sleep_count.load(), 1);
  325. token.reset();
  326. }
  327. }
  328. }
  329. TEST_F(DBTest, MixedSlowdownOptions) {
  330. Options options = CurrentOptions();
  331. options.env = env_;
  332. options.write_buffer_size = 100000;
  333. CreateAndReopenWithCF({"pikachu"}, options);
  334. std::vector<port::Thread> threads;
  335. std::atomic<int> thread_num(0);
  336. std::function<void()> write_slowdown_func = [&]() {
  337. int a = thread_num.fetch_add(1);
  338. std::string key = "foo" + std::to_string(a);
  339. WriteOptions wo;
  340. wo.no_slowdown = false;
  341. ASSERT_OK(dbfull()->Put(wo, key, "bar"));
  342. };
  343. std::function<void()> write_no_slowdown_func = [&]() {
  344. int a = thread_num.fetch_add(1);
  345. std::string key = "foo" + std::to_string(a);
  346. WriteOptions wo;
  347. wo.no_slowdown = true;
  348. ASSERT_NOK(dbfull()->Put(wo, key, "bar"));
  349. };
  350. // Use a small number to ensure a large delay that is still effective
  351. // when we do Put
  352. // TODO(myabandeh): this is time dependent and could potentially make
  353. // the test flaky
  354. auto token = dbfull()->TEST_write_controler().GetDelayToken(1);
  355. std::atomic<int> sleep_count(0);
  356. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  357. "DBImpl::DelayWrite:BeginWriteStallDone", [&](void* /*arg*/) {
  358. sleep_count.fetch_add(1);
  359. if (threads.empty()) {
  360. for (int i = 0; i < 2; ++i) {
  361. threads.emplace_back(write_slowdown_func);
  362. }
  363. for (int i = 0; i < 2; ++i) {
  364. threads.emplace_back(write_no_slowdown_func);
  365. }
  366. }
  367. });
  368. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  369. WriteOptions wo;
  370. wo.sync = false;
  371. wo.disableWAL = false;
  372. wo.no_slowdown = false;
  373. ASSERT_OK(dbfull()->Put(wo, "foo", "bar"));
  374. // We need the 2nd write to trigger delay. This is because delay is
  375. // estimated based on the last write size which is 0 for the first write.
  376. ASSERT_OK(dbfull()->Put(wo, "foo2", "bar2"));
  377. token.reset();
  378. for (auto& t : threads) {
  379. t.join();
  380. }
  381. ASSERT_GE(sleep_count.load(), 1);
  382. wo.no_slowdown = true;
  383. ASSERT_OK(dbfull()->Put(wo, "foo3", "bar"));
  384. }
  385. TEST_F(DBTest, MixedSlowdownOptionsInQueue) {
  386. Options options = CurrentOptions();
  387. options.env = env_;
  388. options.write_buffer_size = 100000;
  389. CreateAndReopenWithCF({"pikachu"}, options);
  390. std::vector<port::Thread> threads;
  391. std::atomic<int> thread_num(0);
  392. std::function<void()> write_no_slowdown_func = [&]() {
  393. int a = thread_num.fetch_add(1);
  394. std::string key = "foo" + std::to_string(a);
  395. WriteOptions wo;
  396. wo.no_slowdown = true;
  397. ASSERT_NOK(dbfull()->Put(wo, key, "bar"));
  398. };
  399. // Use a small number to ensure a large delay that is still effective
  400. // when we do Put
  401. // TODO(myabandeh): this is time dependent and could potentially make
  402. // the test flaky
  403. auto token = dbfull()->TEST_write_controler().GetDelayToken(1);
  404. std::atomic<int> sleep_count(0);
  405. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  406. "DBImpl::DelayWrite:Sleep", [&](void* /*arg*/) {
  407. sleep_count.fetch_add(1);
  408. if (threads.empty()) {
  409. for (int i = 0; i < 2; ++i) {
  410. threads.emplace_back(write_no_slowdown_func);
  411. }
  412. // Sleep for 3s to allow the threads to insert themselves into the
  413. // write queue
  414. env_->SleepForMicroseconds(3000000ULL);
  415. }
  416. });
  417. std::atomic<int> wait_count(0);
  418. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  419. "DBImpl::DelayWrite:Wait",
  420. [&](void* /*arg*/) { wait_count.fetch_add(1); });
  421. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  422. WriteOptions wo;
  423. wo.sync = false;
  424. wo.disableWAL = false;
  425. wo.no_slowdown = false;
  426. ASSERT_OK(dbfull()->Put(wo, "foo", "bar"));
  427. // We need the 2nd write to trigger delay. This is because delay is
  428. // estimated based on the last write size which is 0 for the first write.
  429. ASSERT_OK(dbfull()->Put(wo, "foo2", "bar2"));
  430. token.reset();
  431. for (auto& t : threads) {
  432. t.join();
  433. }
  434. ASSERT_EQ(sleep_count.load(), 1);
  435. ASSERT_GE(wait_count.load(), 0);
  436. }
  437. TEST_F(DBTest, MixedSlowdownOptionsStop) {
  438. Options options = CurrentOptions();
  439. options.env = env_;
  440. options.write_buffer_size = 100000;
  441. CreateAndReopenWithCF({"pikachu"}, options);
  442. std::vector<port::Thread> threads;
  443. std::atomic<int> thread_num(0);
  444. std::function<void()> write_slowdown_func = [&]() {
  445. int a = thread_num.fetch_add(1);
  446. std::string key = "foo" + std::to_string(a);
  447. WriteOptions wo;
  448. wo.no_slowdown = false;
  449. ASSERT_OK(dbfull()->Put(wo, key, "bar"));
  450. };
  451. std::function<void()> write_no_slowdown_func = [&]() {
  452. int a = thread_num.fetch_add(1);
  453. std::string key = "foo" + std::to_string(a);
  454. WriteOptions wo;
  455. wo.no_slowdown = true;
  456. ASSERT_NOK(dbfull()->Put(wo, key, "bar"));
  457. };
  458. std::function<void()> wakeup_writer = [&]() {
  459. dbfull()->mutex_.Lock();
  460. dbfull()->bg_cv_.SignalAll();
  461. dbfull()->mutex_.Unlock();
  462. };
  463. // Use a small number to ensure a large delay that is still effective
  464. // when we do Put
  465. // TODO(myabandeh): this is time dependent and could potentially make
  466. // the test flaky
  467. auto token = dbfull()->TEST_write_controler().GetStopToken();
  468. std::atomic<int> wait_count(0);
  469. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  470. "DBImpl::DelayWrite:Wait", [&](void* /*arg*/) {
  471. wait_count.fetch_add(1);
  472. if (threads.empty()) {
  473. for (int i = 0; i < 2; ++i) {
  474. threads.emplace_back(write_slowdown_func);
  475. }
  476. for (int i = 0; i < 2; ++i) {
  477. threads.emplace_back(write_no_slowdown_func);
  478. }
  479. // Sleep for 3s to allow the threads to insert themselves into the
  480. // write queue
  481. env_->SleepForMicroseconds(3000000ULL);
  482. }
  483. token.reset();
  484. threads.emplace_back(wakeup_writer);
  485. });
  486. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  487. WriteOptions wo;
  488. wo.sync = false;
  489. wo.disableWAL = false;
  490. wo.no_slowdown = false;
  491. ASSERT_OK(dbfull()->Put(wo, "foo", "bar"));
  492. // We need the 2nd write to trigger delay. This is because delay is
  493. // estimated based on the last write size which is 0 for the first write.
  494. ASSERT_OK(dbfull()->Put(wo, "foo2", "bar2"));
  495. token.reset();
  496. for (auto& t : threads) {
  497. t.join();
  498. }
  499. ASSERT_GE(wait_count.load(), 1);
  500. wo.no_slowdown = true;
  501. ASSERT_OK(dbfull()->Put(wo, "foo3", "bar"));
  502. }
  503. TEST_F(DBTest, LevelLimitReopen) {
  504. Options options = CurrentOptions();
  505. CreateAndReopenWithCF({"pikachu"}, options);
  506. const std::string value(1024 * 1024, ' ');
  507. int i = 0;
  508. while (NumTableFilesAtLevel(2, 1) == 0) {
  509. ASSERT_OK(Put(1, Key(i++), value));
  510. }
  511. options.num_levels = 1;
  512. options.max_bytes_for_level_multiplier_additional.resize(1, 1);
  513. Status s = TryReopenWithColumnFamilies({"default", "pikachu"}, options);
  514. ASSERT_EQ(s.IsInvalidArgument(), true);
  515. ASSERT_EQ(s.ToString(),
  516. "Invalid argument: db has more levels than options.num_levels");
  517. options.num_levels = 10;
  518. options.max_bytes_for_level_multiplier_additional.resize(10, 1);
  519. ASSERT_OK(TryReopenWithColumnFamilies({"default", "pikachu"}, options));
  520. }
  521. TEST_F(DBTest, LevelReopenWithFIFO) {
  522. const int kLevelCount = 4;
  523. const int kKeyCount = 5;
  524. const int kTotalSstFileCount = kLevelCount * kKeyCount;
  525. const int kCF = 1;
  526. Options options = CurrentOptions();
  527. // Config level0_file_num_compaction_trigger to prevent L0 files being
  528. // automatically compacted while we are constructing a LSM tree structure
  529. // to test multi-level FIFO compaction.
  530. options.level0_file_num_compaction_trigger = kKeyCount + 1;
  531. CreateAndReopenWithCF({"pikachu"}, options);
  532. // The expected number of files per level after each file creation.
  533. const std::string expected_files_per_level[kLevelCount][kKeyCount] = {
  534. {"0,0,0,1", "0,0,0,2", "0,0,0,3", "0,0,0,4", "0,0,0,5"},
  535. {"0,0,1,5", "0,0,2,5", "0,0,3,5", "0,0,4,5", "0,0,5,5"},
  536. {"0,1,5,5", "0,2,5,5", "0,3,5,5", "0,4,5,5", "0,5,5,5"},
  537. {"1,5,5,5", "2,5,5,5", "3,5,5,5", "4,5,5,5", "5,5,5,5"},
  538. };
  539. const std::string expected_entries[kKeyCount][kLevelCount + 1] = {
  540. {"[ ]", "[ a3 ]", "[ a2, a3 ]", "[ a1, a2, a3 ]", "[ a0, a1, a2, a3 ]"},
  541. {"[ ]", "[ b3 ]", "[ b2, b3 ]", "[ b1, b2, b3 ]", "[ b0, b1, b2, b3 ]"},
  542. {"[ ]", "[ c3 ]", "[ c2, c3 ]", "[ c1, c2, c3 ]", "[ c0, c1, c2, c3 ]"},
  543. {"[ ]", "[ d3 ]", "[ d2, d3 ]", "[ d1, d2, d3 ]", "[ d0, d1, d2, d3 ]"},
  544. {"[ ]", "[ e3 ]", "[ e2, e3 ]", "[ e1, e2, e3 ]", "[ e0, e1, e2, e3 ]"},
  545. };
  546. // The loop below creates the following LSM tree where each (k, v) pair
  547. // represents a file that contains that entry. When a file is created,
  548. // the db is reopend with FIFO compaction and verified the LSM tree
  549. // structure is still the same.
  550. //
  551. // The resulting LSM tree will contain 5 different keys. Each key as
  552. // 4 different versions, located in different level.
  553. //
  554. // L0: (e, e0) (d, d0) (c, c0) (b, b0) (a, a0)
  555. // L1: (a, a1) (b, b1) (c, c1) (d, d1) (e, e1)
  556. // L2: (a, a2) (b, b2) (c, c2) (d, d2) (e, e2)
  557. // L3: (a, a3) (b, b3) (c, c3) (d, d3) (e, e3)
  558. for (int l = 0; l < kLevelCount; ++l) {
  559. int level = kLevelCount - 1 - l;
  560. for (int p = 0; p < kKeyCount; ++p) {
  561. std::string put_key = std::string(1, char('a' + p));
  562. ASSERT_OK(Put(kCF, put_key, put_key + std::to_string(level)));
  563. ASSERT_OK(Flush(kCF));
  564. ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
  565. for (int g = 0; g < kKeyCount; ++g) {
  566. int entry_count = (p >= g) ? l + 1 : l;
  567. std::string get_key = std::string(1, char('a' + g));
  568. CheckAllEntriesWithFifoReopen(expected_entries[g][entry_count], get_key,
  569. kCF, {"pikachu"}, options);
  570. }
  571. if (level != 0) {
  572. MoveFilesToLevel(level, kCF);
  573. for (int g = 0; g < kKeyCount; ++g) {
  574. int entry_count = (p >= g) ? l + 1 : l;
  575. std::string get_key = std::string(1, char('a' + g));
  576. CheckAllEntriesWithFifoReopen(expected_entries[g][entry_count],
  577. get_key, kCF, {"pikachu"}, options);
  578. }
  579. }
  580. ASSERT_EQ(expected_files_per_level[l][p], FilesPerLevel(kCF));
  581. }
  582. }
  583. // The expected number of sst files in each level after each FIFO compaction
  584. // that deletes the oldest sst file.
  585. const std::string expected_files_per_level_after_fifo[] = {
  586. "5,5,5,4", "5,5,5,3", "5,5,5,2", "5,5,5,1", "5,5,5", "5,5,4", "5,5,3",
  587. "5,5,2", "5,5,1", "5,5", "5,4", "5,3", "5,2", "5,1",
  588. "5", "4", "3", "2", "1", "",
  589. };
  590. // The expected value entries of each key after each FIFO compaction.
  591. // This verifies whether FIFO removes the file with the smallest key in non-L0
  592. // files first then the oldest files in L0.
  593. const std::string expected_entries_after_fifo[kKeyCount][kLevelCount + 1] = {
  594. {"[ a0, a1, a2, a3 ]", "[ a0, a1, a2 ]", "[ a0, a1 ]", "[ a0 ]", "[ ]"},
  595. {"[ b0, b1, b2, b3 ]", "[ b0, b1, b2 ]", "[ b0, b1 ]", "[ b0 ]", "[ ]"},
  596. {"[ c0, c1, c2, c3 ]", "[ c0, c1, c2 ]", "[ c0, c1 ]", "[ c0 ]", "[ ]"},
  597. {"[ d0, d1, d2, d3 ]", "[ d0, d1, d2 ]", "[ d0, d1 ]", "[ d0 ]", "[ ]"},
  598. {"[ e0, e1, e2, e3 ]", "[ e0, e1, e2 ]", "[ e0, e1 ]", "[ e0 ]", "[ ]"},
  599. };
  600. // In the 2nd phase, we reopen the DB with FIFO compaction. In each reopen,
  601. // we config max_table_files_size so that FIFO will remove exactly one file
  602. // at a time upon compaction, and we will use it to verify whether the sst
  603. // files are deleted in the correct order.
  604. for (int i = 0; i < kTotalSstFileCount; ++i) {
  605. uint64_t total_sst_files_size = 0;
  606. ASSERT_TRUE(dbfull()->GetIntProperty(
  607. handles_[1], "rocksdb.total-sst-files-size", &total_sst_files_size));
  608. ASSERT_TRUE(total_sst_files_size > 0);
  609. Options fifo_options(options);
  610. fifo_options.compaction_style = kCompactionStyleFIFO;
  611. options.create_if_missing = false;
  612. fifo_options.max_open_files = -1;
  613. fifo_options.disable_auto_compactions = false;
  614. // Config max_table_files_size to be total_sst_files_size - 1 so that
  615. // FIFO will delete one file.
  616. fifo_options.compaction_options_fifo.max_table_files_size =
  617. total_sst_files_size - 1;
  618. ASSERT_OK(
  619. TryReopenWithColumnFamilies({"default", "pikachu"}, fifo_options));
  620. // For FIFO to pick a compaction
  621. ASSERT_OK(dbfull()->TEST_CompactRange(0, nullptr, nullptr, handles_[1]));
  622. ASSERT_OK(dbfull()->TEST_WaitForBackgroundWork());
  623. for (int g = 0; g < kKeyCount; ++g) {
  624. std::string get_key = std::string(1, char('a' + g));
  625. int status_index = i / kKeyCount;
  626. if ((i % kKeyCount) >= g) {
  627. // If true, then it means the sst file containing the get_key in the
  628. // current level has already been deleted, so we need to move the
  629. // status_index for checking the expected value.
  630. status_index++;
  631. }
  632. CheckAllEntriesWithFifoReopen(
  633. expected_entries_after_fifo[g][status_index], get_key, kCF,
  634. {"pikachu"}, options);
  635. }
  636. ASSERT_EQ(expected_files_per_level_after_fifo[i], FilesPerLevel(kCF));
  637. }
  638. }
  639. TEST_F(DBTest, PutSingleDeleteGet) {
  640. do {
  641. CreateAndReopenWithCF({"pikachu"}, CurrentOptions());
  642. ASSERT_OK(Put(1, "foo", "v1"));
  643. ASSERT_EQ("v1", Get(1, "foo"));
  644. ASSERT_OK(Put(1, "foo2", "v2"));
  645. ASSERT_EQ("v2", Get(1, "foo2"));
  646. ASSERT_OK(SingleDelete(1, "foo"));
  647. ASSERT_EQ("NOT_FOUND", Get(1, "foo"));
  648. // Skip FIFO and universal compaction because they do not apply to the test
  649. // case. Skip MergePut because single delete does not get removed when it
  650. // encounters a merge.
  651. } while (ChangeOptions(kSkipFIFOCompaction | kSkipUniversalCompaction |
  652. kSkipMergePut));
  653. }
  654. TEST_F(DBTest, ReadFromPersistedTier) {
  655. do {
  656. Random rnd(301);
  657. Options options = CurrentOptions();
  658. for (int disableWAL = 0; disableWAL <= 1; ++disableWAL) {
  659. CreateAndReopenWithCF({"pikachu"}, options);
  660. WriteOptions wopt;
  661. wopt.disableWAL = (disableWAL == 1);
  662. // 1st round: put but not flush
  663. ASSERT_OK(db_->Put(wopt, handles_[1], "foo", "first"));
  664. ASSERT_OK(db_->Put(wopt, handles_[1], "bar", "one"));
  665. ASSERT_EQ("first", Get(1, "foo"));
  666. ASSERT_EQ("one", Get(1, "bar"));
  667. // Read directly from persited data.
  668. ReadOptions ropt;
  669. ropt.read_tier = kPersistedTier;
  670. std::string value;
  671. if (wopt.disableWAL) {
  672. // as data has not yet being flushed, we expect not found.
  673. ASSERT_TRUE(db_->Get(ropt, handles_[1], "foo", &value).IsNotFound());
  674. ASSERT_TRUE(db_->Get(ropt, handles_[1], "bar", &value).IsNotFound());
  675. } else {
  676. ASSERT_OK(db_->Get(ropt, handles_[1], "foo", &value));
  677. ASSERT_OK(db_->Get(ropt, handles_[1], "bar", &value));
  678. }
  679. const auto check_multiget_func =
  680. [&](const ReadOptions& read_opts,
  681. std::vector<ColumnFamilyHandle*> cfhs, std::vector<Slice>& keys,
  682. std::vector<std::string>& values,
  683. bool batched) -> std::vector<Status> {
  684. if (!batched) {
  685. return db_->MultiGet(read_opts, cfhs, keys, &values);
  686. } else {
  687. size_t num_keys = keys.size();
  688. std::vector<Status> statuses;
  689. std::vector<PinnableSlice> pinnable_values;
  690. statuses.resize(num_keys);
  691. pinnable_values.resize(num_keys);
  692. values.resize(num_keys);
  693. db_->MultiGet(read_opts, cfhs[0], num_keys, keys.data(),
  694. pinnable_values.data(), statuses.data(), false);
  695. for (size_t i = 0; i < statuses.size(); ++i) {
  696. if (statuses[i].ok()) {
  697. values[i].assign(pinnable_values[i].data(),
  698. pinnable_values[i].size());
  699. pinnable_values[i].Reset();
  700. }
  701. }
  702. return statuses;
  703. }
  704. };
  705. // Multiget
  706. std::vector<ColumnFamilyHandle*> multiget_cfs;
  707. multiget_cfs.push_back(handles_[1]);
  708. multiget_cfs.push_back(handles_[1]);
  709. std::vector<Slice> multiget_keys;
  710. multiget_keys.emplace_back("foo");
  711. multiget_keys.emplace_back("bar");
  712. std::vector<std::string> multiget_values;
  713. for (int i = 0; i < 2; i++) {
  714. bool batched = i == 0;
  715. auto statuses = check_multiget_func(ropt, multiget_cfs, multiget_keys,
  716. multiget_values, batched);
  717. if (wopt.disableWAL) {
  718. ASSERT_TRUE(statuses[0].IsNotFound());
  719. ASSERT_TRUE(statuses[1].IsNotFound());
  720. } else {
  721. ASSERT_OK(statuses[0]);
  722. ASSERT_OK(statuses[1]);
  723. }
  724. }
  725. // 2nd round: flush and put a new value in memtable.
  726. ASSERT_OK(Flush(1));
  727. ASSERT_OK(db_->Put(wopt, handles_[1], "rocksdb", "hello"));
  728. // once the data has been flushed, we are able to get the
  729. // data when kPersistedTier is used.
  730. ASSERT_TRUE(db_->Get(ropt, handles_[1], "foo", &value).ok());
  731. ASSERT_EQ(value, "first");
  732. ASSERT_TRUE(db_->Get(ropt, handles_[1], "bar", &value).ok());
  733. ASSERT_EQ(value, "one");
  734. if (wopt.disableWAL) {
  735. ASSERT_TRUE(
  736. db_->Get(ropt, handles_[1], "rocksdb", &value).IsNotFound());
  737. } else {
  738. ASSERT_OK(db_->Get(ropt, handles_[1], "rocksdb", &value));
  739. ASSERT_EQ(value, "hello");
  740. }
  741. // Expect same result in multiget
  742. multiget_cfs.push_back(handles_[1]);
  743. multiget_keys.emplace_back("rocksdb");
  744. multiget_values.clear();
  745. for (int i = 0; i < 2; i++) {
  746. bool batched = i == 0;
  747. auto statuses = check_multiget_func(ropt, multiget_cfs, multiget_keys,
  748. multiget_values, batched);
  749. ASSERT_TRUE(statuses[0].ok());
  750. ASSERT_EQ("first", multiget_values[0]);
  751. ASSERT_TRUE(statuses[1].ok());
  752. ASSERT_EQ("one", multiget_values[1]);
  753. if (wopt.disableWAL) {
  754. ASSERT_TRUE(statuses[2].IsNotFound());
  755. } else {
  756. ASSERT_OK(statuses[2]);
  757. }
  758. }
  759. // 3rd round: delete and flush
  760. ASSERT_OK(db_->Delete(wopt, handles_[1], "foo"));
  761. ASSERT_OK(Flush(1));
  762. ASSERT_OK(db_->Delete(wopt, handles_[1], "bar"));
  763. ASSERT_TRUE(db_->Get(ropt, handles_[1], "foo", &value).IsNotFound());
  764. if (wopt.disableWAL) {
  765. // Still expect finding the value as its delete has not yet being
  766. // flushed.
  767. ASSERT_TRUE(db_->Get(ropt, handles_[1], "bar", &value).ok());
  768. ASSERT_EQ(value, "one");
  769. } else {
  770. ASSERT_TRUE(db_->Get(ropt, handles_[1], "bar", &value).IsNotFound());
  771. }
  772. ASSERT_TRUE(db_->Get(ropt, handles_[1], "rocksdb", &value).ok());
  773. ASSERT_EQ(value, "hello");
  774. multiget_values.clear();
  775. for (int i = 0; i < 2; i++) {
  776. bool batched = i == 0;
  777. auto statuses = check_multiget_func(ropt, multiget_cfs, multiget_keys,
  778. multiget_values, batched);
  779. ASSERT_TRUE(statuses[0].IsNotFound());
  780. if (wopt.disableWAL) {
  781. ASSERT_TRUE(statuses[1].ok());
  782. ASSERT_EQ("one", multiget_values[1]);
  783. } else {
  784. ASSERT_TRUE(statuses[1].IsNotFound());
  785. }
  786. ASSERT_TRUE(statuses[2].ok());
  787. ASSERT_EQ("hello", multiget_values[2]);
  788. }
  789. if (wopt.disableWAL == 0) {
  790. DestroyAndReopen(options);
  791. }
  792. }
  793. } while (ChangeOptions());
  794. }
  795. TEST_F(DBTest, SingleDeleteFlush) {
  796. // Test to check whether flushing preserves a single delete hidden
  797. // behind a put.
  798. do {
  799. Random rnd(301);
  800. Options options = CurrentOptions();
  801. options.disable_auto_compactions = true;
  802. CreateAndReopenWithCF({"pikachu"}, options);
  803. // Put values on second level (so that they will not be in the same
  804. // compaction as the other operations.
  805. ASSERT_OK(Put(1, "foo", "first"));
  806. ASSERT_OK(Put(1, "bar", "one"));
  807. ASSERT_OK(Flush(1));
  808. MoveFilesToLevel(2, 1);
  809. // (Single) delete hidden by a put
  810. ASSERT_OK(SingleDelete(1, "foo"));
  811. ASSERT_OK(Put(1, "foo", "second"));
  812. ASSERT_OK(Delete(1, "bar"));
  813. ASSERT_OK(Put(1, "bar", "two"));
  814. ASSERT_OK(Flush(1));
  815. ASSERT_OK(SingleDelete(1, "foo"));
  816. ASSERT_OK(Delete(1, "bar"));
  817. ASSERT_OK(Flush(1));
  818. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), handles_[1],
  819. nullptr, nullptr));
  820. ASSERT_EQ("NOT_FOUND", Get(1, "bar"));
  821. ASSERT_EQ("NOT_FOUND", Get(1, "foo"));
  822. // Skip FIFO and universal compaction beccaus they do not apply to the test
  823. // case. Skip MergePut because single delete does not get removed when it
  824. // encounters a merge.
  825. } while (ChangeOptions(kSkipFIFOCompaction | kSkipUniversalCompaction |
  826. kSkipMergePut));
  827. }
  828. TEST_F(DBTest, SingleDeletePutFlush) {
  829. // Single deletes that encounter the matching put in a flush should get
  830. // removed.
  831. do {
  832. Random rnd(301);
  833. Options options = CurrentOptions();
  834. options.disable_auto_compactions = true;
  835. CreateAndReopenWithCF({"pikachu"}, options);
  836. ASSERT_OK(Put(1, "foo", Slice()));
  837. ASSERT_OK(Put(1, "a", Slice()));
  838. ASSERT_OK(SingleDelete(1, "a"));
  839. ASSERT_OK(Flush(1));
  840. ASSERT_EQ("[ ]", AllEntriesFor("a", 1));
  841. // Skip FIFO and universal compaction because they do not apply to the test
  842. // case. Skip MergePut because single delete does not get removed when it
  843. // encounters a merge.
  844. } while (ChangeOptions(kSkipFIFOCompaction | kSkipUniversalCompaction |
  845. kSkipMergePut));
  846. }
  847. // Disable because not all platform can run it.
  848. // It requires more than 9GB memory to run it, With single allocation
  849. // of more than 3GB.
  850. TEST_F(DBTest, DISABLED_SanitizeVeryVeryLargeValue) {
  851. const size_t kValueSize = 4 * size_t{1024 * 1024 * 1024}; // 4GB value
  852. std::string raw(kValueSize, 'v');
  853. Options options = CurrentOptions();
  854. options.env = env_;
  855. options.merge_operator = MergeOperators::CreatePutOperator();
  856. options.write_buffer_size = 100000; // Small write buffer
  857. options.paranoid_checks = true;
  858. DestroyAndReopen(options);
  859. ASSERT_OK(Put("boo", "v1"));
  860. ASSERT_TRUE(Put("foo", raw).IsInvalidArgument());
  861. ASSERT_TRUE(Merge("foo", raw).IsInvalidArgument());
  862. WriteBatch wb;
  863. ASSERT_TRUE(wb.Put("foo", raw).IsInvalidArgument());
  864. ASSERT_TRUE(wb.Merge("foo", raw).IsInvalidArgument());
  865. Slice value_slice = raw;
  866. Slice key_slice = "foo";
  867. SliceParts sp_key(&key_slice, 1);
  868. SliceParts sp_value(&value_slice, 1);
  869. ASSERT_TRUE(wb.Put(sp_key, sp_value).IsInvalidArgument());
  870. ASSERT_TRUE(wb.Merge(sp_key, sp_value).IsInvalidArgument());
  871. }
  872. // Disable because not all platform can run it.
  873. // It requires more than 9GB memory to run it, With single allocation
  874. // of more than 3GB.
  875. TEST_F(DBTest, DISABLED_VeryLargeValue) {
  876. const size_t kValueSize = 3221225472u; // 3GB value
  877. const size_t kKeySize = 8388608u; // 8MB key
  878. std::string raw(kValueSize, 'v');
  879. std::string key1(kKeySize, 'c');
  880. std::string key2(kKeySize, 'd');
  881. Options options = CurrentOptions();
  882. options.env = env_;
  883. options.write_buffer_size = 100000; // Small write buffer
  884. options.paranoid_checks = true;
  885. DestroyAndReopen(options);
  886. ASSERT_OK(Put("boo", "v1"));
  887. ASSERT_OK(Put("foo", "v1"));
  888. ASSERT_OK(Put(key1, raw));
  889. raw[0] = 'w';
  890. ASSERT_OK(Put(key2, raw));
  891. dbfull()->TEST_WaitForFlushMemTable();
  892. ASSERT_EQ(1, NumTableFilesAtLevel(0));
  893. std::string value;
  894. Status s = db_->Get(ReadOptions(), key1, &value);
  895. ASSERT_OK(s);
  896. ASSERT_EQ(kValueSize, value.size());
  897. ASSERT_EQ('v', value[0]);
  898. s = db_->Get(ReadOptions(), key2, &value);
  899. ASSERT_OK(s);
  900. ASSERT_EQ(kValueSize, value.size());
  901. ASSERT_EQ('w', value[0]);
  902. // Compact all files.
  903. ASSERT_OK(Flush());
  904. db_->CompactRange(CompactRangeOptions(), nullptr, nullptr);
  905. // Check DB is not in read-only state.
  906. ASSERT_OK(Put("boo", "v1"));
  907. s = db_->Get(ReadOptions(), key1, &value);
  908. ASSERT_OK(s);
  909. ASSERT_EQ(kValueSize, value.size());
  910. ASSERT_EQ('v', value[0]);
  911. s = db_->Get(ReadOptions(), key2, &value);
  912. ASSERT_OK(s);
  913. ASSERT_EQ(kValueSize, value.size());
  914. ASSERT_EQ('w', value[0]);
  915. }
  916. TEST_F(DBTest, GetFromImmutableLayer) {
  917. do {
  918. Options options = CurrentOptions();
  919. options.env = env_;
  920. CreateAndReopenWithCF({"pikachu"}, options);
  921. ASSERT_OK(Put(1, "foo", "v1"));
  922. ASSERT_EQ("v1", Get(1, "foo"));
  923. // Block sync calls
  924. env_->delay_sstable_sync_.store(true, std::memory_order_release);
  925. ASSERT_OK(Put(1, "k1", std::string(100000, 'x'))); // Fill memtable
  926. ASSERT_OK(Put(1, "k2", std::string(100000, 'y'))); // Trigger flush
  927. ASSERT_EQ("v1", Get(1, "foo"));
  928. ASSERT_EQ("NOT_FOUND", Get(0, "foo"));
  929. // Release sync calls
  930. env_->delay_sstable_sync_.store(false, std::memory_order_release);
  931. } while (ChangeOptions());
  932. }
  933. TEST_F(DBTest, GetLevel0Ordering) {
  934. do {
  935. CreateAndReopenWithCF({"pikachu"}, CurrentOptions());
  936. // Check that we process level-0 files in correct order. The code
  937. // below generates two level-0 files where the earlier one comes
  938. // before the later one in the level-0 file list since the earlier
  939. // one has a smaller "smallest" key.
  940. ASSERT_OK(Put(1, "bar", "b"));
  941. ASSERT_OK(Put(1, "foo", "v1"));
  942. ASSERT_OK(Flush(1));
  943. ASSERT_OK(Put(1, "foo", "v2"));
  944. ASSERT_OK(Flush(1));
  945. ASSERT_EQ("v2", Get(1, "foo"));
  946. } while (ChangeOptions());
  947. }
  948. TEST_F(DBTest, WrongLevel0Config) {
  949. Options options = CurrentOptions();
  950. Close();
  951. ASSERT_OK(DestroyDB(dbname_, options));
  952. options.level0_stop_writes_trigger = 1;
  953. options.level0_slowdown_writes_trigger = 2;
  954. options.level0_file_num_compaction_trigger = 3;
  955. ASSERT_OK(DB::Open(options, dbname_, &db_));
  956. }
  957. TEST_F(DBTest, GetOrderedByLevels) {
  958. do {
  959. CreateAndReopenWithCF({"pikachu"}, CurrentOptions());
  960. ASSERT_OK(Put(1, "foo", "v1"));
  961. Compact(1, "a", "z");
  962. ASSERT_EQ("v1", Get(1, "foo"));
  963. ASSERT_OK(Put(1, "foo", "v2"));
  964. ASSERT_EQ("v2", Get(1, "foo"));
  965. ASSERT_OK(Flush(1));
  966. ASSERT_EQ("v2", Get(1, "foo"));
  967. } while (ChangeOptions());
  968. }
  969. TEST_F(DBTest, GetPicksCorrectFile) {
  970. do {
  971. CreateAndReopenWithCF({"pikachu"}, CurrentOptions());
  972. // Arrange to have multiple files in a non-level-0 level.
  973. ASSERT_OK(Put(1, "a", "va"));
  974. Compact(1, "a", "b");
  975. ASSERT_OK(Put(1, "x", "vx"));
  976. Compact(1, "x", "y");
  977. ASSERT_OK(Put(1, "f", "vf"));
  978. Compact(1, "f", "g");
  979. ASSERT_EQ("va", Get(1, "a"));
  980. ASSERT_EQ("vf", Get(1, "f"));
  981. ASSERT_EQ("vx", Get(1, "x"));
  982. } while (ChangeOptions());
  983. }
  984. TEST_F(DBTest, GetEncountersEmptyLevel) {
  985. do {
  986. Options options = CurrentOptions();
  987. CreateAndReopenWithCF({"pikachu"}, options);
  988. // Arrange for the following to happen:
  989. // * sstable A in level 0
  990. // * nothing in level 1
  991. // * sstable B in level 2
  992. // Then do enough Get() calls to arrange for an automatic compaction
  993. // of sstable A. A bug would cause the compaction to be marked as
  994. // occurring at level 1 (instead of the correct level 0).
  995. // Step 1: First place sstables in levels 0 and 2
  996. ASSERT_OK(Put(1, "a", "begin"));
  997. ASSERT_OK(Put(1, "z", "end"));
  998. ASSERT_OK(Flush(1));
  999. ASSERT_OK(dbfull()->TEST_CompactRange(0, nullptr, nullptr, handles_[1]));
  1000. ASSERT_OK(dbfull()->TEST_CompactRange(1, nullptr, nullptr, handles_[1]));
  1001. ASSERT_OK(Put(1, "a", "begin"));
  1002. ASSERT_OK(Put(1, "z", "end"));
  1003. ASSERT_OK(Flush(1));
  1004. ASSERT_GT(NumTableFilesAtLevel(0, 1), 0);
  1005. ASSERT_GT(NumTableFilesAtLevel(2, 1), 0);
  1006. // Step 2: clear level 1 if necessary.
  1007. ASSERT_OK(dbfull()->TEST_CompactRange(1, nullptr, nullptr, handles_[1]));
  1008. ASSERT_EQ(NumTableFilesAtLevel(0, 1), 1);
  1009. ASSERT_EQ(NumTableFilesAtLevel(1, 1), 0);
  1010. ASSERT_EQ(NumTableFilesAtLevel(2, 1), 1);
  1011. // Step 3: read a bunch of times
  1012. for (int i = 0; i < 1000; i++) {
  1013. ASSERT_EQ("NOT_FOUND", Get(1, "missing"));
  1014. }
  1015. // Step 4: Wait for compaction to finish
  1016. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  1017. ASSERT_EQ(NumTableFilesAtLevel(0, 1), 1); // XXX
  1018. } while (ChangeOptions(kSkipUniversalCompaction | kSkipFIFOCompaction));
  1019. }
  1020. TEST_F(DBTest, FlushMultipleMemtable) {
  1021. do {
  1022. Options options = CurrentOptions();
  1023. WriteOptions writeOpt = WriteOptions();
  1024. writeOpt.disableWAL = true;
  1025. options.max_write_buffer_number = 4;
  1026. options.min_write_buffer_number_to_merge = 3;
  1027. options.max_write_buffer_size_to_maintain = -1;
  1028. CreateAndReopenWithCF({"pikachu"}, options);
  1029. ASSERT_OK(dbfull()->Put(writeOpt, handles_[1], "foo", "v1"));
  1030. ASSERT_OK(Flush(1));
  1031. ASSERT_OK(dbfull()->Put(writeOpt, handles_[1], "bar", "v1"));
  1032. ASSERT_EQ("v1", Get(1, "foo"));
  1033. ASSERT_EQ("v1", Get(1, "bar"));
  1034. ASSERT_OK(Flush(1));
  1035. } while (ChangeCompactOptions());
  1036. }
  1037. TEST_F(DBTest, FlushSchedule) {
  1038. Options options = CurrentOptions();
  1039. options.disable_auto_compactions = true;
  1040. options.level0_stop_writes_trigger = 1 << 10;
  1041. options.level0_slowdown_writes_trigger = 1 << 10;
  1042. options.min_write_buffer_number_to_merge = 1;
  1043. options.max_write_buffer_size_to_maintain =
  1044. static_cast<int64_t>(options.write_buffer_size);
  1045. options.max_write_buffer_number = 2;
  1046. options.write_buffer_size = 120 * 1024;
  1047. auto flush_listener = std::make_shared<FlushCounterListener>();
  1048. flush_listener->expected_flush_reason = FlushReason::kWriteBufferFull;
  1049. options.listeners.push_back(flush_listener);
  1050. CreateAndReopenWithCF({"pikachu"}, options);
  1051. std::vector<port::Thread> threads;
  1052. std::atomic<int> thread_num(0);
  1053. // each column family will have 5 thread, each thread generating 2 memtables.
  1054. // each column family should end up with 10 table files
  1055. std::function<void()> fill_memtable_func = [&]() {
  1056. int a = thread_num.fetch_add(1);
  1057. Random rnd(a);
  1058. WriteOptions wo;
  1059. // this should fill up 2 memtables
  1060. for (int k = 0; k < 5000; ++k) {
  1061. ASSERT_OK(db_->Put(wo, handles_[a & 1], rnd.RandomString(13), ""));
  1062. }
  1063. };
  1064. for (int i = 0; i < 10; ++i) {
  1065. threads.emplace_back(fill_memtable_func);
  1066. }
  1067. for (auto& t : threads) {
  1068. t.join();
  1069. }
  1070. auto default_tables = GetNumberOfSstFilesForColumnFamily(db_, "default");
  1071. auto pikachu_tables = GetNumberOfSstFilesForColumnFamily(db_, "pikachu");
  1072. ASSERT_LE(default_tables, static_cast<uint64_t>(10));
  1073. ASSERT_GT(default_tables, static_cast<uint64_t>(0));
  1074. ASSERT_LE(pikachu_tables, static_cast<uint64_t>(10));
  1075. ASSERT_GT(pikachu_tables, static_cast<uint64_t>(0));
  1076. }
  1077. namespace {
  1078. class KeepFilter : public CompactionFilter {
  1079. public:
  1080. bool Filter(int /*level*/, const Slice& /*key*/, const Slice& /*value*/,
  1081. std::string* /*new_value*/,
  1082. bool* /*value_changed*/) const override {
  1083. return false;
  1084. }
  1085. const char* Name() const override { return "KeepFilter"; }
  1086. };
  1087. class KeepFilterFactory : public CompactionFilterFactory {
  1088. public:
  1089. explicit KeepFilterFactory(bool check_context = false)
  1090. : check_context_(check_context) {}
  1091. std::unique_ptr<CompactionFilter> CreateCompactionFilter(
  1092. const CompactionFilter::Context& context) override {
  1093. if (check_context_) {
  1094. EXPECT_EQ(expect_full_compaction_.load(), context.is_full_compaction);
  1095. EXPECT_EQ(expect_manual_compaction_.load(), context.is_manual_compaction);
  1096. }
  1097. return std::unique_ptr<CompactionFilter>(new KeepFilter());
  1098. }
  1099. const char* Name() const override { return "KeepFilterFactory"; }
  1100. bool check_context_;
  1101. std::atomic_bool expect_full_compaction_;
  1102. std::atomic_bool expect_manual_compaction_;
  1103. };
  1104. class DelayFilter : public CompactionFilter {
  1105. public:
  1106. explicit DelayFilter(DBTestBase* d) : db_test(d) {}
  1107. bool Filter(int /*level*/, const Slice& /*key*/, const Slice& /*value*/,
  1108. std::string* /*new_value*/,
  1109. bool* /*value_changed*/) const override {
  1110. db_test->env_->MockSleepForMicroseconds(1000);
  1111. return true;
  1112. }
  1113. const char* Name() const override { return "DelayFilter"; }
  1114. private:
  1115. DBTestBase* db_test;
  1116. };
  1117. class DelayFilterFactory : public CompactionFilterFactory {
  1118. public:
  1119. explicit DelayFilterFactory(DBTestBase* d) : db_test(d) {}
  1120. std::unique_ptr<CompactionFilter> CreateCompactionFilter(
  1121. const CompactionFilter::Context& /*context*/) override {
  1122. return std::unique_ptr<CompactionFilter>(new DelayFilter(db_test));
  1123. }
  1124. const char* Name() const override { return "DelayFilterFactory"; }
  1125. private:
  1126. DBTestBase* db_test;
  1127. };
  1128. } // anonymous namespace
  1129. TEST_F(DBTest, FailMoreDbPaths) {
  1130. Options options = CurrentOptions();
  1131. options.db_paths.emplace_back(dbname_, 10000000);
  1132. options.db_paths.emplace_back(dbname_ + "_2", 1000000);
  1133. options.db_paths.emplace_back(dbname_ + "_3", 1000000);
  1134. options.db_paths.emplace_back(dbname_ + "_4", 1000000);
  1135. options.db_paths.emplace_back(dbname_ + "_5", 1000000);
  1136. ASSERT_TRUE(TryReopen(options).IsNotSupported());
  1137. }
  1138. void CheckColumnFamilyMeta(
  1139. const ColumnFamilyMetaData& cf_meta, const std::string& cf_name,
  1140. const std::vector<std::vector<FileMetaData>>& files_by_level,
  1141. uint64_t start_time, uint64_t end_time) {
  1142. ASSERT_EQ(cf_meta.name, cf_name);
  1143. ASSERT_EQ(cf_meta.levels.size(), files_by_level.size());
  1144. uint64_t cf_size = 0;
  1145. size_t file_count = 0;
  1146. for (size_t i = 0; i < cf_meta.levels.size(); ++i) {
  1147. const auto& level_meta_from_cf = cf_meta.levels[i];
  1148. const auto& level_meta_from_files = files_by_level[i];
  1149. ASSERT_EQ(level_meta_from_cf.level, i);
  1150. ASSERT_EQ(level_meta_from_cf.files.size(), level_meta_from_files.size());
  1151. file_count += level_meta_from_cf.files.size();
  1152. uint64_t level_size = 0;
  1153. for (size_t j = 0; j < level_meta_from_cf.files.size(); ++j) {
  1154. const auto& file_meta_from_cf = level_meta_from_cf.files[j];
  1155. const auto& file_meta_from_files = level_meta_from_files[j];
  1156. level_size += file_meta_from_cf.size;
  1157. ASSERT_EQ(file_meta_from_cf.file_number,
  1158. file_meta_from_files.fd.GetNumber());
  1159. ASSERT_EQ(file_meta_from_cf.file_number,
  1160. TableFileNameToNumber(file_meta_from_cf.name));
  1161. ASSERT_EQ(file_meta_from_cf.size, file_meta_from_files.fd.file_size);
  1162. ASSERT_EQ(file_meta_from_cf.smallest_seqno,
  1163. file_meta_from_files.fd.smallest_seqno);
  1164. ASSERT_EQ(file_meta_from_cf.largest_seqno,
  1165. file_meta_from_files.fd.largest_seqno);
  1166. ASSERT_EQ(file_meta_from_cf.smallestkey,
  1167. file_meta_from_files.smallest.user_key().ToString());
  1168. ASSERT_EQ(file_meta_from_cf.largestkey,
  1169. file_meta_from_files.largest.user_key().ToString());
  1170. ASSERT_EQ(file_meta_from_cf.oldest_blob_file_number,
  1171. file_meta_from_files.oldest_blob_file_number);
  1172. ASSERT_EQ(file_meta_from_cf.oldest_ancester_time,
  1173. file_meta_from_files.oldest_ancester_time);
  1174. ASSERT_EQ(file_meta_from_cf.file_creation_time,
  1175. file_meta_from_files.file_creation_time);
  1176. ASSERT_GE(file_meta_from_cf.file_creation_time, start_time);
  1177. ASSERT_LE(file_meta_from_cf.file_creation_time, end_time);
  1178. ASSERT_EQ(file_meta_from_cf.epoch_number,
  1179. file_meta_from_files.epoch_number);
  1180. ASSERT_GE(file_meta_from_cf.oldest_ancester_time, start_time);
  1181. ASSERT_LE(file_meta_from_cf.oldest_ancester_time, end_time);
  1182. // More from FileStorageInfo
  1183. ASSERT_EQ(file_meta_from_cf.file_type, kTableFile);
  1184. ASSERT_EQ(file_meta_from_cf.name,
  1185. "/" + file_meta_from_cf.relative_filename);
  1186. ASSERT_EQ(file_meta_from_cf.directory, file_meta_from_cf.db_path);
  1187. }
  1188. ASSERT_EQ(level_meta_from_cf.size, level_size);
  1189. cf_size += level_size;
  1190. }
  1191. ASSERT_EQ(cf_meta.file_count, file_count);
  1192. ASSERT_EQ(cf_meta.size, cf_size);
  1193. }
  1194. void CheckLiveFilesMeta(
  1195. const std::vector<LiveFileMetaData>& live_file_meta,
  1196. const std::vector<std::vector<FileMetaData>>& files_by_level) {
  1197. size_t total_file_count = 0;
  1198. for (const auto& f : files_by_level) {
  1199. total_file_count += f.size();
  1200. }
  1201. ASSERT_EQ(live_file_meta.size(), total_file_count);
  1202. int level = 0;
  1203. int i = 0;
  1204. for (const auto& meta : live_file_meta) {
  1205. if (level != meta.level) {
  1206. level = meta.level;
  1207. i = 0;
  1208. }
  1209. ASSERT_LT(i, files_by_level[level].size());
  1210. const auto& expected_meta = files_by_level[level][i];
  1211. ASSERT_EQ(meta.column_family_name, kDefaultColumnFamilyName);
  1212. ASSERT_EQ(meta.file_number, expected_meta.fd.GetNumber());
  1213. ASSERT_EQ(meta.file_number, TableFileNameToNumber(meta.name));
  1214. ASSERT_EQ(meta.size, expected_meta.fd.file_size);
  1215. ASSERT_EQ(meta.smallest_seqno, expected_meta.fd.smallest_seqno);
  1216. ASSERT_EQ(meta.largest_seqno, expected_meta.fd.largest_seqno);
  1217. ASSERT_EQ(meta.smallestkey, expected_meta.smallest.user_key().ToString());
  1218. ASSERT_EQ(meta.largestkey, expected_meta.largest.user_key().ToString());
  1219. ASSERT_EQ(meta.oldest_blob_file_number,
  1220. expected_meta.oldest_blob_file_number);
  1221. ASSERT_EQ(meta.epoch_number, expected_meta.epoch_number);
  1222. // More from FileStorageInfo
  1223. ASSERT_EQ(meta.file_type, kTableFile);
  1224. ASSERT_EQ(meta.name, "/" + meta.relative_filename);
  1225. ASSERT_EQ(meta.directory, meta.db_path);
  1226. ++i;
  1227. }
  1228. }
  1229. void AddBlobFile(const ColumnFamilyHandle* cfh, uint64_t blob_file_number,
  1230. uint64_t total_blob_count, uint64_t total_blob_bytes,
  1231. const std::string& checksum_method,
  1232. const std::string& checksum_value,
  1233. uint64_t garbage_blob_count = 0,
  1234. uint64_t garbage_blob_bytes = 0) {
  1235. ColumnFamilyData* cfd =
  1236. (static_cast<const ColumnFamilyHandleImpl*>(cfh))->cfd();
  1237. assert(cfd);
  1238. Version* const version = cfd->current();
  1239. assert(version);
  1240. VersionStorageInfo* const storage_info = version->storage_info();
  1241. assert(storage_info);
  1242. // Add a live blob file.
  1243. auto shared_meta = SharedBlobFileMetaData::Create(
  1244. blob_file_number, total_blob_count, total_blob_bytes, checksum_method,
  1245. checksum_value);
  1246. auto meta = BlobFileMetaData::Create(std::move(shared_meta),
  1247. BlobFileMetaData::LinkedSsts(),
  1248. garbage_blob_count, garbage_blob_bytes);
  1249. storage_info->AddBlobFile(std::move(meta));
  1250. }
  1251. static void CheckBlobMetaData(
  1252. const BlobMetaData& bmd, uint64_t blob_file_number,
  1253. uint64_t total_blob_count, uint64_t total_blob_bytes,
  1254. const std::string& checksum_method, const std::string& checksum_value,
  1255. uint64_t garbage_blob_count = 0, uint64_t garbage_blob_bytes = 0) {
  1256. ASSERT_EQ(bmd.blob_file_number, blob_file_number);
  1257. ASSERT_EQ(bmd.blob_file_name, BlobFileName("", blob_file_number));
  1258. ASSERT_EQ(bmd.blob_file_size,
  1259. total_blob_bytes + BlobLogHeader::kSize + BlobLogFooter::kSize);
  1260. ASSERT_EQ(bmd.total_blob_count, total_blob_count);
  1261. ASSERT_EQ(bmd.total_blob_bytes, total_blob_bytes);
  1262. ASSERT_EQ(bmd.garbage_blob_count, garbage_blob_count);
  1263. ASSERT_EQ(bmd.garbage_blob_bytes, garbage_blob_bytes);
  1264. ASSERT_EQ(bmd.checksum_method, checksum_method);
  1265. ASSERT_EQ(bmd.checksum_value, checksum_value);
  1266. }
  1267. TEST_F(DBTest, MetaDataTest) {
  1268. Options options = CurrentOptions();
  1269. options.create_if_missing = true;
  1270. options.disable_auto_compactions = true;
  1271. int64_t temp_time = 0;
  1272. ASSERT_OK(options.env->GetCurrentTime(&temp_time));
  1273. uint64_t start_time = static_cast<uint64_t>(temp_time);
  1274. DestroyAndReopen(options);
  1275. Random rnd(301);
  1276. int key_index = 0;
  1277. for (int i = 0; i < 100; ++i) {
  1278. // Add a single blob reference to each file
  1279. std::string blob_index;
  1280. BlobIndex::EncodeBlob(&blob_index, /* blob_file_number */ i + 1000,
  1281. /* offset */ 1234, /* size */ 5678, kNoCompression);
  1282. WriteBatch batch;
  1283. ASSERT_OK(WriteBatchInternal::PutBlobIndex(&batch, 0, Key(key_index),
  1284. blob_index));
  1285. ASSERT_OK(dbfull()->Write(WriteOptions(), &batch));
  1286. ++key_index;
  1287. // Fill up the rest of the file with random values.
  1288. GenerateNewFile(&rnd, &key_index, /* nowait */ true);
  1289. ASSERT_OK(Flush());
  1290. }
  1291. std::vector<std::vector<FileMetaData>> files_by_level;
  1292. dbfull()->TEST_GetFilesMetaData(db_->DefaultColumnFamily(), &files_by_level);
  1293. ASSERT_OK(options.env->GetCurrentTime(&temp_time));
  1294. uint64_t end_time = static_cast<uint64_t>(temp_time);
  1295. ColumnFamilyMetaData cf_meta;
  1296. db_->GetColumnFamilyMetaData(&cf_meta);
  1297. CheckColumnFamilyMeta(cf_meta, kDefaultColumnFamilyName, files_by_level,
  1298. start_time, end_time);
  1299. std::vector<LiveFileMetaData> live_file_meta;
  1300. db_->GetLiveFilesMetaData(&live_file_meta);
  1301. CheckLiveFilesMeta(live_file_meta, files_by_level);
  1302. }
  1303. TEST_F(DBTest, AllMetaDataTest) {
  1304. Options options = CurrentOptions();
  1305. options.create_if_missing = true;
  1306. options.disable_auto_compactions = true;
  1307. DestroyAndReopen(options);
  1308. CreateAndReopenWithCF({"pikachu"}, options);
  1309. constexpr uint64_t blob_file_number = 234;
  1310. constexpr uint64_t total_blob_count = 555;
  1311. constexpr uint64_t total_blob_bytes = 66666;
  1312. constexpr char checksum_method[] = "CRC32";
  1313. constexpr char checksum_value[] = "\x3d\x87\xff\x57";
  1314. int64_t temp_time = 0;
  1315. options.env->GetCurrentTime(&temp_time).PermitUncheckedError();
  1316. uint64_t start_time = static_cast<uint64_t>(temp_time);
  1317. Random rnd(301);
  1318. dbfull()->TEST_LockMutex();
  1319. for (int cf = 0; cf < 2; cf++) {
  1320. AddBlobFile(handles_[cf], blob_file_number * (cf + 1),
  1321. total_blob_count * (cf + 1), total_blob_bytes * (cf + 1),
  1322. checksum_method, checksum_value);
  1323. }
  1324. dbfull()->TEST_UnlockMutex();
  1325. std::vector<ColumnFamilyMetaData> all_meta;
  1326. db_->GetAllColumnFamilyMetaData(&all_meta);
  1327. std::vector<std::vector<FileMetaData>> default_files_by_level;
  1328. std::vector<std::vector<FileMetaData>> pikachu_files_by_level;
  1329. dbfull()->TEST_GetFilesMetaData(handles_[0], &default_files_by_level);
  1330. dbfull()->TEST_GetFilesMetaData(handles_[1], &pikachu_files_by_level);
  1331. options.env->GetCurrentTime(&temp_time).PermitUncheckedError();
  1332. uint64_t end_time = static_cast<uint64_t>(temp_time);
  1333. ASSERT_EQ(all_meta.size(), 2);
  1334. for (int cf = 0; cf < 2; cf++) {
  1335. const auto& cfmd = all_meta[cf];
  1336. if (cf == 0) {
  1337. CheckColumnFamilyMeta(cfmd, "default", default_files_by_level, start_time,
  1338. end_time);
  1339. } else {
  1340. CheckColumnFamilyMeta(cfmd, "pikachu", pikachu_files_by_level, start_time,
  1341. end_time);
  1342. }
  1343. ASSERT_EQ(cfmd.blob_files.size(), 1U);
  1344. const auto& bmd = cfmd.blob_files[0];
  1345. ASSERT_EQ(cfmd.blob_file_count, 1U);
  1346. ASSERT_EQ(cfmd.blob_file_size, bmd.blob_file_size);
  1347. ASSERT_EQ(NormalizePath(bmd.blob_file_path), NormalizePath(dbname_));
  1348. CheckBlobMetaData(bmd, blob_file_number * (cf + 1),
  1349. total_blob_count * (cf + 1), total_blob_bytes * (cf + 1),
  1350. checksum_method, checksum_value);
  1351. }
  1352. }
  1353. namespace {
  1354. void MinLevelHelper(DBTest* self, Options& options) {
  1355. Random rnd(301);
  1356. for (int num = 0; num < options.level0_file_num_compaction_trigger - 1;
  1357. num++) {
  1358. std::vector<std::string> values;
  1359. // Write 120KB (12 values, each 10K)
  1360. for (int i = 0; i < 12; i++) {
  1361. values.push_back(rnd.RandomString(10000));
  1362. ASSERT_OK(self->Put(DBTestBase::Key(i), values[i]));
  1363. }
  1364. ASSERT_OK(self->dbfull()->TEST_WaitForFlushMemTable());
  1365. ASSERT_EQ(self->NumTableFilesAtLevel(0), num + 1);
  1366. }
  1367. // generate one more file in level-0, and should trigger level-0 compaction
  1368. std::vector<std::string> values;
  1369. for (int i = 0; i < 12; i++) {
  1370. values.push_back(rnd.RandomString(10000));
  1371. ASSERT_OK(self->Put(DBTestBase::Key(i), values[i]));
  1372. }
  1373. ASSERT_OK(self->dbfull()->TEST_WaitForCompact());
  1374. ASSERT_EQ(self->NumTableFilesAtLevel(0), 0);
  1375. ASSERT_EQ(self->NumTableFilesAtLevel(1), 1);
  1376. }
  1377. // returns false if the calling-Test should be skipped
  1378. bool MinLevelToCompress(CompressionType& type, Options& options, int wbits,
  1379. int lev, int strategy) {
  1380. fprintf(stderr,
  1381. "Test with compression options : window_bits = %d, level = %d, "
  1382. "strategy = %d}\n",
  1383. wbits, lev, strategy);
  1384. options.write_buffer_size = 100 << 10; // 100KB
  1385. options.arena_block_size = 4096;
  1386. options.num_levels = 3;
  1387. options.level0_file_num_compaction_trigger = 3;
  1388. options.create_if_missing = true;
  1389. if (Snappy_Supported()) {
  1390. type = kSnappyCompression;
  1391. fprintf(stderr, "using snappy\n");
  1392. } else if (Zlib_Supported()) {
  1393. type = kZlibCompression;
  1394. fprintf(stderr, "using zlib\n");
  1395. } else if (BZip2_Supported()) {
  1396. type = kBZip2Compression;
  1397. fprintf(stderr, "using bzip2\n");
  1398. } else if (LZ4_Supported()) {
  1399. type = kLZ4Compression;
  1400. fprintf(stderr, "using lz4\n");
  1401. } else if (XPRESS_Supported()) {
  1402. type = kXpressCompression;
  1403. fprintf(stderr, "using xpress\n");
  1404. } else if (ZSTD_Supported()) {
  1405. type = kZSTD;
  1406. fprintf(stderr, "using ZSTD\n");
  1407. } else {
  1408. fprintf(stderr, "skipping test, compression disabled\n");
  1409. return false;
  1410. }
  1411. options.compression_per_level.resize(options.num_levels);
  1412. // do not compress L0
  1413. for (int i = 0; i < 1; i++) {
  1414. options.compression_per_level[i] = kNoCompression;
  1415. }
  1416. for (int i = 1; i < options.num_levels; i++) {
  1417. options.compression_per_level[i] = type;
  1418. }
  1419. return true;
  1420. }
  1421. } // anonymous namespace
  1422. TEST_F(DBTest, MinLevelToCompress1) {
  1423. Options options = CurrentOptions();
  1424. CompressionType type = kSnappyCompression;
  1425. if (!MinLevelToCompress(type, options, -14, -1, 0)) {
  1426. return;
  1427. }
  1428. Reopen(options);
  1429. MinLevelHelper(this, options);
  1430. // do not compress L0 and L1
  1431. for (int i = 0; i < 2; i++) {
  1432. options.compression_per_level[i] = kNoCompression;
  1433. }
  1434. for (int i = 2; i < options.num_levels; i++) {
  1435. options.compression_per_level[i] = type;
  1436. }
  1437. DestroyAndReopen(options);
  1438. MinLevelHelper(this, options);
  1439. }
  1440. TEST_F(DBTest, MinLevelToCompress2) {
  1441. Options options = CurrentOptions();
  1442. CompressionType type = kSnappyCompression;
  1443. if (!MinLevelToCompress(type, options, 15, -1, 0)) {
  1444. return;
  1445. }
  1446. Reopen(options);
  1447. MinLevelHelper(this, options);
  1448. // do not compress L0 and L1
  1449. for (int i = 0; i < 2; i++) {
  1450. options.compression_per_level[i] = kNoCompression;
  1451. }
  1452. for (int i = 2; i < options.num_levels; i++) {
  1453. options.compression_per_level[i] = type;
  1454. }
  1455. DestroyAndReopen(options);
  1456. MinLevelHelper(this, options);
  1457. }
  1458. // This test may fail because of a legit case that multiple L0 files
  1459. // are trivial moved to L1.
  1460. TEST_F(DBTest, DISABLED_RepeatedWritesToSameKey) {
  1461. do {
  1462. Options options = CurrentOptions();
  1463. options.env = env_;
  1464. options.write_buffer_size = 100000; // Small write buffer
  1465. CreateAndReopenWithCF({"pikachu"}, options);
  1466. // We must have at most one file per level except for level-0,
  1467. // which may have up to kL0_StopWritesTrigger files.
  1468. const int kMaxFiles =
  1469. options.num_levels + options.level0_stop_writes_trigger;
  1470. Random rnd(301);
  1471. std::string value =
  1472. rnd.RandomString(static_cast<int>(2 * options.write_buffer_size));
  1473. for (int i = 0; i < 5 * kMaxFiles; i++) {
  1474. ASSERT_OK(Put(1, "key", value));
  1475. ASSERT_LE(TotalTableFiles(1), kMaxFiles);
  1476. }
  1477. } while (ChangeCompactOptions());
  1478. }
  1479. static bool Between(uint64_t val, uint64_t low, uint64_t high) {
  1480. bool result = (val >= low) && (val <= high);
  1481. if (!result) {
  1482. fprintf(stderr, "Value %llu is not in range [%llu, %llu]\n",
  1483. (unsigned long long)(val), (unsigned long long)(low),
  1484. (unsigned long long)(high));
  1485. }
  1486. return result;
  1487. }
  1488. TEST_F(DBTest, ApproximateSizesMemTable) {
  1489. Options options = CurrentOptions();
  1490. options.write_buffer_size = 100000000; // Large write buffer
  1491. options.compression = kNoCompression;
  1492. options.create_if_missing = true;
  1493. DestroyAndReopen(options);
  1494. auto default_cf = db_->DefaultColumnFamily();
  1495. const int N = 128;
  1496. Random rnd(301);
  1497. for (int i = 0; i < N; i++) {
  1498. ASSERT_OK(Put(Key(i), rnd.RandomString(1024)));
  1499. }
  1500. uint64_t size;
  1501. std::string start = Key(50);
  1502. std::string end = Key(60);
  1503. Range r(start, end);
  1504. SizeApproximationOptions size_approx_options;
  1505. size_approx_options.include_memtables = true;
  1506. size_approx_options.include_files = true;
  1507. ASSERT_OK(
  1508. db_->GetApproximateSizes(size_approx_options, default_cf, &r, 1, &size));
  1509. ASSERT_GT(size, 6000);
  1510. ASSERT_LT(size, 204800);
  1511. // Zero if not including mem table
  1512. ASSERT_OK(db_->GetApproximateSizes(&r, 1, &size));
  1513. ASSERT_EQ(size, 0);
  1514. start = Key(500);
  1515. end = Key(600);
  1516. r = Range(start, end);
  1517. ASSERT_OK(
  1518. db_->GetApproximateSizes(size_approx_options, default_cf, &r, 1, &size));
  1519. ASSERT_EQ(size, 0);
  1520. for (int i = 0; i < N; i++) {
  1521. ASSERT_OK(Put(Key(1000 + i), rnd.RandomString(1024)));
  1522. }
  1523. start = Key(500);
  1524. end = Key(600);
  1525. r = Range(start, end);
  1526. ASSERT_OK(
  1527. db_->GetApproximateSizes(size_approx_options, default_cf, &r, 1, &size));
  1528. ASSERT_EQ(size, 0);
  1529. start = Key(100);
  1530. end = Key(1020);
  1531. r = Range(start, end);
  1532. ASSERT_OK(
  1533. db_->GetApproximateSizes(size_approx_options, default_cf, &r, 1, &size));
  1534. ASSERT_GT(size, 6000);
  1535. options.max_write_buffer_number = 8;
  1536. options.min_write_buffer_number_to_merge = 5;
  1537. options.write_buffer_size = 1024 * N; // Not very large
  1538. DestroyAndReopen(options);
  1539. default_cf = db_->DefaultColumnFamily();
  1540. int keys[N * 3];
  1541. for (int i = 0; i < N; i++) {
  1542. keys[i * 3] = i * 5;
  1543. keys[i * 3 + 1] = i * 5 + 1;
  1544. keys[i * 3 + 2] = i * 5 + 2;
  1545. }
  1546. // MemTable entry counting is estimated and can vary greatly depending on
  1547. // layout. Thus, using deterministic seed for test stability.
  1548. RandomShuffle(std::begin(keys), std::end(keys), rnd.Next());
  1549. for (int i = 0; i < N * 3; i++) {
  1550. ASSERT_OK(Put(Key(keys[i] + 1000), rnd.RandomString(1024)));
  1551. }
  1552. start = Key(100);
  1553. end = Key(300);
  1554. r = Range(start, end);
  1555. ASSERT_OK(
  1556. db_->GetApproximateSizes(size_approx_options, default_cf, &r, 1, &size));
  1557. ASSERT_EQ(size, 0);
  1558. start = Key(1050);
  1559. end = Key(1080);
  1560. r = Range(start, end);
  1561. ASSERT_OK(
  1562. db_->GetApproximateSizes(size_approx_options, default_cf, &r, 1, &size));
  1563. ASSERT_GT(size, 6000);
  1564. start = Key(2100);
  1565. end = Key(2300);
  1566. r = Range(start, end);
  1567. ASSERT_OK(
  1568. db_->GetApproximateSizes(size_approx_options, default_cf, &r, 1, &size));
  1569. ASSERT_EQ(size, 0);
  1570. start = Key(1050);
  1571. end = Key(1080);
  1572. r = Range(start, end);
  1573. uint64_t size_with_mt, size_without_mt;
  1574. ASSERT_OK(db_->GetApproximateSizes(size_approx_options, default_cf, &r, 1,
  1575. &size_with_mt));
  1576. ASSERT_GT(size_with_mt, 6000);
  1577. ASSERT_OK(db_->GetApproximateSizes(&r, 1, &size_without_mt));
  1578. ASSERT_EQ(size_without_mt, 0);
  1579. ASSERT_OK(Flush());
  1580. for (int i = 0; i < N; i++) {
  1581. ASSERT_OK(Put(Key(i + 1000), rnd.RandomString(1024)));
  1582. }
  1583. start = Key(1050);
  1584. end = Key(1080);
  1585. r = Range(start, end);
  1586. ASSERT_OK(db_->GetApproximateSizes(size_approx_options, default_cf, &r, 1,
  1587. &size_with_mt));
  1588. ASSERT_OK(db_->GetApproximateSizes(&r, 1, &size_without_mt));
  1589. ASSERT_GT(size_with_mt, size_without_mt);
  1590. ASSERT_GT(size_without_mt, 6000);
  1591. // Check that include_memtables flag works as expected
  1592. size_approx_options.include_memtables = false;
  1593. ASSERT_OK(
  1594. db_->GetApproximateSizes(size_approx_options, default_cf, &r, 1, &size));
  1595. ASSERT_EQ(size, size_without_mt);
  1596. // Check that files_size_error_margin works as expected, when the heuristic
  1597. // conditions are not met
  1598. start = Key(1);
  1599. end = Key(1000 + N - 2);
  1600. r = Range(start, end);
  1601. size_approx_options.files_size_error_margin = -1.0; // disabled
  1602. ASSERT_OK(
  1603. db_->GetApproximateSizes(size_approx_options, default_cf, &r, 1, &size));
  1604. uint64_t size2;
  1605. size_approx_options.files_size_error_margin = 0.5; // enabled, but not used
  1606. ASSERT_OK(
  1607. db_->GetApproximateSizes(size_approx_options, default_cf, &r, 1, &size2));
  1608. ASSERT_EQ(size, size2);
  1609. }
  1610. TEST_F(DBTest, ApproximateSizesFilesWithErrorMargin) {
  1611. // Roughly 4 keys per data block, 1000 keys per file,
  1612. // with filter substantially larger than a data block
  1613. BlockBasedTableOptions table_options;
  1614. table_options.filter_policy.reset(NewBloomFilterPolicy(16));
  1615. table_options.block_size = 100;
  1616. Options options = CurrentOptions();
  1617. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1618. options.write_buffer_size = 24 * 1024;
  1619. options.compression = kNoCompression;
  1620. options.create_if_missing = true;
  1621. options.target_file_size_base = 24 * 1024;
  1622. DestroyAndReopen(options);
  1623. const auto default_cf = db_->DefaultColumnFamily();
  1624. const int N = 64000;
  1625. Random rnd(301);
  1626. for (int i = 0; i < N; i++) {
  1627. ASSERT_OK(Put(Key(i), rnd.RandomString(24)));
  1628. }
  1629. // Flush everything to files
  1630. ASSERT_OK(Flush());
  1631. // Compact the entire key space into the next level
  1632. ASSERT_OK(
  1633. db_->CompactRange(CompactRangeOptions(), default_cf, nullptr, nullptr));
  1634. // Write more keys
  1635. for (int i = N; i < (N + N / 4); i++) {
  1636. ASSERT_OK(Put(Key(i), rnd.RandomString(24)));
  1637. }
  1638. // Flush everything to files again
  1639. ASSERT_OK(Flush());
  1640. // Wait for compaction to finish
  1641. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  1642. {
  1643. const std::string start = Key(0);
  1644. const std::string end = Key(2 * N);
  1645. const Range r(start, end);
  1646. SizeApproximationOptions size_approx_options;
  1647. size_approx_options.include_memtables = false;
  1648. size_approx_options.include_files = true;
  1649. size_approx_options.files_size_error_margin = -1.0; // disabled
  1650. // Get the precise size without any approximation heuristic
  1651. uint64_t size;
  1652. ASSERT_OK(db_->GetApproximateSizes(size_approx_options, default_cf, &r, 1,
  1653. &size));
  1654. ASSERT_NE(size, 0);
  1655. // Get the size with an approximation heuristic
  1656. uint64_t size2;
  1657. const double error_margin = 0.2;
  1658. size_approx_options.files_size_error_margin = error_margin;
  1659. ASSERT_OK(db_->GetApproximateSizes(size_approx_options, default_cf, &r, 1,
  1660. &size2));
  1661. ASSERT_LT(size2, size * (1 + error_margin));
  1662. ASSERT_GT(size2, size * (1 - error_margin));
  1663. }
  1664. {
  1665. // Ensure that metadata is not falsely attributed only to the last data in
  1666. // the file. (In some applications, filters can be large portion of data
  1667. // size.)
  1668. // Perform many queries over small range, enough to ensure crossing file
  1669. // boundary, and make sure we never see a spike for large filter.
  1670. for (int i = 0; i < 3000; i += 10) {
  1671. const std::string start = Key(i);
  1672. const std::string end = Key(i + 11); // overlap by 1 key
  1673. const Range r(start, end);
  1674. uint64_t size;
  1675. ASSERT_OK(db_->GetApproximateSizes(&r, 1, &size));
  1676. ASSERT_LE(size, 11 * 100);
  1677. }
  1678. }
  1679. }
  1680. TEST_F(DBTest, GetApproximateMemTableStats) {
  1681. Options options = CurrentOptions();
  1682. options.write_buffer_size = 100000000;
  1683. options.compression = kNoCompression;
  1684. options.create_if_missing = true;
  1685. DestroyAndReopen(options);
  1686. const int N = 128;
  1687. Random rnd(301);
  1688. for (int i = 0; i < N; i++) {
  1689. ASSERT_OK(Put(Key(i), rnd.RandomString(1024)));
  1690. }
  1691. uint64_t count;
  1692. uint64_t size;
  1693. // Because Random::GetTLSInstance() seed is reset in DBTestBase,
  1694. // this test is deterministic.
  1695. std::string start = Key(50);
  1696. std::string end = Key(60);
  1697. Range r(start, end);
  1698. db_->GetApproximateMemTableStats(r, &count, &size);
  1699. // When actual count is <= 10, it returns that as the minimum
  1700. EXPECT_EQ(count, 10);
  1701. EXPECT_EQ(size, 10440);
  1702. start = Key(20);
  1703. end = Key(100);
  1704. r = Range(start, end);
  1705. db_->GetApproximateMemTableStats(r, &count, &size);
  1706. EXPECT_EQ(count, 72);
  1707. EXPECT_EQ(size, 75168);
  1708. start = Key(500);
  1709. end = Key(600);
  1710. r = Range(start, end);
  1711. db_->GetApproximateMemTableStats(r, &count, &size);
  1712. EXPECT_EQ(count, 0);
  1713. EXPECT_EQ(size, 0);
  1714. ASSERT_OK(Flush());
  1715. start = Key(50);
  1716. end = Key(60);
  1717. r = Range(start, end);
  1718. db_->GetApproximateMemTableStats(r, &count, &size);
  1719. EXPECT_EQ(count, 0);
  1720. EXPECT_EQ(size, 0);
  1721. for (int i = 0; i < N; i++) {
  1722. ASSERT_OK(Put(Key(1000 + i), rnd.RandomString(1024)));
  1723. }
  1724. start = Key(100);
  1725. end = Key(1020);
  1726. // Actually 20 keys in the range ^^
  1727. r = Range(start, end);
  1728. db_->GetApproximateMemTableStats(r, &count, &size);
  1729. EXPECT_EQ(count, 20);
  1730. EXPECT_EQ(size, 20880);
  1731. }
  1732. TEST_F(DBTest, ApproximateSizes) {
  1733. do {
  1734. Options options = CurrentOptions();
  1735. options.write_buffer_size = 100000000; // Large write buffer
  1736. options.compression = kNoCompression;
  1737. options.create_if_missing = true;
  1738. DestroyAndReopen(options);
  1739. CreateAndReopenWithCF({"pikachu"}, options);
  1740. uint64_t size;
  1741. ASSERT_OK(Size("", "xyz", 1, &size));
  1742. ASSERT_TRUE(Between(size, 0, 0));
  1743. ReopenWithColumnFamilies({"default", "pikachu"}, options);
  1744. ASSERT_OK(Size("", "xyz", 1, &size));
  1745. ASSERT_TRUE(Between(size, 0, 0));
  1746. // Write 8MB (80 values, each 100K)
  1747. ASSERT_EQ(NumTableFilesAtLevel(0, 1), 0);
  1748. const int N = 80;
  1749. static const int S1 = 100000;
  1750. static const int S2 = 105000; // Allow some expansion from metadata
  1751. Random rnd(301);
  1752. for (int i = 0; i < N; i++) {
  1753. ASSERT_OK(Put(1, Key(i), rnd.RandomString(S1)));
  1754. }
  1755. // 0 because GetApproximateSizes() does not account for memtable space
  1756. ASSERT_OK(Size("", Key(50), 1, &size));
  1757. ASSERT_TRUE(Between(size, 0, 0));
  1758. // Check sizes across recovery by reopening a few times
  1759. for (int run = 0; run < 3; run++) {
  1760. ReopenWithColumnFamilies({"default", "pikachu"}, options);
  1761. for (int compact_start = 0; compact_start < N; compact_start += 10) {
  1762. for (int i = 0; i < N; i += 10) {
  1763. ASSERT_OK(Size("", Key(i), 1, &size));
  1764. ASSERT_TRUE(Between(size, S1 * i, S2 * i));
  1765. ASSERT_OK(Size("", Key(i) + ".suffix", 1, &size));
  1766. ASSERT_TRUE(Between(size, S1 * (i + 1), S2 * (i + 1)));
  1767. ASSERT_OK(Size(Key(i), Key(i + 10), 1, &size));
  1768. ASSERT_TRUE(Between(size, S1 * 10, S2 * 10));
  1769. }
  1770. ASSERT_OK(Size("", Key(50), 1, &size));
  1771. ASSERT_TRUE(Between(size, S1 * 50, S2 * 50));
  1772. ASSERT_OK(Size("", Key(50) + ".suffix", 1, &size));
  1773. ASSERT_TRUE(Between(size, S1 * 50, S2 * 50));
  1774. std::string cstart_str = Key(compact_start);
  1775. std::string cend_str = Key(compact_start + 9);
  1776. Slice cstart = cstart_str;
  1777. Slice cend = cend_str;
  1778. ASSERT_OK(dbfull()->TEST_CompactRange(0, &cstart, &cend, handles_[1]));
  1779. }
  1780. ASSERT_EQ(NumTableFilesAtLevel(0, 1), 0);
  1781. ASSERT_GT(NumTableFilesAtLevel(1, 1), 0);
  1782. }
  1783. // ApproximateOffsetOf() is not yet implemented in plain table format.
  1784. } while (ChangeOptions(kSkipUniversalCompaction | kSkipFIFOCompaction |
  1785. kSkipPlainTable | kSkipHashIndex));
  1786. }
  1787. TEST_F(DBTest, ApproximateSizes_MixOfSmallAndLarge) {
  1788. do {
  1789. Options options = CurrentOptions();
  1790. options.compression = kNoCompression;
  1791. CreateAndReopenWithCF({"pikachu"}, options);
  1792. Random rnd(301);
  1793. std::string big1 = rnd.RandomString(100000);
  1794. ASSERT_OK(Put(1, Key(0), rnd.RandomString(10000)));
  1795. ASSERT_OK(Put(1, Key(1), rnd.RandomString(10000)));
  1796. ASSERT_OK(Put(1, Key(2), big1));
  1797. ASSERT_OK(Put(1, Key(3), rnd.RandomString(10000)));
  1798. ASSERT_OK(Put(1, Key(4), big1));
  1799. ASSERT_OK(Put(1, Key(5), rnd.RandomString(10000)));
  1800. ASSERT_OK(Put(1, Key(6), rnd.RandomString(300000)));
  1801. ASSERT_OK(Put(1, Key(7), rnd.RandomString(10000)));
  1802. // Check sizes across recovery by reopening a few times
  1803. uint64_t size;
  1804. for (int run = 0; run < 3; run++) {
  1805. ReopenWithColumnFamilies({"default", "pikachu"}, options);
  1806. ASSERT_OK(Size("", Key(0), 1, &size));
  1807. ASSERT_TRUE(Between(size, 0, 0));
  1808. ASSERT_OK(Size("", Key(1), 1, &size));
  1809. ASSERT_TRUE(Between(size, 10000, 11000));
  1810. ASSERT_OK(Size("", Key(2), 1, &size));
  1811. ASSERT_TRUE(Between(size, 20000, 21000));
  1812. ASSERT_OK(Size("", Key(3), 1, &size));
  1813. ASSERT_TRUE(Between(size, 120000, 121000));
  1814. ASSERT_OK(Size("", Key(4), 1, &size));
  1815. ASSERT_TRUE(Between(size, 130000, 131000));
  1816. ASSERT_OK(Size("", Key(5), 1, &size));
  1817. ASSERT_TRUE(Between(size, 230000, 232000));
  1818. ASSERT_OK(Size("", Key(6), 1, &size));
  1819. ASSERT_TRUE(Between(size, 240000, 242000));
  1820. // Ensure some overhead is accounted for, even without including all
  1821. ASSERT_OK(Size("", Key(7), 1, &size));
  1822. ASSERT_TRUE(Between(size, 540500, 545000));
  1823. ASSERT_OK(Size("", Key(8), 1, &size));
  1824. ASSERT_TRUE(Between(size, 550500, 555000));
  1825. ASSERT_OK(Size(Key(3), Key(5), 1, &size));
  1826. ASSERT_TRUE(Between(size, 110100, 111000));
  1827. ASSERT_OK(dbfull()->TEST_CompactRange(0, nullptr, nullptr, handles_[1]));
  1828. }
  1829. // ApproximateOffsetOf() is not yet implemented in plain table format.
  1830. } while (ChangeOptions(kSkipPlainTable));
  1831. }
  1832. TEST_F(DBTest, Snapshot) {
  1833. env_->SetMockSleep();
  1834. anon::OptionsOverride options_override;
  1835. options_override.skip_policy = kSkipNoSnapshot;
  1836. do {
  1837. CreateAndReopenWithCF({"pikachu"}, CurrentOptions(options_override));
  1838. ASSERT_OK(Put(0, "foo", "0v1"));
  1839. ASSERT_OK(Put(1, "foo", "1v1"));
  1840. const Snapshot* s1 = db_->GetSnapshot();
  1841. ASSERT_EQ(1U, GetNumSnapshots());
  1842. uint64_t time_snap1 = GetTimeOldestSnapshots();
  1843. ASSERT_GT(time_snap1, 0U);
  1844. ASSERT_EQ(GetSequenceOldestSnapshots(), s1->GetSequenceNumber());
  1845. ASSERT_EQ(GetTimeOldestSnapshots(),
  1846. static_cast<uint64_t>(s1->GetUnixTime()));
  1847. ASSERT_OK(Put(0, "foo", "0v2"));
  1848. ASSERT_OK(Put(1, "foo", "1v2"));
  1849. env_->MockSleepForSeconds(1);
  1850. const Snapshot* s2 = db_->GetSnapshot();
  1851. ASSERT_EQ(2U, GetNumSnapshots());
  1852. ASSERT_EQ(time_snap1, GetTimeOldestSnapshots());
  1853. ASSERT_EQ(GetSequenceOldestSnapshots(), s1->GetSequenceNumber());
  1854. ASSERT_EQ(GetTimeOldestSnapshots(),
  1855. static_cast<uint64_t>(s1->GetUnixTime()));
  1856. ASSERT_OK(Put(0, "foo", "0v3"));
  1857. ASSERT_OK(Put(1, "foo", "1v3"));
  1858. {
  1859. ManagedSnapshot s3(db_);
  1860. ASSERT_EQ(3U, GetNumSnapshots());
  1861. ASSERT_EQ(time_snap1, GetTimeOldestSnapshots());
  1862. ASSERT_EQ(GetSequenceOldestSnapshots(), s1->GetSequenceNumber());
  1863. ASSERT_EQ(GetTimeOldestSnapshots(),
  1864. static_cast<uint64_t>(s1->GetUnixTime()));
  1865. ASSERT_OK(Put(0, "foo", "0v4"));
  1866. ASSERT_OK(Put(1, "foo", "1v4"));
  1867. ASSERT_EQ("0v1", Get(0, "foo", s1));
  1868. ASSERT_EQ("1v1", Get(1, "foo", s1));
  1869. ASSERT_EQ("0v2", Get(0, "foo", s2));
  1870. ASSERT_EQ("1v2", Get(1, "foo", s2));
  1871. ASSERT_EQ("0v3", Get(0, "foo", s3.snapshot()));
  1872. ASSERT_EQ("1v3", Get(1, "foo", s3.snapshot()));
  1873. ASSERT_EQ("0v4", Get(0, "foo"));
  1874. ASSERT_EQ("1v4", Get(1, "foo"));
  1875. }
  1876. ASSERT_EQ(2U, GetNumSnapshots());
  1877. ASSERT_EQ(time_snap1, GetTimeOldestSnapshots());
  1878. ASSERT_EQ(GetSequenceOldestSnapshots(), s1->GetSequenceNumber());
  1879. ASSERT_EQ(GetTimeOldestSnapshots(),
  1880. static_cast<uint64_t>(s1->GetUnixTime()));
  1881. ASSERT_EQ("0v1", Get(0, "foo", s1));
  1882. ASSERT_EQ("1v1", Get(1, "foo", s1));
  1883. ASSERT_EQ("0v2", Get(0, "foo", s2));
  1884. ASSERT_EQ("1v2", Get(1, "foo", s2));
  1885. ASSERT_EQ("0v4", Get(0, "foo"));
  1886. ASSERT_EQ("1v4", Get(1, "foo"));
  1887. db_->ReleaseSnapshot(s1);
  1888. ASSERT_EQ("0v2", Get(0, "foo", s2));
  1889. ASSERT_EQ("1v2", Get(1, "foo", s2));
  1890. ASSERT_EQ("0v4", Get(0, "foo"));
  1891. ASSERT_EQ("1v4", Get(1, "foo"));
  1892. ASSERT_EQ(1U, GetNumSnapshots());
  1893. ASSERT_LT(time_snap1, GetTimeOldestSnapshots());
  1894. ASSERT_EQ(GetSequenceOldestSnapshots(), s2->GetSequenceNumber());
  1895. ASSERT_EQ(GetTimeOldestSnapshots(),
  1896. static_cast<uint64_t>(s2->GetUnixTime()));
  1897. db_->ReleaseSnapshot(s2);
  1898. ASSERT_EQ(0U, GetNumSnapshots());
  1899. ASSERT_EQ(GetSequenceOldestSnapshots(), 0);
  1900. ASSERT_EQ("0v4", Get(0, "foo"));
  1901. ASSERT_EQ("1v4", Get(1, "foo"));
  1902. } while (ChangeOptions());
  1903. }
  1904. TEST_F(DBTest, HiddenValuesAreRemoved) {
  1905. anon::OptionsOverride options_override;
  1906. options_override.skip_policy = kSkipNoSnapshot;
  1907. uint64_t size;
  1908. do {
  1909. Options options = CurrentOptions(options_override);
  1910. CreateAndReopenWithCF({"pikachu"}, options);
  1911. Random rnd(301);
  1912. FillLevels("a", "z", 1);
  1913. std::string big = rnd.RandomString(50000);
  1914. ASSERT_OK(Put(1, "foo", big));
  1915. ASSERT_OK(Put(1, "pastfoo", "v"));
  1916. const Snapshot* snapshot = db_->GetSnapshot();
  1917. ASSERT_OK(Put(1, "foo", "tiny"));
  1918. ASSERT_OK(Put(1, "pastfoo2", "v2")); // Advance sequence number one more
  1919. ASSERT_OK(Flush(1));
  1920. ASSERT_GT(NumTableFilesAtLevel(0, 1), 0);
  1921. ASSERT_EQ(big, Get(1, "foo", snapshot));
  1922. ASSERT_OK(Size("", "pastfoo", 1, &size));
  1923. ASSERT_TRUE(Between(size, 50000, 60000));
  1924. db_->ReleaseSnapshot(snapshot);
  1925. ASSERT_EQ(AllEntriesFor("foo", 1), "[ tiny, " + big + " ]");
  1926. Slice x("x");
  1927. ASSERT_OK(dbfull()->TEST_CompactRange(0, nullptr, &x, handles_[1]));
  1928. ASSERT_EQ(AllEntriesFor("foo", 1), "[ tiny ]");
  1929. ASSERT_EQ(NumTableFilesAtLevel(0, 1), 0);
  1930. ASSERT_GE(NumTableFilesAtLevel(1, 1), 1);
  1931. ASSERT_OK(dbfull()->TEST_CompactRange(1, nullptr, &x, handles_[1]));
  1932. ASSERT_EQ(AllEntriesFor("foo", 1), "[ tiny ]");
  1933. ASSERT_OK(Size("", "pastfoo", 1, &size));
  1934. ASSERT_TRUE(Between(size, 0, 1000));
  1935. // ApproximateOffsetOf() is not yet implemented in plain table format,
  1936. // which is used by Size().
  1937. } while (ChangeOptions(kSkipUniversalCompaction | kSkipFIFOCompaction |
  1938. kSkipPlainTable));
  1939. }
  1940. TEST_F(DBTest, UnremovableSingleDelete) {
  1941. // If we compact:
  1942. //
  1943. // Put(A, v1) Snapshot SingleDelete(A) Put(A, v2)
  1944. //
  1945. // We do not want to end up with:
  1946. //
  1947. // Put(A, v1) Snapshot Put(A, v2)
  1948. //
  1949. // Because a subsequent SingleDelete(A) would delete the Put(A, v2)
  1950. // but not Put(A, v1), so Get(A) would return v1.
  1951. anon::OptionsOverride options_override;
  1952. options_override.skip_policy = kSkipNoSnapshot;
  1953. do {
  1954. Options options = CurrentOptions(options_override);
  1955. options.disable_auto_compactions = true;
  1956. CreateAndReopenWithCF({"pikachu"}, options);
  1957. ASSERT_OK(Put(1, "foo", "first"));
  1958. const Snapshot* snapshot = db_->GetSnapshot();
  1959. ASSERT_OK(SingleDelete(1, "foo"));
  1960. ASSERT_OK(Put(1, "foo", "second"));
  1961. ASSERT_OK(Flush(1));
  1962. ASSERT_EQ("first", Get(1, "foo", snapshot));
  1963. ASSERT_EQ("second", Get(1, "foo"));
  1964. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), handles_[1],
  1965. nullptr, nullptr));
  1966. ASSERT_EQ("[ second, SDEL, first ]", AllEntriesFor("foo", 1));
  1967. ASSERT_OK(SingleDelete(1, "foo"));
  1968. ASSERT_EQ("first", Get(1, "foo", snapshot));
  1969. ASSERT_EQ("NOT_FOUND", Get(1, "foo"));
  1970. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), handles_[1],
  1971. nullptr, nullptr));
  1972. ASSERT_EQ("first", Get(1, "foo", snapshot));
  1973. ASSERT_EQ("NOT_FOUND", Get(1, "foo"));
  1974. db_->ReleaseSnapshot(snapshot);
  1975. // Skip FIFO and universal compaction because they do not apply to the test
  1976. // case. Skip MergePut because single delete does not get removed when it
  1977. // encounters a merge.
  1978. } while (ChangeOptions(kSkipFIFOCompaction | kSkipUniversalCompaction |
  1979. kSkipMergePut));
  1980. }
  1981. TEST_F(DBTest, DeletionMarkers1) {
  1982. Options options = CurrentOptions();
  1983. CreateAndReopenWithCF({"pikachu"}, options);
  1984. ASSERT_OK(Put(1, "foo", "v1"));
  1985. ASSERT_OK(Flush(1));
  1986. const int last = 2;
  1987. MoveFilesToLevel(last, 1);
  1988. // foo => v1 is now in last level
  1989. ASSERT_EQ(NumTableFilesAtLevel(last, 1), 1);
  1990. // Place a table at level last-1 to prevent merging with preceding mutation
  1991. ASSERT_OK(Put(1, "a", "begin"));
  1992. ASSERT_OK(Put(1, "z", "end"));
  1993. ASSERT_OK(Flush(1));
  1994. MoveFilesToLevel(last - 1, 1);
  1995. ASSERT_EQ(NumTableFilesAtLevel(last, 1), 1);
  1996. ASSERT_EQ(NumTableFilesAtLevel(last - 1, 1), 1);
  1997. ASSERT_OK(Delete(1, "foo"));
  1998. ASSERT_OK(Put(1, "foo", "v2"));
  1999. ASSERT_EQ(AllEntriesFor("foo", 1), "[ v2, DEL, v1 ]");
  2000. ASSERT_OK(Flush(1)); // Moves to level last-2
  2001. ASSERT_EQ(AllEntriesFor("foo", 1), "[ v2, v1 ]");
  2002. Slice z("z");
  2003. ASSERT_OK(dbfull()->TEST_CompactRange(last - 2, nullptr, &z, handles_[1]));
  2004. // DEL eliminated, but v1 remains because we aren't compacting that level
  2005. // (DEL can be eliminated because v2 hides v1).
  2006. ASSERT_EQ(AllEntriesFor("foo", 1), "[ v2, v1 ]");
  2007. ASSERT_OK(
  2008. dbfull()->TEST_CompactRange(last - 1, nullptr, nullptr, handles_[1]));
  2009. // Merging last-1 w/ last, so we are the base level for "foo", so
  2010. // DEL is removed. (as is v1).
  2011. ASSERT_EQ(AllEntriesFor("foo", 1), "[ v2 ]");
  2012. }
  2013. TEST_F(DBTest, DeletionMarkers2) {
  2014. Options options = CurrentOptions();
  2015. CreateAndReopenWithCF({"pikachu"}, options);
  2016. ASSERT_OK(Put(1, "foo", "v1"));
  2017. ASSERT_OK(Flush(1));
  2018. const int last = 2;
  2019. MoveFilesToLevel(last, 1);
  2020. // foo => v1 is now in last level
  2021. ASSERT_EQ(NumTableFilesAtLevel(last, 1), 1);
  2022. // Place a table at level last-1 to prevent merging with preceding mutation
  2023. ASSERT_OK(Put(1, "a", "begin"));
  2024. ASSERT_OK(Put(1, "z", "end"));
  2025. ASSERT_OK(Flush(1));
  2026. MoveFilesToLevel(last - 1, 1);
  2027. ASSERT_EQ(NumTableFilesAtLevel(last, 1), 1);
  2028. ASSERT_EQ(NumTableFilesAtLevel(last - 1, 1), 1);
  2029. ASSERT_OK(Delete(1, "foo"));
  2030. ASSERT_EQ(AllEntriesFor("foo", 1), "[ DEL, v1 ]");
  2031. ASSERT_OK(Flush(1)); // Moves to level last-2
  2032. ASSERT_EQ(AllEntriesFor("foo", 1), "[ DEL, v1 ]");
  2033. ASSERT_OK(
  2034. dbfull()->TEST_CompactRange(last - 2, nullptr, nullptr, handles_[1]));
  2035. // DEL kept: "last" file overlaps
  2036. ASSERT_EQ(AllEntriesFor("foo", 1), "[ DEL, v1 ]");
  2037. ASSERT_OK(
  2038. dbfull()->TEST_CompactRange(last - 1, nullptr, nullptr, handles_[1]));
  2039. // Merging last-1 w/ last, so we are the base level for "foo", so
  2040. // DEL is removed. (as is v1).
  2041. ASSERT_EQ(AllEntriesFor("foo", 1), "[ ]");
  2042. }
  2043. TEST_F(DBTest, OverlapInLevel0) {
  2044. do {
  2045. Options options = CurrentOptions();
  2046. CreateAndReopenWithCF({"pikachu"}, options);
  2047. // Fill levels 1 and 2 to disable the pushing of new memtables to levels >
  2048. // 0.
  2049. ASSERT_OK(Put(1, "100", "v100"));
  2050. ASSERT_OK(Put(1, "999", "v999"));
  2051. ASSERT_OK(Flush(1));
  2052. MoveFilesToLevel(2, 1);
  2053. ASSERT_OK(Delete(1, "100"));
  2054. ASSERT_OK(Delete(1, "999"));
  2055. ASSERT_OK(Flush(1));
  2056. MoveFilesToLevel(1, 1);
  2057. ASSERT_EQ("0,1,1", FilesPerLevel(1));
  2058. // Make files spanning the following ranges in level-0:
  2059. // files[0] 200 .. 900
  2060. // files[1] 300 .. 500
  2061. // Note that files are sorted by smallest key.
  2062. ASSERT_OK(Put(1, "300", "v300"));
  2063. ASSERT_OK(Put(1, "500", "v500"));
  2064. ASSERT_OK(Flush(1));
  2065. ASSERT_OK(Put(1, "200", "v200"));
  2066. ASSERT_OK(Put(1, "600", "v600"));
  2067. ASSERT_OK(Put(1, "900", "v900"));
  2068. ASSERT_OK(Flush(1));
  2069. ASSERT_EQ("2,1,1", FilesPerLevel(1));
  2070. // BEGIN addition to existing test
  2071. // Take this opportunity to verify SST unique ids (including Plain table)
  2072. TablePropertiesCollection tbc;
  2073. ASSERT_OK(db_->GetPropertiesOfAllTables(handles_[1], &tbc));
  2074. VerifySstUniqueIds(tbc);
  2075. // END addition to existing test
  2076. // Compact away the placeholder files we created initially
  2077. ASSERT_OK(dbfull()->TEST_CompactRange(1, nullptr, nullptr, handles_[1]));
  2078. ASSERT_OK(dbfull()->TEST_CompactRange(2, nullptr, nullptr, handles_[1]));
  2079. ASSERT_EQ("2", FilesPerLevel(1));
  2080. // Do a memtable compaction. Before bug-fix, the compaction would
  2081. // not detect the overlap with level-0 files and would incorrectly place
  2082. // the deletion in a deeper level.
  2083. ASSERT_OK(Delete(1, "600"));
  2084. ASSERT_OK(Flush(1));
  2085. ASSERT_EQ("3", FilesPerLevel(1));
  2086. ASSERT_EQ("NOT_FOUND", Get(1, "600"));
  2087. } while (ChangeOptions(kSkipUniversalCompaction | kSkipFIFOCompaction));
  2088. }
  2089. TEST_F(DBTest, ComparatorCheck) {
  2090. class NewComparator : public Comparator {
  2091. public:
  2092. const char* Name() const override { return "rocksdb.NewComparator"; }
  2093. int Compare(const Slice& a, const Slice& b) const override {
  2094. return BytewiseComparator()->Compare(a, b);
  2095. }
  2096. void FindShortestSeparator(std::string* s, const Slice& l) const override {
  2097. BytewiseComparator()->FindShortestSeparator(s, l);
  2098. }
  2099. void FindShortSuccessor(std::string* key) const override {
  2100. BytewiseComparator()->FindShortSuccessor(key);
  2101. }
  2102. };
  2103. Options new_options, options;
  2104. NewComparator cmp;
  2105. do {
  2106. options = CurrentOptions();
  2107. CreateAndReopenWithCF({"pikachu"}, options);
  2108. new_options = CurrentOptions();
  2109. new_options.comparator = &cmp;
  2110. // only the non-default column family has non-matching comparator
  2111. Status s = TryReopenWithColumnFamilies(
  2112. {"default", "pikachu"}, std::vector<Options>({options, new_options}));
  2113. ASSERT_TRUE(!s.ok());
  2114. ASSERT_TRUE(s.ToString().find("comparator") != std::string::npos)
  2115. << s.ToString();
  2116. } while (ChangeCompactOptions());
  2117. }
  2118. TEST_F(DBTest, CustomComparator) {
  2119. class NumberComparator : public Comparator {
  2120. public:
  2121. const char* Name() const override { return "test.NumberComparator"; }
  2122. int Compare(const Slice& a, const Slice& b) const override {
  2123. return ToNumber(a) - ToNumber(b);
  2124. }
  2125. void FindShortestSeparator(std::string* s, const Slice& l) const override {
  2126. ToNumber(*s); // Check format
  2127. ToNumber(l); // Check format
  2128. }
  2129. void FindShortSuccessor(std::string* key) const override {
  2130. ToNumber(*key); // Check format
  2131. }
  2132. private:
  2133. static int ToNumber(const Slice& x) {
  2134. // Check that there are no extra characters.
  2135. EXPECT_TRUE(x.size() >= 2 && x[0] == '[' && x[x.size() - 1] == ']')
  2136. << EscapeString(x);
  2137. int val;
  2138. char ignored;
  2139. EXPECT_TRUE(sscanf(x.ToString().c_str(), "[%i]%c", &val, &ignored) == 1)
  2140. << EscapeString(x);
  2141. return val;
  2142. }
  2143. };
  2144. Options new_options;
  2145. NumberComparator cmp;
  2146. do {
  2147. new_options = CurrentOptions();
  2148. new_options.create_if_missing = true;
  2149. new_options.comparator = &cmp;
  2150. new_options.write_buffer_size = 4096; // Compact more often
  2151. new_options.arena_block_size = 4096;
  2152. new_options = CurrentOptions(new_options);
  2153. DestroyAndReopen(new_options);
  2154. CreateAndReopenWithCF({"pikachu"}, new_options);
  2155. ASSERT_OK(Put(1, "[10]", "ten"));
  2156. ASSERT_OK(Put(1, "[0x14]", "twenty"));
  2157. for (int i = 0; i < 2; i++) {
  2158. ASSERT_EQ("ten", Get(1, "[10]"));
  2159. ASSERT_EQ("ten", Get(1, "[0xa]"));
  2160. ASSERT_EQ("twenty", Get(1, "[20]"));
  2161. ASSERT_EQ("twenty", Get(1, "[0x14]"));
  2162. ASSERT_EQ("NOT_FOUND", Get(1, "[15]"));
  2163. ASSERT_EQ("NOT_FOUND", Get(1, "[0xf]"));
  2164. Compact(1, "[0]", "[9999]");
  2165. }
  2166. for (int run = 0; run < 2; run++) {
  2167. for (int i = 0; i < 1000; i++) {
  2168. char buf[100];
  2169. snprintf(buf, sizeof(buf), "[%d]", i * 10);
  2170. ASSERT_OK(Put(1, buf, buf));
  2171. }
  2172. Compact(1, "[0]", "[1000000]");
  2173. }
  2174. } while (ChangeCompactOptions());
  2175. }
  2176. TEST_F(DBTest, DBOpen_Options) {
  2177. Options options = CurrentOptions();
  2178. std::string dbname = test::PerThreadDBPath("db_options_test");
  2179. ASSERT_OK(DestroyDB(dbname, options));
  2180. // Does not exist, and create_if_missing == false: error
  2181. DB* db = nullptr;
  2182. options.create_if_missing = false;
  2183. Status s = DB::Open(options, dbname, &db);
  2184. ASSERT_TRUE(strstr(s.ToString().c_str(), "does not exist") != nullptr);
  2185. ASSERT_TRUE(db == nullptr);
  2186. // Does not exist, and create_if_missing == true: OK
  2187. options.create_if_missing = true;
  2188. s = DB::Open(options, dbname, &db);
  2189. ASSERT_OK(s);
  2190. ASSERT_TRUE(db != nullptr);
  2191. delete db;
  2192. db = nullptr;
  2193. // Does exist, and error_if_exists == true: error
  2194. options.create_if_missing = false;
  2195. options.error_if_exists = true;
  2196. s = DB::Open(options, dbname, &db);
  2197. ASSERT_TRUE(strstr(s.ToString().c_str(), "exists") != nullptr);
  2198. ASSERT_TRUE(db == nullptr);
  2199. // Does exist, and error_if_exists == false: OK
  2200. options.create_if_missing = true;
  2201. options.error_if_exists = false;
  2202. s = DB::Open(options, dbname, &db);
  2203. ASSERT_OK(s);
  2204. ASSERT_TRUE(db != nullptr);
  2205. delete db;
  2206. db = nullptr;
  2207. }
  2208. TEST_F(DBTest, DBOpen_Change_NumLevels) {
  2209. Options options = CurrentOptions();
  2210. options.create_if_missing = true;
  2211. DestroyAndReopen(options);
  2212. ASSERT_TRUE(db_ != nullptr);
  2213. CreateAndReopenWithCF({"pikachu"}, options);
  2214. ASSERT_OK(Put(1, "a", "123"));
  2215. ASSERT_OK(Put(1, "b", "234"));
  2216. ASSERT_OK(Flush(1));
  2217. MoveFilesToLevel(3, 1);
  2218. Close();
  2219. options.create_if_missing = false;
  2220. options.num_levels = 2;
  2221. Status s = TryReopenWithColumnFamilies({"default", "pikachu"}, options);
  2222. ASSERT_TRUE(strstr(s.ToString().c_str(), "Invalid argument") != nullptr);
  2223. ASSERT_TRUE(db_ == nullptr);
  2224. }
  2225. TEST_F(DBTest, DestroyDBMetaDatabase) {
  2226. std::string dbname = test::PerThreadDBPath("db_meta");
  2227. ASSERT_OK(env_->CreateDirIfMissing(dbname));
  2228. std::string metadbname = MetaDatabaseName(dbname, 0);
  2229. ASSERT_OK(env_->CreateDirIfMissing(metadbname));
  2230. std::string metametadbname = MetaDatabaseName(metadbname, 0);
  2231. ASSERT_OK(env_->CreateDirIfMissing(metametadbname));
  2232. // Destroy previous versions if they exist. Using the long way.
  2233. Options options = CurrentOptions();
  2234. ASSERT_OK(DestroyDB(metametadbname, options));
  2235. ASSERT_OK(DestroyDB(metadbname, options));
  2236. ASSERT_OK(DestroyDB(dbname, options));
  2237. // Setup databases
  2238. DB* db = nullptr;
  2239. ASSERT_OK(DB::Open(options, dbname, &db));
  2240. delete db;
  2241. db = nullptr;
  2242. ASSERT_OK(DB::Open(options, metadbname, &db));
  2243. delete db;
  2244. db = nullptr;
  2245. ASSERT_OK(DB::Open(options, metametadbname, &db));
  2246. delete db;
  2247. db = nullptr;
  2248. // Delete databases
  2249. ASSERT_OK(DestroyDB(dbname, options));
  2250. // Check if deletion worked.
  2251. options.create_if_missing = false;
  2252. ASSERT_TRUE(!(DB::Open(options, dbname, &db)).ok());
  2253. ASSERT_TRUE(!(DB::Open(options, metadbname, &db)).ok());
  2254. ASSERT_TRUE(!(DB::Open(options, metametadbname, &db)).ok());
  2255. }
  2256. TEST_F(DBTest, SnapshotFiles) {
  2257. do {
  2258. Options options = CurrentOptions();
  2259. options.write_buffer_size = 100000000; // Large write buffer
  2260. CreateAndReopenWithCF({"pikachu"}, options);
  2261. Random rnd(301);
  2262. // Write 8MB (80 values, each 100K)
  2263. ASSERT_EQ(NumTableFilesAtLevel(0, 1), 0);
  2264. std::vector<std::string> values;
  2265. for (int i = 0; i < 80; i++) {
  2266. values.push_back(rnd.RandomString(100000));
  2267. ASSERT_OK(Put((i < 40), Key(i), values[i]));
  2268. }
  2269. // assert that nothing makes it to disk yet.
  2270. ASSERT_EQ(NumTableFilesAtLevel(0, 1), 0);
  2271. // get a file snapshot
  2272. uint64_t manifest_number = 0;
  2273. uint64_t manifest_size = 0;
  2274. std::vector<std::string> files;
  2275. ASSERT_OK(dbfull()->DisableFileDeletions());
  2276. ASSERT_OK(dbfull()->GetLiveFiles(files, &manifest_size));
  2277. // CURRENT, MANIFEST, OPTIONS, *.sst files (one for each CF)
  2278. ASSERT_EQ(files.size(), 5U);
  2279. uint64_t number = 0;
  2280. FileType type;
  2281. // copy these files to a new snapshot directory
  2282. std::string snapdir = dbname_ + ".snapdir/";
  2283. if (env_->FileExists(snapdir).ok()) {
  2284. ASSERT_OK(DestroyDir(env_, snapdir));
  2285. }
  2286. ASSERT_OK(env_->CreateDir(snapdir));
  2287. for (size_t i = 0; i < files.size(); i++) {
  2288. // our clients require that GetLiveFiles returns
  2289. // files with "/" as first character!
  2290. ASSERT_EQ(files[i][0], '/');
  2291. std::string src = dbname_ + files[i];
  2292. std::string dest = snapdir + files[i];
  2293. uint64_t size;
  2294. ASSERT_OK(env_->GetFileSize(src, &size));
  2295. // record the number and the size of the
  2296. // latest manifest file
  2297. if (ParseFileName(files[i].substr(1), &number, &type)) {
  2298. if (type == kDescriptorFile) {
  2299. ASSERT_EQ(manifest_number, 0);
  2300. manifest_number = number;
  2301. ASSERT_GE(size, manifest_size);
  2302. size = manifest_size; // copy only valid MANIFEST data
  2303. }
  2304. }
  2305. CopyFile(src, dest, size);
  2306. }
  2307. // release file snapshot
  2308. ASSERT_OK(dbfull()->EnableFileDeletions());
  2309. // overwrite one key, this key should not appear in the snapshot
  2310. std::vector<std::string> extras;
  2311. for (unsigned int i = 0; i < 1; i++) {
  2312. extras.push_back(rnd.RandomString(100000));
  2313. ASSERT_OK(Put(0, Key(i), extras[i]));
  2314. }
  2315. // verify that data in the snapshot are correct
  2316. std::vector<ColumnFamilyDescriptor> column_families;
  2317. column_families.emplace_back("default", ColumnFamilyOptions());
  2318. column_families.emplace_back("pikachu", ColumnFamilyOptions());
  2319. std::vector<ColumnFamilyHandle*> cf_handles;
  2320. DB* snapdb;
  2321. DBOptions opts;
  2322. opts.env = env_;
  2323. opts.create_if_missing = false;
  2324. Status stat =
  2325. DB::Open(opts, snapdir, column_families, &cf_handles, &snapdb);
  2326. ASSERT_OK(stat);
  2327. ReadOptions roptions;
  2328. std::string val;
  2329. for (unsigned int i = 0; i < 80; i++) {
  2330. ASSERT_OK(snapdb->Get(roptions, cf_handles[i < 40], Key(i), &val));
  2331. ASSERT_EQ(values[i].compare(val), 0);
  2332. }
  2333. for (auto cfh : cf_handles) {
  2334. delete cfh;
  2335. }
  2336. delete snapdb;
  2337. // look at the new live files after we added an 'extra' key
  2338. // and after we took the first snapshot.
  2339. uint64_t new_manifest_number = 0;
  2340. uint64_t new_manifest_size = 0;
  2341. std::vector<std::string> newfiles;
  2342. ASSERT_OK(dbfull()->DisableFileDeletions());
  2343. ASSERT_OK(dbfull()->GetLiveFiles(newfiles, &new_manifest_size));
  2344. // find the new manifest file. assert that this manifest file is
  2345. // the same one as in the previous snapshot. But its size should be
  2346. // larger because we added an extra key after taking the
  2347. // previous shapshot.
  2348. for (size_t i = 0; i < newfiles.size(); i++) {
  2349. std::string src = dbname_ + "/" + newfiles[i];
  2350. // record the lognumber and the size of the
  2351. // latest manifest file
  2352. if (ParseFileName(newfiles[i].substr(1), &number, &type)) {
  2353. if (type == kDescriptorFile) {
  2354. ASSERT_EQ(new_manifest_number, 0);
  2355. uint64_t size;
  2356. new_manifest_number = number;
  2357. ASSERT_OK(env_->GetFileSize(src, &size));
  2358. ASSERT_GE(size, new_manifest_size);
  2359. }
  2360. }
  2361. }
  2362. ASSERT_EQ(manifest_number, new_manifest_number);
  2363. ASSERT_GT(new_manifest_size, manifest_size);
  2364. // Also test GetLiveFilesStorageInfo
  2365. std::vector<LiveFileStorageInfo> new_infos;
  2366. ASSERT_OK(db_->GetLiveFilesStorageInfo(LiveFilesStorageInfoOptions(),
  2367. &new_infos));
  2368. // Close DB (while deletions disabled)
  2369. Close();
  2370. // Validate
  2371. for (auto& info : new_infos) {
  2372. std::string path = info.directory + "/" + info.relative_filename;
  2373. uint64_t size;
  2374. ASSERT_OK(env_->GetFileSize(path, &size));
  2375. if (info.trim_to_size) {
  2376. ASSERT_LE(info.size, size);
  2377. } else if (!info.replacement_contents.empty()) {
  2378. ASSERT_EQ(info.size, info.replacement_contents.size());
  2379. } else {
  2380. ASSERT_EQ(info.size, size);
  2381. }
  2382. if (info.file_type == kDescriptorFile) {
  2383. ASSERT_EQ(info.file_number, manifest_number);
  2384. }
  2385. }
  2386. } while (ChangeCompactOptions());
  2387. }
  2388. TEST_F(DBTest, ReadonlyDBGetLiveManifestSize) {
  2389. do {
  2390. Options options = CurrentOptions();
  2391. options.level0_file_num_compaction_trigger = 2;
  2392. DestroyAndReopen(options);
  2393. ASSERT_OK(Put("foo", "bar"));
  2394. ASSERT_OK(Flush());
  2395. ASSERT_OK(Put("foo", "bar"));
  2396. ASSERT_OK(Flush());
  2397. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  2398. Close();
  2399. ASSERT_OK(ReadOnlyReopen(options));
  2400. uint64_t manifest_size = 0;
  2401. std::vector<std::string> files;
  2402. ASSERT_OK(dbfull()->GetLiveFiles(files, &manifest_size));
  2403. for (const std::string& f : files) {
  2404. uint64_t number = 0;
  2405. FileType type;
  2406. if (ParseFileName(f.substr(1), &number, &type)) {
  2407. if (type == kDescriptorFile) {
  2408. uint64_t size_on_disk;
  2409. ASSERT_OK(env_->GetFileSize(dbname_ + "/" + f, &size_on_disk));
  2410. ASSERT_EQ(manifest_size, size_on_disk);
  2411. break;
  2412. }
  2413. }
  2414. }
  2415. Close();
  2416. } while (ChangeCompactOptions());
  2417. }
  2418. TEST_F(DBTest, GetLiveBlobFiles) {
  2419. // Note: the following prevents an otherwise harmless data race between the
  2420. // test setup code (AddBlobFile) below and the periodic stat dumping thread.
  2421. Options options = CurrentOptions();
  2422. options.stats_dump_period_sec = 0;
  2423. constexpr uint64_t blob_file_number = 234;
  2424. constexpr uint64_t total_blob_count = 555;
  2425. constexpr uint64_t total_blob_bytes = 66666;
  2426. constexpr char checksum_method[] = "CRC32";
  2427. constexpr char checksum_value[] = "\x3d\x87\xff\x57";
  2428. constexpr uint64_t garbage_blob_count = 0;
  2429. constexpr uint64_t garbage_blob_bytes = 0;
  2430. Reopen(options);
  2431. AddBlobFile(db_->DefaultColumnFamily(), blob_file_number, total_blob_count,
  2432. total_blob_bytes, checksum_method, checksum_value,
  2433. garbage_blob_count, garbage_blob_bytes);
  2434. // Make sure it appears in the results returned by GetLiveFiles.
  2435. uint64_t manifest_size = 0;
  2436. std::vector<std::string> files;
  2437. ASSERT_OK(dbfull()->GetLiveFiles(files, &manifest_size));
  2438. ASSERT_FALSE(files.empty());
  2439. ASSERT_EQ(files[0], BlobFileName("", blob_file_number));
  2440. ColumnFamilyMetaData cfmd;
  2441. db_->GetColumnFamilyMetaData(&cfmd);
  2442. ASSERT_EQ(cfmd.blob_files.size(), 1);
  2443. const BlobMetaData& bmd = cfmd.blob_files[0];
  2444. CheckBlobMetaData(bmd, blob_file_number, total_blob_count, total_blob_bytes,
  2445. checksum_method, checksum_value, garbage_blob_count,
  2446. garbage_blob_bytes);
  2447. ASSERT_EQ(NormalizePath(bmd.blob_file_path), NormalizePath(dbname_));
  2448. ASSERT_EQ(cfmd.blob_file_count, 1U);
  2449. ASSERT_EQ(cfmd.blob_file_size, bmd.blob_file_size);
  2450. }
  2451. TEST_F(DBTest, PurgeInfoLogs) {
  2452. Options options = CurrentOptions();
  2453. options.keep_log_file_num = 5;
  2454. options.create_if_missing = true;
  2455. options.env = env_;
  2456. for (int mode = 0; mode <= 1; mode++) {
  2457. if (mode == 1) {
  2458. options.db_log_dir = dbname_ + "_logs";
  2459. ASSERT_OK(env_->CreateDirIfMissing(options.db_log_dir));
  2460. } else {
  2461. options.db_log_dir = "";
  2462. }
  2463. for (int i = 0; i < 8; i++) {
  2464. Reopen(options);
  2465. }
  2466. std::vector<std::string> files;
  2467. ASSERT_OK(env_->GetChildren(
  2468. options.db_log_dir.empty() ? dbname_ : options.db_log_dir, &files));
  2469. int info_log_count = 0;
  2470. for (const std::string& file : files) {
  2471. if (file.find("LOG") != std::string::npos) {
  2472. info_log_count++;
  2473. }
  2474. }
  2475. ASSERT_EQ(5, info_log_count);
  2476. Destroy(options);
  2477. // For mode (1), test DestroyDB() to delete all the logs under DB dir.
  2478. // For mode (2), no info log file should have been put under DB dir.
  2479. // Since dbname_ has no children, there is no need to loop db_files
  2480. std::vector<std::string> db_files;
  2481. ASSERT_TRUE(env_->GetChildren(dbname_, &db_files).IsNotFound());
  2482. ASSERT_TRUE(db_files.empty());
  2483. if (mode == 1) {
  2484. // Cleaning up
  2485. ASSERT_OK(env_->GetChildren(options.db_log_dir, &files));
  2486. for (const std::string& file : files) {
  2487. ASSERT_OK(env_->DeleteFile(options.db_log_dir + "/" + file));
  2488. }
  2489. ASSERT_OK(env_->DeleteDir(options.db_log_dir));
  2490. }
  2491. }
  2492. }
  2493. // Multi-threaded test:
  2494. namespace {
  2495. static const int kColumnFamilies = 10;
  2496. static const int kNumThreads = 10;
  2497. static const int kTestSeconds = 10;
  2498. static const int kNumKeys = 1000;
  2499. struct MTState {
  2500. DBTest* test;
  2501. std::atomic<int> counter[kNumThreads];
  2502. };
  2503. struct MTThread {
  2504. MTState* state;
  2505. int id;
  2506. bool multiget_batched;
  2507. };
  2508. static void MTThreadBody(void* arg) {
  2509. MTThread* t = static_cast<MTThread*>(arg);
  2510. int id = t->id;
  2511. DB* db = t->state->test->db_;
  2512. int counter = 0;
  2513. std::shared_ptr<SystemClock> clock = SystemClock::Default();
  2514. auto end_micros = clock->NowMicros() + kTestSeconds * 1000000U;
  2515. fprintf(stderr, "... starting thread %d\n", id);
  2516. Random rnd(1000 + id);
  2517. char valbuf[1500];
  2518. while (clock->NowMicros() < end_micros) {
  2519. t->state->counter[id].store(counter, std::memory_order_release);
  2520. int key = rnd.Uniform(kNumKeys);
  2521. char keybuf[20];
  2522. snprintf(keybuf, sizeof(keybuf), "%016d", key);
  2523. if (rnd.OneIn(2)) {
  2524. // Write values of the form <key, my id, counter, cf, unique_id>.
  2525. // into each of the CFs
  2526. // We add some padding for force compactions.
  2527. int unique_id = rnd.Uniform(1000000);
  2528. // Half of the time directly use WriteBatch. Half of the time use
  2529. // WriteBatchWithIndex.
  2530. if (rnd.OneIn(2)) {
  2531. WriteBatch batch;
  2532. for (int cf = 0; cf < kColumnFamilies; ++cf) {
  2533. snprintf(valbuf, sizeof(valbuf), "%d.%d.%d.%d.%-1000d", key, id,
  2534. static_cast<int>(counter), cf, unique_id);
  2535. ASSERT_OK(batch.Put(t->state->test->handles_[cf], Slice(keybuf),
  2536. Slice(valbuf)));
  2537. }
  2538. ASSERT_OK(db->Write(WriteOptions(), &batch));
  2539. } else {
  2540. WriteBatchWithIndex batch(db->GetOptions().comparator);
  2541. for (int cf = 0; cf < kColumnFamilies; ++cf) {
  2542. snprintf(valbuf, sizeof(valbuf), "%d.%d.%d.%d.%-1000d", key, id,
  2543. static_cast<int>(counter), cf, unique_id);
  2544. ASSERT_OK(batch.Put(t->state->test->handles_[cf], Slice(keybuf),
  2545. Slice(valbuf)));
  2546. }
  2547. ASSERT_OK(db->Write(WriteOptions(), batch.GetWriteBatch()));
  2548. }
  2549. } else {
  2550. // Read a value and verify that it matches the pattern written above
  2551. // and that writes to all column families were atomic (unique_id is the
  2552. // same)
  2553. std::vector<Slice> keys(kColumnFamilies, Slice(keybuf));
  2554. std::vector<std::string> values;
  2555. std::vector<Status> statuses;
  2556. if (!t->multiget_batched) {
  2557. statuses = db->MultiGet(ReadOptions(), t->state->test->handles_, keys,
  2558. &values);
  2559. } else {
  2560. std::vector<PinnableSlice> pin_values(keys.size());
  2561. statuses.resize(keys.size());
  2562. const Snapshot* snapshot = db->GetSnapshot();
  2563. ReadOptions ro;
  2564. ro.snapshot = snapshot;
  2565. for (int cf = 0; cf < kColumnFamilies; ++cf) {
  2566. db->MultiGet(ro, t->state->test->handles_[cf], 1, &keys[cf],
  2567. &pin_values[cf], &statuses[cf]);
  2568. }
  2569. db->ReleaseSnapshot(snapshot);
  2570. values.resize(keys.size());
  2571. for (int cf = 0; cf < kColumnFamilies; ++cf) {
  2572. if (statuses[cf].ok()) {
  2573. values[cf].assign(pin_values[cf].data(), pin_values[cf].size());
  2574. }
  2575. }
  2576. }
  2577. Status s = statuses[0];
  2578. // all statuses have to be the same
  2579. for (size_t i = 1; i < statuses.size(); ++i) {
  2580. // they are either both ok or both not-found
  2581. ASSERT_TRUE((s.ok() && statuses[i].ok()) ||
  2582. (s.IsNotFound() && statuses[i].IsNotFound()));
  2583. }
  2584. if (s.IsNotFound()) {
  2585. // Key has not yet been written
  2586. } else {
  2587. // Check that the writer thread counter is >= the counter in the value
  2588. ASSERT_OK(s);
  2589. int unique_id = -1;
  2590. for (int i = 0; i < kColumnFamilies; ++i) {
  2591. int k, w, c, cf, u;
  2592. ASSERT_EQ(5, sscanf(values[i].c_str(), "%d.%d.%d.%d.%d", &k, &w, &c,
  2593. &cf, &u))
  2594. << values[i];
  2595. ASSERT_EQ(k, key);
  2596. ASSERT_GE(w, 0);
  2597. ASSERT_LT(w, kNumThreads);
  2598. ASSERT_LE(c, t->state->counter[w].load(std::memory_order_acquire));
  2599. ASSERT_EQ(cf, i);
  2600. if (i == 0) {
  2601. unique_id = u;
  2602. } else {
  2603. // this checks that updates across column families happened
  2604. // atomically -- all unique ids are the same
  2605. ASSERT_EQ(u, unique_id);
  2606. }
  2607. }
  2608. }
  2609. }
  2610. counter++;
  2611. }
  2612. fprintf(stderr, "... stopping thread %d after %d ops\n", id, int(counter));
  2613. }
  2614. } // anonymous namespace
  2615. class MultiThreadedDBTest
  2616. : public DBTest,
  2617. public ::testing::WithParamInterface<std::tuple<int, bool>> {
  2618. public:
  2619. void SetUp() override {
  2620. std::tie(option_config_, multiget_batched_) = GetParam();
  2621. }
  2622. static std::vector<int> GenerateOptionConfigs() {
  2623. std::vector<int> optionConfigs;
  2624. for (int optionConfig = kDefault; optionConfig < kEnd; ++optionConfig) {
  2625. optionConfigs.push_back(optionConfig);
  2626. }
  2627. return optionConfigs;
  2628. }
  2629. bool multiget_batched_;
  2630. };
  2631. TEST_P(MultiThreadedDBTest, MultiThreaded) {
  2632. if (option_config_ == kPipelinedWrite) {
  2633. return;
  2634. }
  2635. anon::OptionsOverride options_override;
  2636. options_override.skip_policy = kSkipNoSnapshot;
  2637. Options options = CurrentOptions(options_override);
  2638. std::vector<std::string> cfs;
  2639. for (int i = 1; i < kColumnFamilies; ++i) {
  2640. cfs.push_back(std::to_string(i));
  2641. }
  2642. Reopen(options);
  2643. CreateAndReopenWithCF(cfs, options);
  2644. // Initialize state
  2645. MTState mt;
  2646. mt.test = this;
  2647. for (int id = 0; id < kNumThreads; id++) {
  2648. mt.counter[id].store(0, std::memory_order_release);
  2649. }
  2650. // Start threads
  2651. MTThread thread[kNumThreads];
  2652. for (int id = 0; id < kNumThreads; id++) {
  2653. thread[id].state = &mt;
  2654. thread[id].id = id;
  2655. thread[id].multiget_batched = multiget_batched_;
  2656. env_->StartThread(MTThreadBody, &thread[id]);
  2657. }
  2658. env_->WaitForJoin();
  2659. }
  2660. INSTANTIATE_TEST_CASE_P(
  2661. MultiThreaded, MultiThreadedDBTest,
  2662. ::testing::Combine(
  2663. ::testing::ValuesIn(MultiThreadedDBTest::GenerateOptionConfigs()),
  2664. ::testing::Bool()));
  2665. // Group commit test:
  2666. #if !defined(OS_WIN)
  2667. // Disable this test temporarily on Travis and appveyor as it fails
  2668. // intermittently. Github issue: #4151
  2669. namespace {
  2670. static const int kGCNumThreads = 4;
  2671. static const int kGCNumKeys = 1000;
  2672. struct GCThread {
  2673. DB* db;
  2674. int id;
  2675. std::atomic<bool> done;
  2676. };
  2677. static void GCThreadBody(void* arg) {
  2678. GCThread* t = static_cast<GCThread*>(arg);
  2679. int id = t->id;
  2680. DB* db = t->db;
  2681. WriteOptions wo;
  2682. for (int i = 0; i < kGCNumKeys; ++i) {
  2683. std::string kv(std::to_string(i + id * kGCNumKeys));
  2684. ASSERT_OK(db->Put(wo, kv, kv));
  2685. }
  2686. t->done = true;
  2687. }
  2688. } // anonymous namespace
  2689. TEST_F(DBTest, GroupCommitTest) {
  2690. do {
  2691. Options options = CurrentOptions();
  2692. options.env = env_;
  2693. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  2694. Reopen(options);
  2695. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
  2696. {{"WriteThread::JoinBatchGroup:BeganWaiting",
  2697. "DBImpl::WriteImpl:BeforeLeaderEnters"},
  2698. {"WriteThread::AwaitState:BlockingWaiting",
  2699. "WriteThread::EnterAsBatchGroupLeader:End"}});
  2700. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  2701. // Start threads
  2702. GCThread thread[kGCNumThreads];
  2703. for (int id = 0; id < kGCNumThreads; id++) {
  2704. thread[id].id = id;
  2705. thread[id].db = db_;
  2706. thread[id].done = false;
  2707. env_->StartThread(GCThreadBody, &thread[id]);
  2708. }
  2709. env_->WaitForJoin();
  2710. ASSERT_GT(TestGetTickerCount(options, WRITE_DONE_BY_OTHER), 0);
  2711. std::vector<std::string> expected_db;
  2712. for (int i = 0; i < kGCNumThreads * kGCNumKeys; ++i) {
  2713. expected_db.push_back(std::to_string(i));
  2714. }
  2715. std::sort(expected_db.begin(), expected_db.end());
  2716. Iterator* itr = db_->NewIterator(ReadOptions());
  2717. itr->SeekToFirst();
  2718. for (const auto& x : expected_db) {
  2719. ASSERT_TRUE(itr->Valid());
  2720. ASSERT_EQ(itr->key().ToString(), x);
  2721. ASSERT_EQ(itr->value().ToString(), x);
  2722. itr->Next();
  2723. }
  2724. ASSERT_TRUE(!itr->Valid());
  2725. ASSERT_OK(itr->status());
  2726. delete itr;
  2727. HistogramData hist_data;
  2728. options.statistics->histogramData(DB_WRITE, &hist_data);
  2729. ASSERT_GT(hist_data.average, 0.0);
  2730. } while (ChangeOptions(kSkipNoSeekToLast));
  2731. }
  2732. #endif // OS_WIN
  2733. namespace {
  2734. using KVMap = std::map<std::string, std::string>;
  2735. }
  2736. class ModelDB : public DB {
  2737. public:
  2738. class ModelSnapshot : public Snapshot {
  2739. public:
  2740. KVMap map_;
  2741. SequenceNumber GetSequenceNumber() const override {
  2742. // no need to call this
  2743. assert(false);
  2744. return 0;
  2745. }
  2746. int64_t GetUnixTime() const override {
  2747. // no need to call this
  2748. assert(false);
  2749. return 0;
  2750. }
  2751. uint64_t GetTimestamp() const override {
  2752. // no need to call this
  2753. assert(false);
  2754. return 0;
  2755. }
  2756. };
  2757. explicit ModelDB(const Options& options) : options_(options) {}
  2758. using DB::Put;
  2759. Status Put(const WriteOptions& o, ColumnFamilyHandle* cf, const Slice& k,
  2760. const Slice& v) override {
  2761. WriteBatch batch;
  2762. Status s = batch.Put(cf, k, v);
  2763. if (!s.ok()) {
  2764. return s;
  2765. }
  2766. return Write(o, &batch);
  2767. }
  2768. Status Put(const WriteOptions& /*o*/, ColumnFamilyHandle* /*cf*/,
  2769. const Slice& /*k*/, const Slice& /*ts*/,
  2770. const Slice& /*v*/) override {
  2771. return Status::NotSupported();
  2772. }
  2773. using DB::PutEntity;
  2774. Status PutEntity(const WriteOptions& /* options */,
  2775. ColumnFamilyHandle* /* column_family */,
  2776. const Slice& /* key */,
  2777. const WideColumns& /* columns */) override {
  2778. return Status::NotSupported();
  2779. }
  2780. using DB::Close;
  2781. Status Close() override { return Status::OK(); }
  2782. using DB::Delete;
  2783. Status Delete(const WriteOptions& o, ColumnFamilyHandle* cf,
  2784. const Slice& key) override {
  2785. WriteBatch batch;
  2786. Status s = batch.Delete(cf, key);
  2787. if (!s.ok()) {
  2788. return s;
  2789. }
  2790. return Write(o, &batch);
  2791. }
  2792. Status Delete(const WriteOptions& /*o*/, ColumnFamilyHandle* /*cf*/,
  2793. const Slice& /*key*/, const Slice& /*ts*/) override {
  2794. return Status::NotSupported();
  2795. }
  2796. using DB::SingleDelete;
  2797. Status SingleDelete(const WriteOptions& o, ColumnFamilyHandle* cf,
  2798. const Slice& key) override {
  2799. WriteBatch batch;
  2800. Status s = batch.SingleDelete(cf, key);
  2801. if (!s.ok()) {
  2802. return s;
  2803. }
  2804. return Write(o, &batch);
  2805. }
  2806. Status SingleDelete(const WriteOptions& /*o*/, ColumnFamilyHandle* /*cf*/,
  2807. const Slice& /*key*/, const Slice& /*ts*/) override {
  2808. return Status::NotSupported();
  2809. }
  2810. using DB::Merge;
  2811. Status Merge(const WriteOptions& o, ColumnFamilyHandle* cf, const Slice& k,
  2812. const Slice& v) override {
  2813. WriteBatch batch;
  2814. Status s = batch.Merge(cf, k, v);
  2815. if (!s.ok()) {
  2816. return s;
  2817. }
  2818. return Write(o, &batch);
  2819. }
  2820. Status Merge(const WriteOptions& /*o*/, ColumnFamilyHandle* /*cf*/,
  2821. const Slice& /*k*/, const Slice& /*ts*/,
  2822. const Slice& /*value*/) override {
  2823. return Status::NotSupported();
  2824. }
  2825. using DB::Get;
  2826. Status Get(const ReadOptions& /*options*/, ColumnFamilyHandle* /*cf*/,
  2827. const Slice& key, PinnableSlice* /*value*/,
  2828. std::string* /*timestamp*/) override {
  2829. return Status::NotSupported(key);
  2830. }
  2831. using DB::GetMergeOperands;
  2832. Status GetMergeOperands(const ReadOptions& /*options*/,
  2833. ColumnFamilyHandle* /*column_family*/,
  2834. const Slice& key, PinnableSlice* /*slice*/,
  2835. GetMergeOperandsOptions* /*merge_operands_options*/,
  2836. int* /*number_of_operands*/) override {
  2837. return Status::NotSupported(key);
  2838. }
  2839. using DB::MultiGet;
  2840. void MultiGet(const ReadOptions& /*options*/, const size_t num_keys,
  2841. ColumnFamilyHandle** /*column_families*/, const Slice* /*keys*/,
  2842. PinnableSlice* /*values*/, std::string* /*timestamps*/,
  2843. Status* statuses, const bool /*sorted_input*/) override {
  2844. for (size_t i = 0; i < num_keys; ++i) {
  2845. statuses[i] = Status::NotSupported("Not implemented.");
  2846. }
  2847. }
  2848. using DB::IngestExternalFile;
  2849. Status IngestExternalFile(
  2850. ColumnFamilyHandle* /*column_family*/,
  2851. const std::vector<std::string>& /*external_files*/,
  2852. const IngestExternalFileOptions& /*options*/) override {
  2853. return Status::NotSupported("Not implemented.");
  2854. }
  2855. using DB::IngestExternalFiles;
  2856. Status IngestExternalFiles(
  2857. const std::vector<IngestExternalFileArg>& /*args*/) override {
  2858. return Status::NotSupported("Not implemented");
  2859. }
  2860. using DB::CreateColumnFamilyWithImport;
  2861. Status CreateColumnFamilyWithImport(
  2862. const ColumnFamilyOptions& /*options*/,
  2863. const std::string& /*column_family_name*/,
  2864. const ImportColumnFamilyOptions& /*import_options*/,
  2865. const std::vector<const ExportImportFilesMetaData*>& /*metadatas*/,
  2866. ColumnFamilyHandle** /*handle*/) override {
  2867. return Status::NotSupported("Not implemented.");
  2868. }
  2869. using DB::VerifyChecksum;
  2870. Status VerifyChecksum(const ReadOptions&) override {
  2871. return Status::NotSupported("Not implemented.");
  2872. }
  2873. using DB::ClipColumnFamily;
  2874. Status ClipColumnFamily(ColumnFamilyHandle* /*column_family*/,
  2875. const Slice& /*begin*/,
  2876. const Slice& /*end*/) override {
  2877. return Status::NotSupported("Not implemented.");
  2878. }
  2879. using DB::GetPropertiesOfAllTables;
  2880. Status GetPropertiesOfAllTables(
  2881. ColumnFamilyHandle* /*column_family*/,
  2882. TablePropertiesCollection* /*props*/) override {
  2883. return Status();
  2884. }
  2885. Status GetPropertiesOfTablesInRange(
  2886. ColumnFamilyHandle* /*column_family*/, const Range* /*range*/,
  2887. std::size_t /*n*/, TablePropertiesCollection* /*props*/) override {
  2888. return Status();
  2889. }
  2890. using DB::GetPropertiesOfTablesByLevel;
  2891. Status GetPropertiesOfTablesByLevel(
  2892. ColumnFamilyHandle* /* column_family */,
  2893. std::vector<
  2894. std::unique_ptr<TablePropertiesCollection>>* /* props_by_level */)
  2895. override {
  2896. return Status();
  2897. }
  2898. using DB::KeyMayExist;
  2899. bool KeyMayExist(const ReadOptions& /*options*/,
  2900. ColumnFamilyHandle* /*column_family*/, const Slice& /*key*/,
  2901. std::string* /*value*/,
  2902. bool* value_found = nullptr) override {
  2903. if (value_found != nullptr) {
  2904. *value_found = false;
  2905. }
  2906. return true; // Not Supported directly
  2907. }
  2908. using DB::NewIterator;
  2909. Iterator* NewIterator(const ReadOptions& options,
  2910. ColumnFamilyHandle* /*column_family*/) override {
  2911. if (options.snapshot == nullptr) {
  2912. KVMap* saved = new KVMap;
  2913. *saved = map_;
  2914. return new ModelIter(saved, true);
  2915. } else {
  2916. const KVMap* snapshot_state =
  2917. &(static_cast<const ModelSnapshot*>(options.snapshot)->map_);
  2918. return new ModelIter(snapshot_state, false);
  2919. }
  2920. }
  2921. Status NewIterators(const ReadOptions& /*options*/,
  2922. const std::vector<ColumnFamilyHandle*>& /*column_family*/,
  2923. std::vector<Iterator*>* /*iterators*/) override {
  2924. return Status::NotSupported("Not supported yet");
  2925. }
  2926. std::unique_ptr<Iterator> NewCoalescingIterator(
  2927. const ReadOptions& /*options*/,
  2928. const std::vector<ColumnFamilyHandle*>& /*column_families*/) override {
  2929. return std::unique_ptr<Iterator>(
  2930. NewErrorIterator(Status::NotSupported("Not supported yet")));
  2931. }
  2932. std::unique_ptr<AttributeGroupIterator> NewAttributeGroupIterator(
  2933. const ReadOptions& /*options*/,
  2934. const std::vector<ColumnFamilyHandle*>& /*column_families*/) override {
  2935. return NewAttributeGroupErrorIterator(
  2936. Status::NotSupported("Not supported yet"));
  2937. }
  2938. const Snapshot* GetSnapshot() override {
  2939. ModelSnapshot* snapshot = new ModelSnapshot;
  2940. snapshot->map_ = map_;
  2941. return snapshot;
  2942. }
  2943. void ReleaseSnapshot(const Snapshot* snapshot) override {
  2944. delete static_cast<const ModelSnapshot*>(snapshot);
  2945. }
  2946. Status Write(const WriteOptions& /*options*/, WriteBatch* batch) override {
  2947. class Handler : public WriteBatch::Handler {
  2948. public:
  2949. KVMap* map_;
  2950. void Put(const Slice& key, const Slice& value) override {
  2951. (*map_)[key.ToString()] = value.ToString();
  2952. }
  2953. void Merge(const Slice& /*key*/, const Slice& /*value*/) override {
  2954. // ignore merge for now
  2955. // (*map_)[key.ToString()] = value.ToString();
  2956. }
  2957. void Delete(const Slice& key) override { map_->erase(key.ToString()); }
  2958. };
  2959. Handler handler;
  2960. handler.map_ = &map_;
  2961. return batch->Iterate(&handler);
  2962. }
  2963. using DB::GetProperty;
  2964. bool GetProperty(ColumnFamilyHandle* /*column_family*/,
  2965. const Slice& /*property*/, std::string* /*value*/) override {
  2966. return false;
  2967. }
  2968. using DB::GetIntProperty;
  2969. bool GetIntProperty(ColumnFamilyHandle* /*column_family*/,
  2970. const Slice& /*property*/, uint64_t* /*value*/) override {
  2971. return false;
  2972. }
  2973. using DB::GetMapProperty;
  2974. bool GetMapProperty(ColumnFamilyHandle* /*column_family*/,
  2975. const Slice& /*property*/,
  2976. std::map<std::string, std::string>* /*value*/) override {
  2977. return false;
  2978. }
  2979. using DB::GetAggregatedIntProperty;
  2980. bool GetAggregatedIntProperty(const Slice& /*property*/,
  2981. uint64_t* /*value*/) override {
  2982. return false;
  2983. }
  2984. using DB::GetApproximateSizes;
  2985. Status GetApproximateSizes(const SizeApproximationOptions& /*options*/,
  2986. ColumnFamilyHandle* /*column_family*/,
  2987. const Range* /*range*/, int n,
  2988. uint64_t* sizes) override {
  2989. for (int i = 0; i < n; i++) {
  2990. sizes[i] = 0;
  2991. }
  2992. return Status::OK();
  2993. }
  2994. using DB::GetApproximateMemTableStats;
  2995. void GetApproximateMemTableStats(ColumnFamilyHandle* /*column_family*/,
  2996. const Range& /*range*/,
  2997. uint64_t* const count,
  2998. uint64_t* const size) override {
  2999. *count = 0;
  3000. *size = 0;
  3001. }
  3002. using DB::CompactRange;
  3003. Status CompactRange(const CompactRangeOptions& /*options*/,
  3004. ColumnFamilyHandle* /*column_family*/,
  3005. const Slice* /*start*/, const Slice* /*end*/) override {
  3006. return Status::NotSupported("Not supported operation.");
  3007. }
  3008. Status SetDBOptions(
  3009. const std::unordered_map<std::string, std::string>& /*new_options*/)
  3010. override {
  3011. return Status::NotSupported("Not supported operation.");
  3012. }
  3013. using DB::CompactFiles;
  3014. Status CompactFiles(
  3015. const CompactionOptions& /*compact_options*/,
  3016. ColumnFamilyHandle* /*column_family*/,
  3017. const std::vector<std::string>& /*input_file_names*/,
  3018. const int /*output_level*/, const int /*output_path_id*/ = -1,
  3019. std::vector<std::string>* const /*output_file_names*/ = nullptr,
  3020. CompactionJobInfo* /*compaction_job_info*/ = nullptr) override {
  3021. return Status::NotSupported("Not supported operation.");
  3022. }
  3023. Status PauseBackgroundWork() override {
  3024. return Status::NotSupported("Not supported operation.");
  3025. }
  3026. Status ContinueBackgroundWork() override {
  3027. return Status::NotSupported("Not supported operation.");
  3028. }
  3029. Status EnableAutoCompaction(
  3030. const std::vector<ColumnFamilyHandle*>& /*column_family_handles*/)
  3031. override {
  3032. return Status::NotSupported("Not supported operation.");
  3033. }
  3034. void EnableManualCompaction() override {}
  3035. void DisableManualCompaction() override {}
  3036. Status WaitForCompact(
  3037. const WaitForCompactOptions& /* wait_for_compact_options */) override {
  3038. return Status::OK();
  3039. }
  3040. using DB::NumberLevels;
  3041. int NumberLevels(ColumnFamilyHandle* /*column_family*/) override { return 1; }
  3042. using DB::Level0StopWriteTrigger;
  3043. int Level0StopWriteTrigger(ColumnFamilyHandle* /*column_family*/) override {
  3044. return -1;
  3045. }
  3046. const std::string& GetName() const override { return name_; }
  3047. Env* GetEnv() const override { return nullptr; }
  3048. using DB::GetOptions;
  3049. Options GetOptions(ColumnFamilyHandle* /*column_family*/) const override {
  3050. return options_;
  3051. }
  3052. using DB::GetDBOptions;
  3053. DBOptions GetDBOptions() const override { return options_; }
  3054. using DB::Flush;
  3055. Status Flush(const ROCKSDB_NAMESPACE::FlushOptions& /*options*/,
  3056. ColumnFamilyHandle* /*column_family*/) override {
  3057. Status ret;
  3058. return ret;
  3059. }
  3060. Status Flush(
  3061. const ROCKSDB_NAMESPACE::FlushOptions& /*options*/,
  3062. const std::vector<ColumnFamilyHandle*>& /*column_families*/) override {
  3063. return Status::OK();
  3064. }
  3065. Status SyncWAL() override { return Status::OK(); }
  3066. Status DisableFileDeletions() override { return Status::OK(); }
  3067. Status EnableFileDeletions() override { return Status::OK(); }
  3068. Status GetLiveFiles(std::vector<std::string>&, uint64_t* /*size*/,
  3069. bool /*flush_memtable*/ = true) override {
  3070. return Status::OK();
  3071. }
  3072. Status GetLiveFilesChecksumInfo(
  3073. FileChecksumList* /*checksum_list*/) override {
  3074. return Status::OK();
  3075. }
  3076. Status GetLiveFilesStorageInfo(
  3077. const LiveFilesStorageInfoOptions& /*opts*/,
  3078. std::vector<LiveFileStorageInfo>* /*files*/) override {
  3079. return Status::OK();
  3080. }
  3081. Status GetSortedWalFiles(VectorLogPtr& /*files*/) override {
  3082. return Status::OK();
  3083. }
  3084. Status GetCurrentWalFile(
  3085. std::unique_ptr<LogFile>* /*current_wal_file*/) override {
  3086. return Status::OK();
  3087. }
  3088. Status GetCreationTimeOfOldestFile(uint64_t* /*creation_time*/) override {
  3089. return Status::NotSupported();
  3090. }
  3091. Status GetUpdatesSince(
  3092. ROCKSDB_NAMESPACE::SequenceNumber,
  3093. std::unique_ptr<ROCKSDB_NAMESPACE::TransactionLogIterator>*,
  3094. const TransactionLogIterator::ReadOptions& /*read_options*/ =
  3095. TransactionLogIterator::ReadOptions()) override {
  3096. return Status::NotSupported("Not supported in Model DB");
  3097. }
  3098. void GetColumnFamilyMetaData(ColumnFamilyHandle* /*column_family*/,
  3099. ColumnFamilyMetaData* /*metadata*/) override {}
  3100. Status GetDbIdentity(std::string& /*identity*/) const override {
  3101. return Status::OK();
  3102. }
  3103. Status GetDbSessionId(std::string& /*session_id*/) const override {
  3104. return Status::OK();
  3105. }
  3106. SequenceNumber GetLatestSequenceNumber() const override { return 0; }
  3107. Status IncreaseFullHistoryTsLow(ColumnFamilyHandle* /*cf*/,
  3108. std::string /*ts_low*/) override {
  3109. return Status::OK();
  3110. }
  3111. Status GetFullHistoryTsLow(ColumnFamilyHandle* /*cf*/,
  3112. std::string* /*ts_low*/) override {
  3113. return Status::OK();
  3114. }
  3115. Status GetNewestUserDefinedTimestamp(
  3116. ColumnFamilyHandle* /*cf*/, std::string* /*newest_timestamp*/) override {
  3117. return Status::OK();
  3118. }
  3119. ColumnFamilyHandle* DefaultColumnFamily() const override { return nullptr; }
  3120. private:
  3121. class ModelIter : public Iterator {
  3122. public:
  3123. ModelIter(const KVMap* map, bool owned)
  3124. : map_(map), owned_(owned), iter_(map_->end()) {}
  3125. ~ModelIter() override {
  3126. if (owned_) {
  3127. delete map_;
  3128. }
  3129. }
  3130. bool Valid() const override { return iter_ != map_->end(); }
  3131. void SeekToFirst() override { iter_ = map_->begin(); }
  3132. void SeekToLast() override {
  3133. if (map_->empty()) {
  3134. iter_ = map_->end();
  3135. } else {
  3136. iter_ = map_->find(map_->rbegin()->first);
  3137. }
  3138. }
  3139. void Seek(const Slice& k) override {
  3140. iter_ = map_->lower_bound(k.ToString());
  3141. }
  3142. void SeekForPrev(const Slice& k) override {
  3143. iter_ = map_->upper_bound(k.ToString());
  3144. Prev();
  3145. }
  3146. void Next() override { ++iter_; }
  3147. void Prev() override {
  3148. if (iter_ == map_->begin()) {
  3149. iter_ = map_->end();
  3150. return;
  3151. }
  3152. --iter_;
  3153. }
  3154. Slice key() const override { return iter_->first; }
  3155. Slice value() const override { return iter_->second; }
  3156. Status status() const override { return Status::OK(); }
  3157. private:
  3158. const KVMap* const map_;
  3159. const bool owned_; // Do we own map_
  3160. KVMap::const_iterator iter_;
  3161. };
  3162. const Options options_;
  3163. KVMap map_;
  3164. std::string name_;
  3165. };
  3166. #if !defined(ROCKSDB_VALGRIND_RUN) || defined(ROCKSDB_FULL_VALGRIND_RUN)
  3167. static std::string RandomKey(Random* rnd, int minimum = 0) {
  3168. int len;
  3169. do {
  3170. len = (rnd->OneIn(3)
  3171. ? 1 // Short sometimes to encourage collisions
  3172. : (rnd->OneIn(100) ? rnd->Skewed(10) : rnd->Uniform(10)));
  3173. } while (len < minimum);
  3174. return test::RandomKey(rnd, len);
  3175. }
  3176. static bool CompareIterators(int step, DB* model, DB* db,
  3177. const Snapshot* model_snap,
  3178. const Snapshot* db_snap) {
  3179. ReadOptions options;
  3180. options.snapshot = model_snap;
  3181. Iterator* miter = model->NewIterator(options);
  3182. options.snapshot = db_snap;
  3183. Iterator* dbiter = db->NewIterator(options);
  3184. bool ok = true;
  3185. int count = 0;
  3186. for (miter->SeekToFirst(), dbiter->SeekToFirst();
  3187. ok && miter->Valid() && dbiter->Valid(); miter->Next(), dbiter->Next()) {
  3188. count++;
  3189. if (miter->key().compare(dbiter->key()) != 0) {
  3190. fprintf(stderr, "step %d: Key mismatch: '%s' vs. '%s'\n", step,
  3191. EscapeString(miter->key()).c_str(),
  3192. EscapeString(dbiter->key()).c_str());
  3193. ok = false;
  3194. break;
  3195. }
  3196. if (miter->value().compare(dbiter->value()) != 0) {
  3197. fprintf(stderr, "step %d: Value mismatch for key '%s': '%s' vs. '%s'\n",
  3198. step, EscapeString(miter->key()).c_str(),
  3199. EscapeString(miter->value()).c_str(),
  3200. EscapeString(dbiter->value()).c_str());
  3201. ok = false;
  3202. }
  3203. }
  3204. if (ok) {
  3205. if (miter->Valid() != dbiter->Valid()) {
  3206. fprintf(stderr, "step %d: Mismatch at end of iterators: %d vs. %d\n",
  3207. step, miter->Valid(), dbiter->Valid());
  3208. ok = false;
  3209. }
  3210. }
  3211. EXPECT_OK(miter->status());
  3212. EXPECT_OK(dbiter->status());
  3213. (void)count;
  3214. delete miter;
  3215. delete dbiter;
  3216. return ok;
  3217. }
  3218. class DBTestRandomized : public DBTest,
  3219. public ::testing::WithParamInterface<int> {
  3220. public:
  3221. void SetUp() override { option_config_ = GetParam(); }
  3222. static std::vector<int> GenerateOptionConfigs() {
  3223. std::vector<int> option_configs;
  3224. // skip cuckoo hash as it does not support snapshot.
  3225. for (int option_config = kDefault; option_config < kEnd; ++option_config) {
  3226. if (!ShouldSkipOptions(option_config,
  3227. kSkipDeletesFilterFirst | kSkipNoSeekToLast)) {
  3228. option_configs.push_back(option_config);
  3229. }
  3230. }
  3231. option_configs.push_back(kBlockBasedTableWithIndexRestartInterval);
  3232. return option_configs;
  3233. }
  3234. };
  3235. INSTANTIATE_TEST_CASE_P(
  3236. DBTestRandomized, DBTestRandomized,
  3237. ::testing::ValuesIn(DBTestRandomized::GenerateOptionConfigs()));
  3238. TEST_P(DBTestRandomized, Randomized) {
  3239. anon::OptionsOverride options_override;
  3240. options_override.skip_policy = kSkipNoSnapshot;
  3241. Options options = CurrentOptions(options_override);
  3242. DestroyAndReopen(options);
  3243. Random rnd(test::RandomSeed() + GetParam());
  3244. ModelDB model(options);
  3245. const int N = 10000;
  3246. const Snapshot* model_snap = nullptr;
  3247. const Snapshot* db_snap = nullptr;
  3248. std::string k, v;
  3249. for (int step = 0; step < N; step++) {
  3250. // TODO(sanjay): Test Get() works
  3251. int p = rnd.Uniform(100);
  3252. int minimum = 0;
  3253. if (option_config_ == kHashSkipList || option_config_ == kHashLinkList ||
  3254. option_config_ == kPlainTableFirstBytePrefix ||
  3255. option_config_ == kBlockBasedTableWithWholeKeyHashIndex ||
  3256. option_config_ == kBlockBasedTableWithPrefixHashIndex) {
  3257. minimum = 1;
  3258. }
  3259. if (p < 45) { // Put
  3260. k = RandomKey(&rnd, minimum);
  3261. v = rnd.RandomString(rnd.OneIn(20) ? 100 + rnd.Uniform(100)
  3262. : rnd.Uniform(8));
  3263. ASSERT_OK(model.Put(WriteOptions(), k, v));
  3264. ASSERT_OK(db_->Put(WriteOptions(), k, v));
  3265. } else if (p < 90) { // Delete
  3266. k = RandomKey(&rnd, minimum);
  3267. ASSERT_OK(model.Delete(WriteOptions(), k));
  3268. ASSERT_OK(db_->Delete(WriteOptions(), k));
  3269. } else { // Multi-element batch
  3270. WriteBatch b;
  3271. const int num = rnd.Uniform(8);
  3272. for (int i = 0; i < num; i++) {
  3273. if (i == 0 || !rnd.OneIn(10)) {
  3274. k = RandomKey(&rnd, minimum);
  3275. } else {
  3276. // Periodically re-use the same key from the previous iter, so
  3277. // we have multiple entries in the write batch for the same key
  3278. }
  3279. if (rnd.OneIn(2)) {
  3280. v = rnd.RandomString(rnd.Uniform(10));
  3281. ASSERT_OK(b.Put(k, v));
  3282. } else {
  3283. ASSERT_OK(b.Delete(k));
  3284. }
  3285. }
  3286. ASSERT_OK(model.Write(WriteOptions(), &b));
  3287. ASSERT_OK(db_->Write(WriteOptions(), &b));
  3288. }
  3289. if ((step % 100) == 0) {
  3290. // For DB instances that use the hash index + block-based table, the
  3291. // iterator will be invalid right when seeking a non-existent key, right
  3292. // than return a key that is close to it.
  3293. if (option_config_ != kBlockBasedTableWithWholeKeyHashIndex &&
  3294. option_config_ != kBlockBasedTableWithPrefixHashIndex) {
  3295. ASSERT_TRUE(CompareIterators(step, &model, db_, nullptr, nullptr));
  3296. ASSERT_TRUE(CompareIterators(step, &model, db_, model_snap, db_snap));
  3297. }
  3298. // Save a snapshot from each DB this time that we'll use next
  3299. // time we compare things, to make sure the current state is
  3300. // preserved with the snapshot
  3301. if (model_snap != nullptr) {
  3302. model.ReleaseSnapshot(model_snap);
  3303. }
  3304. if (db_snap != nullptr) {
  3305. db_->ReleaseSnapshot(db_snap);
  3306. }
  3307. Reopen(options);
  3308. ASSERT_TRUE(CompareIterators(step, &model, db_, nullptr, nullptr));
  3309. model_snap = model.GetSnapshot();
  3310. db_snap = db_->GetSnapshot();
  3311. }
  3312. }
  3313. if (model_snap != nullptr) {
  3314. model.ReleaseSnapshot(model_snap);
  3315. }
  3316. if (db_snap != nullptr) {
  3317. db_->ReleaseSnapshot(db_snap);
  3318. }
  3319. }
  3320. #endif // !defined(ROCKSDB_VALGRIND_RUN) || defined(ROCKSDB_FULL_VALGRIND_RUN)
  3321. TEST_F(DBTest, BlockBasedTablePrefixIndexTest) {
  3322. // create a DB with block prefix index
  3323. BlockBasedTableOptions table_options;
  3324. Options options = CurrentOptions();
  3325. table_options.index_type = BlockBasedTableOptions::kHashSearch;
  3326. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  3327. options.prefix_extractor.reset(NewFixedPrefixTransform(1));
  3328. Reopen(options);
  3329. ASSERT_OK(Put("k1", "v1"));
  3330. ASSERT_OK(Flush());
  3331. ASSERT_OK(Put("k2", "v2"));
  3332. // Reopen with different prefix extractor, make sure everything still works.
  3333. // RocksDB should just fall back to the binary index.
  3334. options.prefix_extractor.reset(NewFixedPrefixTransform(2));
  3335. Reopen(options);
  3336. ASSERT_EQ("v1", Get("k1"));
  3337. ASSERT_EQ("v2", Get("k2"));
  3338. // Back to original
  3339. ASSERT_OK(dbfull()->SetOptions({{"prefix_extractor", "fixed:1"}}));
  3340. ASSERT_EQ("v1", Get("k1"));
  3341. ASSERT_EQ("v2", Get("k2"));
  3342. // Same if there's a problem initally loading prefix transform
  3343. options.prefix_extractor.reset(NewFixedPrefixTransform(1));
  3344. SyncPoint::GetInstance()->SetCallBack(
  3345. "BlockBasedTable::Open::ForceNullTablePrefixExtractor",
  3346. [&](void* arg) { *static_cast<bool*>(arg) = true; });
  3347. SyncPoint::GetInstance()->EnableProcessing();
  3348. Reopen(options);
  3349. ASSERT_EQ("v1", Get("k1"));
  3350. ASSERT_EQ("v2", Get("k2"));
  3351. // Change again
  3352. ASSERT_OK(dbfull()->SetOptions({{"prefix_extractor", "fixed:2"}}));
  3353. ASSERT_EQ("v1", Get("k1"));
  3354. ASSERT_EQ("v2", Get("k2"));
  3355. SyncPoint::GetInstance()->DisableProcessing();
  3356. // Reopen with no prefix extractor, make sure everything still works.
  3357. // RocksDB should just fall back to the binary index.
  3358. table_options.index_type = BlockBasedTableOptions::kBinarySearch;
  3359. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  3360. options.prefix_extractor.reset();
  3361. Reopen(options);
  3362. ASSERT_EQ("v1", Get("k1"));
  3363. ASSERT_EQ("v2", Get("k2"));
  3364. }
  3365. TEST_F(DBTest, SetOptionsEffectiveInSuperVersions) {
  3366. // Basically, to test the SetOptions take effect with (and only with)
  3367. // new SuperVersions, and remain in effect through some things like
  3368. // flush and compaction, we use some queries that depend on the current
  3369. // prefix extractor.
  3370. //
  3371. // Making the semantics of read options dependent on the current state of
  3372. // mutable options is kind of an anti-pattern that prefix_seek_opt_in_only
  3373. // is helping to phase out. However, this is useful for rather directly
  3374. // testing the expected behavior of mutable options handling.
  3375. ReadOptions ropts;
  3376. ropts.prefix_same_as_start = true;
  3377. Options options = CurrentOptions();
  3378. options.prefix_extractor.reset(NewFixedPrefixTransform(5));
  3379. options.prefix_seek_opt_in_only = false;
  3380. Reopen(options);
  3381. ASSERT_OK(Put("goat1", "g1"));
  3382. ASSERT_OK(Put("goat2", "g2"));
  3383. std::unique_ptr<Iterator> iter(db_->NewIterator(ropts));
  3384. auto VerifyTransform4 = [&](int caller_line) {
  3385. SCOPED_TRACE("Called from " + std::to_string(caller_line));
  3386. // Nothing with this prefix
  3387. iter->Seek("game1");
  3388. ASSERT_OK(iter->status());
  3389. ASSERT_FALSE(iter->Valid());
  3390. iter->Seek("goat1");
  3391. ASSERT_OK(iter->status());
  3392. ASSERT_TRUE(iter->Valid());
  3393. ASSERT_EQ("goat1", iter->key());
  3394. iter->Next();
  3395. ASSERT_OK(iter->status());
  3396. ASSERT_TRUE(iter->Valid());
  3397. ASSERT_EQ("goat2", iter->key());
  3398. };
  3399. auto VerifyTransform5 = [&](int caller_line) {
  3400. SCOPED_TRACE("Called from " + std::to_string(caller_line));
  3401. // Nothing with this prefix
  3402. iter->Seek("game1");
  3403. ASSERT_OK(iter->status());
  3404. ASSERT_FALSE(iter->Valid());
  3405. iter->Seek("goat1");
  3406. ASSERT_OK(iter->status());
  3407. ASSERT_TRUE(iter->Valid());
  3408. ASSERT_EQ("goat1", iter->key());
  3409. iter->Next();
  3410. ASSERT_OK(iter->status());
  3411. ASSERT_FALSE(iter->Valid());
  3412. iter->Seek("goat2");
  3413. ASSERT_OK(iter->status());
  3414. ASSERT_TRUE(iter->Valid());
  3415. ASSERT_EQ("goat2", iter->key());
  3416. iter->Next();
  3417. ASSERT_OK(iter->status());
  3418. ASSERT_FALSE(iter->Valid());
  3419. };
  3420. for (int i = 0;; ++i) {
  3421. SCOPED_TRACE("Iteration " + std::to_string(i));
  3422. // Baseline
  3423. VerifyTransform5(__LINE__);
  3424. if (i == 0) {
  3425. // Test a "normal" change with nothing happening in parallel
  3426. ASSERT_OK(db_->SetOptions({{"prefix_extractor", "fixed:4"}}));
  3427. // Iterator still uses old superversion
  3428. VerifyTransform5(__LINE__);
  3429. // Refresh updates the SuperVersion
  3430. ASSERT_OK(iter->Refresh());
  3431. } else if (i == 1) {
  3432. // Test a setting change in parallel with flush
  3433. iter = nullptr;
  3434. SyncPoint::GetInstance()->DisableProcessing();
  3435. SyncPoint::GetInstance()->ClearAllCallBacks();
  3436. SyncPoint::GetInstance()->SetCallBack(
  3437. "FlushJob::WriteLevel0Table:num_memtables", [&](void*) {
  3438. // During flush, without DB mutex held
  3439. ASSERT_OK(db_->SetOptions({{"prefix_extractor", "fixed:4"}}));
  3440. iter.reset(db_->NewIterator(ropts));
  3441. VerifyTransform4(__LINE__);
  3442. });
  3443. SyncPoint::GetInstance()->EnableProcessing();
  3444. ASSERT_OK(Flush());
  3445. SyncPoint::GetInstance()->DisableProcessing();
  3446. SyncPoint::GetInstance()->ClearAllCallBacks();
  3447. // Callback was called
  3448. ASSERT_NE(iter, nullptr);
  3449. } else if (i == 2) {
  3450. // Test a setting change in parallel with compaction
  3451. iter = nullptr;
  3452. SyncPoint::GetInstance()->DisableProcessing();
  3453. SyncPoint::GetInstance()->ClearAllCallBacks();
  3454. SyncPoint::GetInstance()->SetCallBack(
  3455. "CompactionJob::Run():EndStatusSet", [&](void*) {
  3456. // During compaction, without DB mutex held
  3457. ASSERT_OK(db_->SetOptions({{"prefix_extractor", "fixed:4"}}));
  3458. iter.reset(db_->NewIterator(ropts));
  3459. VerifyTransform4(__LINE__);
  3460. });
  3461. SyncPoint::GetInstance()->EnableProcessing();
  3462. // Need data overlapping that L0 file to prevent trivial move
  3463. ASSERT_OK(Put("aaaaa", "a"));
  3464. ASSERT_OK(Put("zzzzz", "a"));
  3465. ASSERT_OK(CompactRange({}, {}, {}));
  3466. SyncPoint::GetInstance()->DisableProcessing();
  3467. SyncPoint::GetInstance()->ClearAllCallBacks();
  3468. // Callback was called
  3469. ASSERT_NE(iter, nullptr);
  3470. } else {
  3471. break;
  3472. }
  3473. // Change has taken effect
  3474. VerifyTransform4(__LINE__);
  3475. // Same after a new iterator (in case a new SuperVersion reverted the
  3476. // setting)
  3477. iter.reset(db_->NewIterator(ropts));
  3478. VerifyTransform4(__LINE__);
  3479. // Back to baseline setting
  3480. ASSERT_OK(db_->SetOptions({{"prefix_extractor", "fixed:5"}}));
  3481. // New iterator uses latest SuperVersion
  3482. iter.reset(db_->NewIterator(ropts));
  3483. }
  3484. }
  3485. TEST_F(DBTest, BlockBasedTablePrefixHashIndexTest) {
  3486. // create a DB with block prefix index
  3487. BlockBasedTableOptions table_options;
  3488. Options options = CurrentOptions();
  3489. table_options.index_type = BlockBasedTableOptions::kHashSearch;
  3490. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  3491. options.prefix_extractor.reset(NewCappedPrefixTransform(2));
  3492. Reopen(options);
  3493. ASSERT_OK(Put("kk1", "v1"));
  3494. ASSERT_OK(Put("kk2", "v2"));
  3495. ASSERT_OK(Put("kk", "v3"));
  3496. ASSERT_OK(Put("k", "v4"));
  3497. ASSERT_OK(Flush());
  3498. ASSERT_EQ("v1", Get("kk1"));
  3499. ASSERT_EQ("v2", Get("kk2"));
  3500. ASSERT_EQ("v3", Get("kk"));
  3501. ASSERT_EQ("v4", Get("k"));
  3502. }
  3503. TEST_F(DBTest, BlockBasedTablePrefixIndexTotalOrderSeek) {
  3504. // create a DB with block prefix index
  3505. BlockBasedTableOptions table_options;
  3506. Options options = CurrentOptions();
  3507. options.max_open_files = 10;
  3508. table_options.index_type = BlockBasedTableOptions::kHashSearch;
  3509. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  3510. options.prefix_extractor.reset(NewFixedPrefixTransform(1));
  3511. // RocksDB sanitize max open files to at least 20. Modify it back.
  3512. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  3513. "SanitizeOptions::AfterChangeMaxOpenFiles", [&](void* arg) {
  3514. int* max_open_files = static_cast<int*>(arg);
  3515. *max_open_files = 11;
  3516. });
  3517. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  3518. Reopen(options);
  3519. ASSERT_OK(Put("k1", "v1"));
  3520. ASSERT_OK(Flush());
  3521. CompactRangeOptions cro;
  3522. cro.change_level = true;
  3523. cro.target_level = 1;
  3524. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  3525. // Force evict tables
  3526. dbfull()->TEST_table_cache()->SetCapacity(0);
  3527. // Make table cache to keep one entry.
  3528. dbfull()->TEST_table_cache()->SetCapacity(1);
  3529. ReadOptions read_options;
  3530. read_options.total_order_seek = true;
  3531. {
  3532. std::unique_ptr<Iterator> iter(db_->NewIterator(read_options));
  3533. iter->Seek("k1");
  3534. ASSERT_TRUE(iter->Valid());
  3535. ASSERT_EQ("k1", iter->key().ToString());
  3536. }
  3537. // After total order seek, prefix index should still be used.
  3538. read_options.total_order_seek = false;
  3539. {
  3540. std::unique_ptr<Iterator> iter(db_->NewIterator(read_options));
  3541. iter->Seek("k1");
  3542. ASSERT_TRUE(iter->Valid());
  3543. ASSERT_EQ("k1", iter->key().ToString());
  3544. }
  3545. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  3546. }
  3547. TEST_F(DBTest, ChecksumTest) {
  3548. BlockBasedTableOptions table_options;
  3549. Options options = CurrentOptions();
  3550. table_options.checksum = kCRC32c;
  3551. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  3552. Reopen(options);
  3553. ASSERT_OK(Put("a", "b"));
  3554. ASSERT_OK(Put("c", "d"));
  3555. ASSERT_OK(Flush()); // table with crc checksum
  3556. table_options.checksum = kxxHash;
  3557. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  3558. Reopen(options);
  3559. ASSERT_OK(Put("e", "f"));
  3560. ASSERT_OK(Put("g", "h"));
  3561. ASSERT_OK(Flush()); // table with xxhash checksum
  3562. table_options.checksum = kCRC32c;
  3563. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  3564. Reopen(options);
  3565. ASSERT_EQ("b", Get("a"));
  3566. ASSERT_EQ("d", Get("c"));
  3567. ASSERT_EQ("f", Get("e"));
  3568. ASSERT_EQ("h", Get("g"));
  3569. table_options.checksum = kCRC32c;
  3570. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  3571. Reopen(options);
  3572. ASSERT_EQ("b", Get("a"));
  3573. ASSERT_EQ("d", Get("c"));
  3574. ASSERT_EQ("f", Get("e"));
  3575. ASSERT_EQ("h", Get("g"));
  3576. }
  3577. TEST_P(DBTestWithParam, FIFOCompactionTest) {
  3578. for (int iter = 0; iter < 2; ++iter) {
  3579. // first iteration -- auto compaction
  3580. // second iteration -- manual compaction
  3581. Options options;
  3582. options.compaction_style = kCompactionStyleFIFO;
  3583. options.write_buffer_size = 100 << 10; // 100KB
  3584. options.arena_block_size = 4096;
  3585. options.compaction_options_fifo.max_table_files_size = 500 << 10; // 500KB
  3586. options.compression = kNoCompression;
  3587. options.create_if_missing = true;
  3588. options.max_subcompactions = max_subcompactions_;
  3589. if (iter == 1) {
  3590. options.disable_auto_compactions = true;
  3591. }
  3592. options = CurrentOptions(options);
  3593. DestroyAndReopen(options);
  3594. Random rnd(301);
  3595. for (int i = 0; i < 6; ++i) {
  3596. for (int j = 0; j < 110; ++j) {
  3597. ASSERT_OK(Put(std::to_string(i * 100 + j), rnd.RandomString(980)));
  3598. }
  3599. // flush should happen here
  3600. ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
  3601. }
  3602. if (iter == 0) {
  3603. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  3604. } else {
  3605. CompactRangeOptions cro;
  3606. cro.exclusive_manual_compaction = exclusive_manual_compaction_;
  3607. cro.change_level = true;
  3608. ASSERT_TRUE(db_->CompactRange(cro, nullptr, nullptr).IsNotSupported());
  3609. cro.change_level = false;
  3610. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  3611. }
  3612. // only 5 files should survive
  3613. ASSERT_EQ(NumTableFilesAtLevel(0), 5);
  3614. for (int i = 0; i < 50; ++i) {
  3615. // these keys should be deleted in previous compaction
  3616. ASSERT_EQ("NOT_FOUND", Get(std::to_string(i)));
  3617. }
  3618. }
  3619. }
  3620. TEST_F(DBTest, FIFOCompactionTestWithCompaction) {
  3621. Options options;
  3622. options.compaction_style = kCompactionStyleFIFO;
  3623. options.write_buffer_size = 20 << 10; // 20K
  3624. options.arena_block_size = 4096;
  3625. options.compaction_options_fifo.max_table_files_size = 1500 << 10; // 1MB
  3626. options.compaction_options_fifo.allow_compaction = true;
  3627. options.level0_file_num_compaction_trigger = 6;
  3628. options.compression = kNoCompression;
  3629. options.create_if_missing = true;
  3630. options = CurrentOptions(options);
  3631. DestroyAndReopen(options);
  3632. Random rnd(301);
  3633. for (int i = 0; i < 60; i++) {
  3634. // Generate and flush a file about 20KB.
  3635. for (int j = 0; j < 20; j++) {
  3636. ASSERT_OK(Put(std::to_string(i * 20 + j), rnd.RandomString(980)));
  3637. }
  3638. ASSERT_OK(Flush());
  3639. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  3640. }
  3641. // It should be compacted to 10 files.
  3642. ASSERT_EQ(NumTableFilesAtLevel(0), 10);
  3643. for (int i = 0; i < 60; i++) {
  3644. // Generate and flush a file about 20KB.
  3645. for (int j = 0; j < 20; j++) {
  3646. ASSERT_OK(Put(std::to_string(i * 20 + j + 2000), rnd.RandomString(980)));
  3647. }
  3648. ASSERT_OK(Flush());
  3649. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  3650. }
  3651. // It should be compacted to no more than 20 files.
  3652. ASSERT_GT(NumTableFilesAtLevel(0), 10);
  3653. ASSERT_LT(NumTableFilesAtLevel(0), 18);
  3654. // Size limit is still guaranteed.
  3655. ASSERT_LE(SizeAtLevel(0),
  3656. options.compaction_options_fifo.max_table_files_size);
  3657. }
  3658. TEST_F(DBTest, FIFOCompactionStyleWithCompactionAndDelete) {
  3659. Options options;
  3660. options.compaction_style = kCompactionStyleFIFO;
  3661. options.write_buffer_size = 20 << 10; // 20K
  3662. options.arena_block_size = 4096;
  3663. options.compaction_options_fifo.max_table_files_size = 1500 << 10; // 1MB
  3664. options.compaction_options_fifo.allow_compaction = true;
  3665. options.level0_file_num_compaction_trigger = 3;
  3666. options.compression = kNoCompression;
  3667. options.create_if_missing = true;
  3668. options = CurrentOptions(options);
  3669. DestroyAndReopen(options);
  3670. Random rnd(301);
  3671. for (int i = 0; i < 3; i++) {
  3672. // Each file contains a different key which will be dropped later.
  3673. ASSERT_OK(Put("a" + std::to_string(i), rnd.RandomString(500)));
  3674. ASSERT_OK(Put("key" + std::to_string(i), ""));
  3675. ASSERT_OK(Put("z" + std::to_string(i), rnd.RandomString(500)));
  3676. ASSERT_OK(Flush());
  3677. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  3678. }
  3679. ASSERT_EQ(NumTableFilesAtLevel(0), 1);
  3680. for (int i = 0; i < 3; i++) {
  3681. ASSERT_EQ("", Get("key" + std::to_string(i)));
  3682. }
  3683. for (int i = 0; i < 3; i++) {
  3684. // Each file contains a different key which will be dropped later.
  3685. ASSERT_OK(Put("a" + std::to_string(i), rnd.RandomString(500)));
  3686. ASSERT_OK(Delete("key" + std::to_string(i)));
  3687. ASSERT_OK(Put("z" + std::to_string(i), rnd.RandomString(500)));
  3688. ASSERT_OK(Flush());
  3689. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  3690. }
  3691. ASSERT_EQ(NumTableFilesAtLevel(0), 2);
  3692. for (int i = 0; i < 3; i++) {
  3693. ASSERT_EQ("NOT_FOUND", Get("key" + std::to_string(i)));
  3694. }
  3695. }
  3696. // Check that FIFO-with-TTL is not supported with max_open_files != -1.
  3697. // Github issue #8014
  3698. TEST_F(DBTest, FIFOCompactionWithTTLAndMaxOpenFilesTest) {
  3699. Options options = CurrentOptions();
  3700. options.compaction_style = kCompactionStyleFIFO;
  3701. options.create_if_missing = true;
  3702. options.ttl = 600; // seconds
  3703. // TTL is not supported with max_open_files != -1.
  3704. options.max_open_files = 0;
  3705. ASSERT_TRUE(TryReopen(options).IsNotSupported());
  3706. options.max_open_files = 100;
  3707. ASSERT_TRUE(TryReopen(options).IsNotSupported());
  3708. // TTL is supported with unlimited max_open_files
  3709. options.max_open_files = -1;
  3710. ASSERT_OK(TryReopen(options));
  3711. }
  3712. // Check that FIFO-with-TTL is supported only with BlockBasedTableFactory.
  3713. TEST_F(DBTest, FIFOCompactionWithTTLAndVariousTableFormatsTest) {
  3714. Options options;
  3715. options.compaction_style = kCompactionStyleFIFO;
  3716. options.create_if_missing = true;
  3717. options.ttl = 600; // seconds
  3718. options = CurrentOptions(options);
  3719. options.table_factory.reset(NewBlockBasedTableFactory());
  3720. ASSERT_OK(TryReopen(options));
  3721. Destroy(options);
  3722. options.table_factory.reset(NewPlainTableFactory());
  3723. ASSERT_TRUE(TryReopen(options).IsNotSupported());
  3724. Destroy(options);
  3725. options.table_factory.reset(NewAdaptiveTableFactory());
  3726. ASSERT_TRUE(TryReopen(options).IsNotSupported());
  3727. }
  3728. TEST_F(DBTest, FIFOCompactionWithTTLTest) {
  3729. Options options;
  3730. options.compaction_style = kCompactionStyleFIFO;
  3731. options.write_buffer_size = 10 << 10; // 10KB
  3732. options.arena_block_size = 4096;
  3733. options.compression = kNoCompression;
  3734. options.create_if_missing = true;
  3735. env_->SetMockSleep();
  3736. options.env = env_;
  3737. // Test to make sure that all files with expired ttl are deleted on next
  3738. // manual compaction.
  3739. {
  3740. // NOTE: Presumed unnecessary and removed: resetting mock time in env
  3741. options.compaction_options_fifo.max_table_files_size = 150 << 10; // 150KB
  3742. options.compaction_options_fifo.allow_compaction = false;
  3743. options.ttl = 1 * 60 * 60; // 1 hour
  3744. options = CurrentOptions(options);
  3745. DestroyAndReopen(options);
  3746. Random rnd(301);
  3747. for (int i = 0; i < 10; i++) {
  3748. // Generate and flush a file about 10KB.
  3749. for (int j = 0; j < 10; j++) {
  3750. ASSERT_OK(Put(std::to_string(i * 20 + j), rnd.RandomString(980)));
  3751. }
  3752. ASSERT_OK(Flush());
  3753. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  3754. }
  3755. ASSERT_EQ(NumTableFilesAtLevel(0), 10);
  3756. // Sleep for 2 hours -- which is much greater than TTL.
  3757. env_->MockSleepForSeconds(2 * 60 * 60);
  3758. // Since no flushes and compactions have run, the db should still be in
  3759. // the same state even after considerable time has passed.
  3760. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  3761. ASSERT_EQ(NumTableFilesAtLevel(0), 10);
  3762. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  3763. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  3764. }
  3765. // Test to make sure that all files with expired ttl are deleted on next
  3766. // automatic compaction.
  3767. {
  3768. options.compaction_options_fifo.max_table_files_size = 150 << 10; // 150KB
  3769. options.compaction_options_fifo.allow_compaction = false;
  3770. options.ttl = 1 * 60 * 60; // 1 hour
  3771. options = CurrentOptions(options);
  3772. DestroyAndReopen(options);
  3773. Random rnd(301);
  3774. for (int i = 0; i < 10; i++) {
  3775. // Generate and flush a file about 10KB.
  3776. for (int j = 0; j < 10; j++) {
  3777. ASSERT_OK(Put(std::to_string(i * 20 + j), rnd.RandomString(980)));
  3778. }
  3779. ASSERT_OK(Flush());
  3780. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  3781. }
  3782. ASSERT_EQ(NumTableFilesAtLevel(0), 10);
  3783. // Sleep for 2 hours -- which is much greater than TTL.
  3784. env_->MockSleepForSeconds(2 * 60 * 60);
  3785. // Just to make sure that we are in the same state even after sleeping.
  3786. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  3787. ASSERT_EQ(NumTableFilesAtLevel(0), 10);
  3788. // Create 1 more file to trigger TTL compaction. The old files are dropped.
  3789. for (int i = 0; i < 1; i++) {
  3790. for (int j = 0; j < 10; j++) {
  3791. ASSERT_OK(Put(std::to_string(i * 20 + j), rnd.RandomString(980)));
  3792. }
  3793. ASSERT_OK(Flush());
  3794. }
  3795. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  3796. // Only the new 10 files remain.
  3797. ASSERT_EQ(NumTableFilesAtLevel(0), 1);
  3798. ASSERT_LE(SizeAtLevel(0),
  3799. options.compaction_options_fifo.max_table_files_size);
  3800. }
  3801. // Test that shows the fall back to size-based FIFO compaction if TTL-based
  3802. // deletion doesn't move the total size to be less than max_table_files_size.
  3803. {
  3804. options.write_buffer_size = 10 << 10; // 10KB
  3805. options.compaction_options_fifo.max_table_files_size = 150 << 10; // 150KB
  3806. options.compaction_options_fifo.allow_compaction = false;
  3807. options.ttl = 1 * 60 * 60; // 1 hour
  3808. options = CurrentOptions(options);
  3809. DestroyAndReopen(options);
  3810. Random rnd(301);
  3811. for (int i = 0; i < 3; i++) {
  3812. // Generate and flush a file about 10KB.
  3813. for (int j = 0; j < 10; j++) {
  3814. ASSERT_OK(Put(std::to_string(i * 20 + j), rnd.RandomString(980)));
  3815. }
  3816. ASSERT_OK(Flush());
  3817. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  3818. }
  3819. ASSERT_EQ(NumTableFilesAtLevel(0), 3);
  3820. // Sleep for 2 hours -- which is much greater than TTL.
  3821. env_->MockSleepForSeconds(2 * 60 * 60);
  3822. // Just to make sure that we are in the same state even after sleeping.
  3823. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  3824. ASSERT_EQ(NumTableFilesAtLevel(0), 3);
  3825. for (int i = 0; i < 5; i++) {
  3826. for (int j = 0; j < 140; j++) {
  3827. ASSERT_OK(Put(std::to_string(i * 20 + j), rnd.RandomString(980)));
  3828. }
  3829. ASSERT_OK(Flush());
  3830. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  3831. }
  3832. // Size limit is still guaranteed.
  3833. ASSERT_LE(SizeAtLevel(0),
  3834. options.compaction_options_fifo.max_table_files_size);
  3835. }
  3836. // Test with TTL + Intra-L0 compactions.
  3837. {
  3838. options.compaction_options_fifo.max_table_files_size = 150 << 10; // 150KB
  3839. options.compaction_options_fifo.allow_compaction = true;
  3840. options.ttl = 1 * 60 * 60; // 1 hour
  3841. options.level0_file_num_compaction_trigger = 6;
  3842. options = CurrentOptions(options);
  3843. DestroyAndReopen(options);
  3844. Random rnd(301);
  3845. for (int i = 0; i < 10; i++) {
  3846. // Generate and flush a file about 10KB.
  3847. for (int j = 0; j < 10; j++) {
  3848. ASSERT_OK(Put(std::to_string(i * 20 + j), rnd.RandomString(980)));
  3849. }
  3850. ASSERT_OK(Flush());
  3851. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  3852. }
  3853. // With Intra-L0 compaction, out of 10 files, 6 files will be compacted to 1
  3854. // (due to level0_file_num_compaction_trigger = 6).
  3855. // So total files = 1 + remaining 4 = 5.
  3856. ASSERT_EQ(NumTableFilesAtLevel(0), 5);
  3857. // Sleep for 2 hours -- which is much greater than TTL.
  3858. env_->MockSleepForSeconds(2 * 60 * 60);
  3859. // Just to make sure that we are in the same state even after sleeping.
  3860. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  3861. ASSERT_EQ(NumTableFilesAtLevel(0), 5);
  3862. // Create 10 more files. The old 5 files are dropped as their ttl expired.
  3863. for (int i = 0; i < 10; i++) {
  3864. for (int j = 0; j < 10; j++) {
  3865. ASSERT_OK(Put(std::to_string(i * 20 + j), rnd.RandomString(980)));
  3866. }
  3867. ASSERT_OK(Flush());
  3868. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  3869. }
  3870. ASSERT_EQ(NumTableFilesAtLevel(0), 5);
  3871. ASSERT_LE(SizeAtLevel(0),
  3872. options.compaction_options_fifo.max_table_files_size);
  3873. }
  3874. // Test with large TTL + Intra-L0 compactions.
  3875. // Files dropped based on size, as ttl doesn't kick in.
  3876. {
  3877. options.write_buffer_size = 20 << 10; // 20K
  3878. options.compaction_options_fifo.max_table_files_size = 1500 << 10; // 1.5MB
  3879. options.compaction_options_fifo.allow_compaction = true;
  3880. options.ttl = 1 * 60 * 60; // 1 hour
  3881. options.level0_file_num_compaction_trigger = 6;
  3882. options = CurrentOptions(options);
  3883. DestroyAndReopen(options);
  3884. Random rnd(301);
  3885. for (int i = 0; i < 60; i++) {
  3886. // Generate and flush a file about 20KB.
  3887. for (int j = 0; j < 20; j++) {
  3888. ASSERT_OK(Put(std::to_string(i * 20 + j), rnd.RandomString(980)));
  3889. }
  3890. ASSERT_OK(Flush());
  3891. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  3892. }
  3893. // It should be compacted to 10 files.
  3894. ASSERT_EQ(NumTableFilesAtLevel(0), 10);
  3895. for (int i = 0; i < 60; i++) {
  3896. // Generate and flush a file about 20KB.
  3897. for (int j = 0; j < 20; j++) {
  3898. ASSERT_OK(
  3899. Put(std::to_string(i * 20 + j + 2000), rnd.RandomString(980)));
  3900. }
  3901. ASSERT_OK(Flush());
  3902. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  3903. }
  3904. // It should be compacted to no more than 20 files.
  3905. ASSERT_GT(NumTableFilesAtLevel(0), 10);
  3906. ASSERT_LT(NumTableFilesAtLevel(0), 18);
  3907. // Size limit is still guaranteed.
  3908. ASSERT_LE(SizeAtLevel(0),
  3909. options.compaction_options_fifo.max_table_files_size);
  3910. }
  3911. }
  3912. /*
  3913. * This test is not reliable enough as it heavily depends on disk behavior.
  3914. * Disable as it is flaky.
  3915. */
  3916. TEST_F(DBTest, DISABLED_RateLimitingTest) {
  3917. Options options = CurrentOptions();
  3918. options.write_buffer_size = 1 << 20; // 1MB
  3919. options.level0_file_num_compaction_trigger = 2;
  3920. options.target_file_size_base = 1 << 20; // 1MB
  3921. options.max_bytes_for_level_base = 4 << 20; // 4MB
  3922. options.max_bytes_for_level_multiplier = 4;
  3923. options.compression = kNoCompression;
  3924. options.create_if_missing = true;
  3925. options.env = env_;
  3926. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  3927. options.IncreaseParallelism(4);
  3928. DestroyAndReopen(options);
  3929. WriteOptions wo;
  3930. wo.disableWAL = true;
  3931. // # no rate limiting
  3932. Random rnd(301);
  3933. uint64_t start = env_->NowMicros();
  3934. // Write ~96M data
  3935. for (int64_t i = 0; i < (96 << 10); ++i) {
  3936. ASSERT_OK(Put(rnd.RandomString(32), rnd.RandomString((1 << 10) + 1), wo));
  3937. }
  3938. uint64_t elapsed = env_->NowMicros() - start;
  3939. double raw_rate = env_->bytes_written_ * 1000000.0 / elapsed;
  3940. uint64_t rate_limiter_drains =
  3941. TestGetTickerCount(options, NUMBER_RATE_LIMITER_DRAINS);
  3942. ASSERT_EQ(0, rate_limiter_drains);
  3943. Close();
  3944. // # rate limiting with 0.7 x threshold
  3945. options.rate_limiter.reset(
  3946. NewGenericRateLimiter(static_cast<int64_t>(0.7 * raw_rate)));
  3947. env_->bytes_written_ = 0;
  3948. DestroyAndReopen(options);
  3949. start = env_->NowMicros();
  3950. // Write ~96M data
  3951. for (int64_t i = 0; i < (96 << 10); ++i) {
  3952. ASSERT_OK(Put(rnd.RandomString(32), rnd.RandomString((1 << 10) + 1), wo));
  3953. }
  3954. rate_limiter_drains =
  3955. TestGetTickerCount(options, NUMBER_RATE_LIMITER_DRAINS) -
  3956. rate_limiter_drains;
  3957. elapsed = env_->NowMicros() - start;
  3958. Close();
  3959. ASSERT_EQ(options.rate_limiter->GetTotalBytesThrough(), env_->bytes_written_);
  3960. // Most intervals should've been drained (interval time is 100ms, elapsed is
  3961. // micros)
  3962. ASSERT_GT(rate_limiter_drains, 0);
  3963. ASSERT_LE(rate_limiter_drains, elapsed / 100000 + 1);
  3964. double ratio = env_->bytes_written_ * 1000000 / elapsed / raw_rate;
  3965. fprintf(stderr, "write rate ratio = %.2lf, expected 0.7\n", ratio);
  3966. ASSERT_TRUE(ratio < 0.8);
  3967. // # rate limiting with half of the raw_rate
  3968. options.rate_limiter.reset(
  3969. NewGenericRateLimiter(static_cast<int64_t>(raw_rate / 2)));
  3970. env_->bytes_written_ = 0;
  3971. DestroyAndReopen(options);
  3972. start = env_->NowMicros();
  3973. // Write ~96M data
  3974. for (int64_t i = 0; i < (96 << 10); ++i) {
  3975. ASSERT_OK(Put(rnd.RandomString(32), rnd.RandomString((1 << 10) + 1), wo));
  3976. }
  3977. elapsed = env_->NowMicros() - start;
  3978. rate_limiter_drains =
  3979. TestGetTickerCount(options, NUMBER_RATE_LIMITER_DRAINS) -
  3980. rate_limiter_drains;
  3981. Close();
  3982. ASSERT_EQ(options.rate_limiter->GetTotalBytesThrough(), env_->bytes_written_);
  3983. // Most intervals should've been drained (interval time is 100ms, elapsed is
  3984. // micros)
  3985. ASSERT_GT(rate_limiter_drains, elapsed / 100000 / 2);
  3986. ASSERT_LE(rate_limiter_drains, elapsed / 100000 + 1);
  3987. ratio = env_->bytes_written_ * 1000000 / elapsed / raw_rate;
  3988. fprintf(stderr, "write rate ratio = %.2lf, expected 0.5\n", ratio);
  3989. ASSERT_LT(ratio, 0.6);
  3990. }
  3991. // This is a mocked customed rate limiter without implementing optional APIs
  3992. // (e.g, RateLimiter::GetTotalPendingRequests())
  3993. class MockedRateLimiterWithNoOptionalAPIImpl : public RateLimiter {
  3994. public:
  3995. MockedRateLimiterWithNoOptionalAPIImpl() = default;
  3996. ~MockedRateLimiterWithNoOptionalAPIImpl() override = default;
  3997. void SetBytesPerSecond(int64_t bytes_per_second) override {
  3998. (void)bytes_per_second;
  3999. }
  4000. using RateLimiter::Request;
  4001. void Request(const int64_t bytes, const Env::IOPriority pri,
  4002. Statistics* stats) override {
  4003. (void)bytes;
  4004. (void)pri;
  4005. (void)stats;
  4006. }
  4007. int64_t GetSingleBurstBytes() const override { return 200; }
  4008. int64_t GetTotalBytesThrough(
  4009. const Env::IOPriority pri = Env::IO_TOTAL) const override {
  4010. (void)pri;
  4011. return 0;
  4012. }
  4013. int64_t GetTotalRequests(
  4014. const Env::IOPriority pri = Env::IO_TOTAL) const override {
  4015. (void)pri;
  4016. return 0;
  4017. }
  4018. int64_t GetBytesPerSecond() const override { return 0; }
  4019. };
  4020. // To test that customed rate limiter not implementing optional APIs (e.g,
  4021. // RateLimiter::GetTotalPendingRequests()) works fine with RocksDB basic
  4022. // operations (e.g, Put, Get, Flush)
  4023. TEST_F(DBTest, CustomedRateLimiterWithNoOptionalAPIImplTest) {
  4024. Options options = CurrentOptions();
  4025. options.rate_limiter.reset(new MockedRateLimiterWithNoOptionalAPIImpl());
  4026. DestroyAndReopen(options);
  4027. ASSERT_OK(Put("abc", "def"));
  4028. ASSERT_EQ(Get("abc"), "def");
  4029. ASSERT_OK(Flush());
  4030. ASSERT_EQ(Get("abc"), "def");
  4031. }
  4032. TEST_F(DBTest, TableOptionsSanitizeTest) {
  4033. Options options = CurrentOptions();
  4034. options.create_if_missing = true;
  4035. DestroyAndReopen(options);
  4036. ASSERT_EQ(db_->GetOptions().allow_mmap_reads, false);
  4037. options.table_factory.reset(NewPlainTableFactory());
  4038. options.prefix_extractor.reset(NewNoopTransform());
  4039. Destroy(options);
  4040. ASSERT_TRUE(!TryReopen(options).IsNotSupported());
  4041. // Test for check of prefix_extractor when hash index is used for
  4042. // block-based table
  4043. BlockBasedTableOptions to;
  4044. to.index_type = BlockBasedTableOptions::kHashSearch;
  4045. options = CurrentOptions();
  4046. options.create_if_missing = true;
  4047. options.table_factory.reset(NewBlockBasedTableFactory(to));
  4048. ASSERT_TRUE(TryReopen(options).IsInvalidArgument());
  4049. options.prefix_extractor.reset(NewFixedPrefixTransform(1));
  4050. ASSERT_OK(TryReopen(options));
  4051. }
  4052. TEST_F(DBTest, ConcurrentMemtableNotSupported) {
  4053. Options options = CurrentOptions();
  4054. options.allow_concurrent_memtable_write = true;
  4055. options.soft_pending_compaction_bytes_limit = 0;
  4056. options.hard_pending_compaction_bytes_limit = 100;
  4057. options.create_if_missing = true;
  4058. Close();
  4059. ASSERT_OK(DestroyDB(dbname_, options));
  4060. options.memtable_factory.reset(NewHashLinkListRepFactory(4, 0, 3, true, 4));
  4061. ASSERT_NOK(TryReopen(options));
  4062. options.memtable_factory.reset(new SkipListFactory);
  4063. ASSERT_OK(TryReopen(options));
  4064. ColumnFamilyOptions cf_options(options);
  4065. cf_options.memtable_factory.reset(
  4066. NewHashLinkListRepFactory(4, 0, 3, true, 4));
  4067. ColumnFamilyHandle* handle;
  4068. ASSERT_NOK(db_->CreateColumnFamily(cf_options, "name", &handle));
  4069. }
  4070. TEST_F(DBTest, SanitizeNumThreads) {
  4071. for (int attempt = 0; attempt < 2; attempt++) {
  4072. const size_t kTotalTasks = 8;
  4073. test::SleepingBackgroundTask sleeping_tasks[kTotalTasks];
  4074. Options options = CurrentOptions();
  4075. if (attempt == 0) {
  4076. options.max_background_compactions = 3;
  4077. options.max_background_flushes = 2;
  4078. }
  4079. options.create_if_missing = true;
  4080. DestroyAndReopen(options);
  4081. for (size_t i = 0; i < kTotalTasks; i++) {
  4082. // Insert 5 tasks to low priority queue and 5 tasks to high priority queue
  4083. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask,
  4084. &sleeping_tasks[i],
  4085. (i < 4) ? Env::Priority::LOW : Env::Priority::HIGH);
  4086. }
  4087. // Wait until 10s for they are scheduled.
  4088. for (int i = 0; i < 10000; i++) {
  4089. if (options.env->GetThreadPoolQueueLen(Env::Priority::LOW) <= 1 &&
  4090. options.env->GetThreadPoolQueueLen(Env::Priority::HIGH) <= 2) {
  4091. break;
  4092. }
  4093. env_->SleepForMicroseconds(1000);
  4094. }
  4095. // pool size 3, total task 4. Queue size should be 1.
  4096. ASSERT_EQ(1U, options.env->GetThreadPoolQueueLen(Env::Priority::LOW));
  4097. // pool size 2, total task 4. Queue size should be 2.
  4098. ASSERT_EQ(2U, options.env->GetThreadPoolQueueLen(Env::Priority::HIGH));
  4099. for (size_t i = 0; i < kTotalTasks; i++) {
  4100. sleeping_tasks[i].WakeUp();
  4101. sleeping_tasks[i].WaitUntilDone();
  4102. }
  4103. ASSERT_OK(Put("abc", "def"));
  4104. ASSERT_EQ("def", Get("abc"));
  4105. ASSERT_OK(Flush());
  4106. ASSERT_EQ("def", Get("abc"));
  4107. }
  4108. }
  4109. TEST_F(DBTest, WriteSingleThreadEntry) {
  4110. std::vector<port::Thread> threads;
  4111. dbfull()->TEST_LockMutex();
  4112. auto w = dbfull()->TEST_BeginWrite();
  4113. threads.emplace_back([&] { ASSERT_OK(Put("a", "b")); });
  4114. env_->SleepForMicroseconds(10000);
  4115. threads.emplace_back([&] { ASSERT_OK(Flush()); });
  4116. env_->SleepForMicroseconds(10000);
  4117. dbfull()->TEST_UnlockMutex();
  4118. dbfull()->TEST_LockMutex();
  4119. dbfull()->TEST_EndWrite(w);
  4120. dbfull()->TEST_UnlockMutex();
  4121. for (auto& t : threads) {
  4122. t.join();
  4123. }
  4124. }
  4125. TEST_F(DBTest, ConcurrentFlushWAL) {
  4126. const size_t cnt = 100;
  4127. Options options;
  4128. options.env = env_;
  4129. WriteOptions wopt;
  4130. ReadOptions ropt;
  4131. for (bool two_write_queues : {false, true}) {
  4132. for (bool manual_wal_flush : {false, true}) {
  4133. options.two_write_queues = two_write_queues;
  4134. options.manual_wal_flush = manual_wal_flush;
  4135. options.create_if_missing = true;
  4136. DestroyAndReopen(options);
  4137. std::vector<port::Thread> threads;
  4138. threads.emplace_back([&] {
  4139. for (size_t i = 0; i < cnt; i++) {
  4140. auto istr = std::to_string(i);
  4141. ASSERT_OK(db_->Put(wopt, db_->DefaultColumnFamily(), "a" + istr,
  4142. "b" + istr));
  4143. }
  4144. });
  4145. if (two_write_queues) {
  4146. threads.emplace_back([&] {
  4147. for (size_t i = cnt; i < 2 * cnt; i++) {
  4148. auto istr = std::to_string(i);
  4149. WriteBatch batch(0 /* reserved_bytes */, 0 /* max_bytes */,
  4150. wopt.protection_bytes_per_key,
  4151. 0 /* default_cf_ts_sz */);
  4152. ASSERT_OK(batch.Put("a" + istr, "b" + istr));
  4153. ASSERT_OK(
  4154. dbfull()->WriteImpl(wopt, &batch, nullptr, nullptr, 0, true));
  4155. }
  4156. });
  4157. }
  4158. threads.emplace_back([&] {
  4159. for (size_t i = 0; i < cnt * 100; i++) { // FlushWAL is faster than Put
  4160. ASSERT_OK(db_->FlushWAL(false));
  4161. }
  4162. });
  4163. for (auto& t : threads) {
  4164. t.join();
  4165. }
  4166. options.create_if_missing = false;
  4167. // Recover from the wal and make sure that it is not corrupted
  4168. Reopen(options);
  4169. for (size_t i = 0; i < cnt; i++) {
  4170. PinnableSlice pval;
  4171. auto istr = std::to_string(i);
  4172. ASSERT_OK(
  4173. db_->Get(ropt, db_->DefaultColumnFamily(), "a" + istr, &pval));
  4174. ASSERT_TRUE(pval == ("b" + istr));
  4175. }
  4176. }
  4177. }
  4178. }
  4179. // This test failure will be caught with a probability
  4180. TEST_F(DBTest, ManualFlushWalAndWriteRace) {
  4181. Options options;
  4182. options.env = env_;
  4183. options.manual_wal_flush = true;
  4184. options.create_if_missing = true;
  4185. DestroyAndReopen(options);
  4186. WriteOptions wopts;
  4187. wopts.sync = true;
  4188. port::Thread writeThread([&]() {
  4189. for (int i = 0; i < 100; i++) {
  4190. auto istr = std::to_string(i);
  4191. ASSERT_OK(dbfull()->Put(wopts, "key_" + istr, "value_" + istr));
  4192. }
  4193. });
  4194. port::Thread flushThread([&]() {
  4195. for (int i = 0; i < 100; i++) {
  4196. ASSERT_OK(dbfull()->FlushWAL(false));
  4197. }
  4198. });
  4199. writeThread.join();
  4200. flushThread.join();
  4201. ASSERT_OK(dbfull()->Put(wopts, "foo1", "value1"));
  4202. ASSERT_OK(dbfull()->Put(wopts, "foo2", "value2"));
  4203. Reopen(options);
  4204. ASSERT_EQ("value1", Get("foo1"));
  4205. ASSERT_EQ("value2", Get("foo2"));
  4206. }
  4207. TEST_F(DBTest, DynamicMemtableOptions) {
  4208. const uint64_t k64KB = 1 << 16;
  4209. const uint64_t k128KB = 1 << 17;
  4210. const uint64_t k5KB = 5 * 1024;
  4211. Options options;
  4212. options.env = env_;
  4213. options.create_if_missing = true;
  4214. options.compression = kNoCompression;
  4215. options.max_background_compactions = 1;
  4216. options.write_buffer_size = k64KB;
  4217. options.arena_block_size = 16 * 1024;
  4218. options.max_write_buffer_number = 2;
  4219. // Don't trigger compact/slowdown/stop
  4220. options.level0_file_num_compaction_trigger = 1024;
  4221. options.level0_slowdown_writes_trigger = 1024;
  4222. options.level0_stop_writes_trigger = 1024;
  4223. DestroyAndReopen(options);
  4224. auto gen_l0_kb = [this](int size) {
  4225. const int kNumPutsBeforeWaitForFlush = 64;
  4226. Random rnd(301);
  4227. for (int i = 0; i < size; i++) {
  4228. ASSERT_OK(Put(Key(i), rnd.RandomString(1024)));
  4229. // The following condition prevents a race condition between flush jobs
  4230. // acquiring work and this thread filling up multiple memtables. Without
  4231. // this, the flush might produce less files than expected because
  4232. // multiple memtables are flushed into a single L0 file. This race
  4233. // condition affects assertion (A).
  4234. if (i % kNumPutsBeforeWaitForFlush == kNumPutsBeforeWaitForFlush - 1) {
  4235. ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
  4236. }
  4237. }
  4238. ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
  4239. };
  4240. // Test write_buffer_size
  4241. gen_l0_kb(64);
  4242. ASSERT_EQ(NumTableFilesAtLevel(0), 1);
  4243. ASSERT_LT(SizeAtLevel(0), k64KB + k5KB);
  4244. ASSERT_GT(SizeAtLevel(0), k64KB - k5KB * 2);
  4245. // Clean up L0
  4246. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  4247. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  4248. // Increase buffer size
  4249. ASSERT_OK(dbfull()->SetOptions({
  4250. {"write_buffer_size", "131072"},
  4251. }));
  4252. // The existing memtable inflated 64KB->128KB when we invoked SetOptions().
  4253. // Write 192KB, we should have a 128KB L0 file and a memtable with 64KB data.
  4254. gen_l0_kb(192);
  4255. ASSERT_EQ(NumTableFilesAtLevel(0), 1); // (A)
  4256. ASSERT_LT(SizeAtLevel(0), k128KB + 2 * k5KB);
  4257. ASSERT_GT(SizeAtLevel(0), k128KB - 4 * k5KB);
  4258. // Decrease buffer size below current usage
  4259. ASSERT_OK(dbfull()->SetOptions({
  4260. {"write_buffer_size", "65536"},
  4261. }));
  4262. // The existing memtable became eligible for flush when we reduced its
  4263. // capacity to 64KB. Two keys need to be added to trigger flush: first causes
  4264. // memtable to be marked full, second schedules the flush. Then we should have
  4265. // a 128KB L0 file, a 64KB L0 file, and a memtable with just one key.
  4266. gen_l0_kb(2);
  4267. ASSERT_EQ(NumTableFilesAtLevel(0), 2);
  4268. ASSERT_LT(SizeAtLevel(0), k128KB + k64KB + 2 * k5KB);
  4269. ASSERT_GT(SizeAtLevel(0), k128KB + k64KB - 4 * k5KB);
  4270. // Test max_write_buffer_number
  4271. // Block compaction thread, which will also block the flushes because
  4272. // max_background_flushes == 0, so flushes are getting executed by the
  4273. // compaction thread
  4274. env_->SetBackgroundThreads(1, Env::LOW);
  4275. test::SleepingBackgroundTask sleeping_task_low;
  4276. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &sleeping_task_low,
  4277. Env::Priority::LOW);
  4278. // Start from scratch and disable compaction/flush. Flush can only happen
  4279. // during compaction but trigger is pretty high
  4280. options.disable_auto_compactions = true;
  4281. DestroyAndReopen(options);
  4282. env_->SetBackgroundThreads(0, Env::HIGH);
  4283. // Put until writes are stopped, bounded by 256 puts. We should see stop at
  4284. // ~128KB
  4285. int count = 0;
  4286. Random rnd(301);
  4287. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  4288. "DBImpl::DelayWrite:Wait",
  4289. [&](void* /*arg*/) { sleeping_task_low.WakeUp(); });
  4290. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  4291. while (!sleeping_task_low.WokenUp() && count < 256) {
  4292. ASSERT_OK(Put(Key(count), rnd.RandomString(1024), WriteOptions()));
  4293. count++;
  4294. }
  4295. ASSERT_GT(static_cast<double>(count), 128 * 0.8);
  4296. ASSERT_LT(static_cast<double>(count), 128 * 1.2);
  4297. sleeping_task_low.WaitUntilDone();
  4298. // Increase
  4299. ASSERT_OK(dbfull()->SetOptions({
  4300. {"max_write_buffer_number", "8"},
  4301. }));
  4302. // Clean up memtable and L0
  4303. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  4304. sleeping_task_low.Reset();
  4305. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &sleeping_task_low,
  4306. Env::Priority::LOW);
  4307. count = 0;
  4308. while (!sleeping_task_low.WokenUp() && count < 1024) {
  4309. ASSERT_OK(Put(Key(count), rnd.RandomString(1024), WriteOptions()));
  4310. count++;
  4311. }
  4312. // Windows fails this test. Will tune in the future and figure out
  4313. // approp number
  4314. #ifndef OS_WIN
  4315. ASSERT_GT(static_cast<double>(count), 512 * 0.8);
  4316. ASSERT_LT(static_cast<double>(count), 512 * 1.2);
  4317. #endif
  4318. sleeping_task_low.WaitUntilDone();
  4319. // Decrease
  4320. ASSERT_OK(dbfull()->SetOptions({
  4321. {"max_write_buffer_number", "4"},
  4322. }));
  4323. // Clean up memtable and L0
  4324. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  4325. sleeping_task_low.Reset();
  4326. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &sleeping_task_low,
  4327. Env::Priority::LOW);
  4328. count = 0;
  4329. while (!sleeping_task_low.WokenUp() && count < 1024) {
  4330. ASSERT_OK(Put(Key(count), rnd.RandomString(1024), WriteOptions()));
  4331. count++;
  4332. }
  4333. // Windows fails this test. Will tune in the future and figure out
  4334. // approp number
  4335. #ifndef OS_WIN
  4336. ASSERT_GT(static_cast<double>(count), 256 * 0.8);
  4337. ASSERT_LT(static_cast<double>(count), 266 * 1.2);
  4338. #endif
  4339. sleeping_task_low.WaitUntilDone();
  4340. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  4341. }
  4342. #ifdef ROCKSDB_USING_THREAD_STATUS
  4343. namespace {
  4344. bool VerifyOperationCount(Env* env, ThreadStatus::OperationType op_type,
  4345. int expected_count) {
  4346. int op_count = 0;
  4347. std::vector<ThreadStatus> thread_list;
  4348. EXPECT_OK(env->GetThreadList(&thread_list));
  4349. for (const auto& thread : thread_list) {
  4350. if (thread.operation_type == op_type) {
  4351. op_count++;
  4352. }
  4353. }
  4354. if (op_count != expected_count) {
  4355. fprintf(stderr, "op_count: %d, expected_count %d\n", op_count,
  4356. expected_count);
  4357. for (const auto& thread : thread_list) {
  4358. fprintf(stderr, "thread id: %" PRIu64 ", thread status: %s, cf_name %s\n",
  4359. thread.thread_id,
  4360. thread.GetOperationName(thread.operation_type).c_str(),
  4361. thread.cf_name.c_str());
  4362. }
  4363. }
  4364. return op_count == expected_count;
  4365. }
  4366. } // anonymous namespace
  4367. TEST_F(DBTest, GetThreadStatus) {
  4368. Options options;
  4369. options.env = env_;
  4370. options.enable_thread_tracking = true;
  4371. ASSERT_OK(TryReopen(options));
  4372. std::vector<ThreadStatus> thread_list;
  4373. Status s = env_->GetThreadList(&thread_list);
  4374. for (int i = 0; i < 2; ++i) {
  4375. // repeat the test with differet number of high / low priority threads
  4376. const int kTestCount = 3;
  4377. const unsigned int kHighPriCounts[kTestCount] = {3, 2, 5};
  4378. const unsigned int kLowPriCounts[kTestCount] = {10, 15, 3};
  4379. const unsigned int kBottomPriCounts[kTestCount] = {2, 1, 4};
  4380. for (int test = 0; test < kTestCount; ++test) {
  4381. // Change the number of threads in high / low priority pool.
  4382. env_->SetBackgroundThreads(kHighPriCounts[test], Env::HIGH);
  4383. env_->SetBackgroundThreads(kLowPriCounts[test], Env::LOW);
  4384. env_->SetBackgroundThreads(kBottomPriCounts[test], Env::BOTTOM);
  4385. // Wait to ensure the all threads has been registered
  4386. unsigned int thread_type_counts[ThreadStatus::NUM_THREAD_TYPES];
  4387. // TODO(ajkr): it'd be better if SetBackgroundThreads returned only after
  4388. // all threads have been registered.
  4389. // Try up to 60 seconds.
  4390. for (int num_try = 0; num_try < 60000; num_try++) {
  4391. env_->SleepForMicroseconds(1000);
  4392. thread_list.clear();
  4393. s = env_->GetThreadList(&thread_list);
  4394. ASSERT_OK(s);
  4395. memset(thread_type_counts, 0, sizeof(thread_type_counts));
  4396. for (const auto& thread : thread_list) {
  4397. ASSERT_LT(thread.thread_type, ThreadStatus::NUM_THREAD_TYPES);
  4398. thread_type_counts[thread.thread_type]++;
  4399. }
  4400. if (thread_type_counts[ThreadStatus::HIGH_PRIORITY] ==
  4401. kHighPriCounts[test] &&
  4402. thread_type_counts[ThreadStatus::LOW_PRIORITY] ==
  4403. kLowPriCounts[test] &&
  4404. thread_type_counts[ThreadStatus::BOTTOM_PRIORITY] ==
  4405. kBottomPriCounts[test]) {
  4406. break;
  4407. }
  4408. }
  4409. // Verify the number of high-priority threads
  4410. ASSERT_EQ(thread_type_counts[ThreadStatus::HIGH_PRIORITY],
  4411. kHighPriCounts[test]);
  4412. // Verify the number of low-priority threads
  4413. ASSERT_EQ(thread_type_counts[ThreadStatus::LOW_PRIORITY],
  4414. kLowPriCounts[test]);
  4415. // Verify the number of bottom-priority threads
  4416. ASSERT_EQ(thread_type_counts[ThreadStatus::BOTTOM_PRIORITY],
  4417. kBottomPriCounts[test]);
  4418. }
  4419. if (i == 0) {
  4420. // repeat the test with multiple column families
  4421. CreateAndReopenWithCF({"pikachu", "about-to-remove"}, options);
  4422. env_->GetThreadStatusUpdater()->TEST_VerifyColumnFamilyInfoMap(handles_,
  4423. true);
  4424. }
  4425. }
  4426. ASSERT_OK(db_->DropColumnFamily(handles_[2]));
  4427. delete handles_[2];
  4428. handles_.erase(handles_.begin() + 2);
  4429. env_->GetThreadStatusUpdater()->TEST_VerifyColumnFamilyInfoMap(handles_,
  4430. true);
  4431. Close();
  4432. env_->GetThreadStatusUpdater()->TEST_VerifyColumnFamilyInfoMap(handles_,
  4433. true);
  4434. }
  4435. TEST_F(DBTest, DisableThreadStatus) {
  4436. Options options;
  4437. options.env = env_;
  4438. options.enable_thread_tracking = false;
  4439. ASSERT_OK(TryReopen(options));
  4440. CreateAndReopenWithCF({"pikachu", "about-to-remove"}, options);
  4441. // Verify non of the column family info exists
  4442. env_->GetThreadStatusUpdater()->TEST_VerifyColumnFamilyInfoMap(handles_,
  4443. false);
  4444. }
  4445. TEST_F(DBTest, ThreadStatusFlush) {
  4446. Options options;
  4447. options.env = env_;
  4448. options.write_buffer_size = 100000; // Small write buffer
  4449. options.enable_thread_tracking = true;
  4450. options = CurrentOptions(options);
  4451. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency({
  4452. {"FlushJob::FlushJob()", "DBTest::ThreadStatusFlush:1"},
  4453. {"DBTest::ThreadStatusFlush:2", "FlushJob::WriteLevel0Table"},
  4454. });
  4455. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  4456. CreateAndReopenWithCF({"pikachu"}, options);
  4457. ASSERT_TRUE(VerifyOperationCount(env_, ThreadStatus::OP_FLUSH, 0));
  4458. ASSERT_OK(Put(1, "foo", "v1"));
  4459. ASSERT_EQ("v1", Get(1, "foo"));
  4460. ASSERT_TRUE(VerifyOperationCount(env_, ThreadStatus::OP_FLUSH, 0));
  4461. uint64_t num_running_flushes = 0;
  4462. ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumRunningFlushes,
  4463. &num_running_flushes));
  4464. ASSERT_EQ(num_running_flushes, 0);
  4465. ASSERT_OK(Put(1, "k1", std::string(100000, 'x'))); // Fill memtable
  4466. ASSERT_OK(Put(1, "k2", std::string(100000, 'y'))); // Trigger flush
  4467. // The first sync point is to make sure there's one flush job
  4468. // running when we perform VerifyOperationCount().
  4469. TEST_SYNC_POINT("DBTest::ThreadStatusFlush:1");
  4470. ASSERT_TRUE(VerifyOperationCount(env_, ThreadStatus::OP_FLUSH, 1));
  4471. ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumRunningFlushes,
  4472. &num_running_flushes));
  4473. ASSERT_EQ(num_running_flushes, 1);
  4474. // This second sync point is to ensure the flush job will not
  4475. // be completed until we already perform VerifyOperationCount().
  4476. TEST_SYNC_POINT("DBTest::ThreadStatusFlush:2");
  4477. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  4478. }
  4479. TEST_P(DBTestWithParam, ThreadStatusSingleCompaction) {
  4480. const int kTestValueSize = 984;
  4481. const int kEntriesPerBuffer = 100;
  4482. Options options;
  4483. options.create_if_missing = true;
  4484. options.compaction_style = kCompactionStyleLevel;
  4485. options.compression = kNoCompression;
  4486. options = CurrentOptions(options);
  4487. options.env = env_;
  4488. options.enable_thread_tracking = true;
  4489. const int kNumL0Files = 4;
  4490. options.level0_file_num_compaction_trigger = kNumL0Files;
  4491. options.max_subcompactions = max_subcompactions_;
  4492. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency({
  4493. {"DBTest::ThreadStatusSingleCompaction:0", "DBImpl::BGWorkCompaction"},
  4494. {"CompactionJob::Run():Start", "DBTest::ThreadStatusSingleCompaction:1"},
  4495. {"DBTest::ThreadStatusSingleCompaction:2", "CompactionJob::Run():End"},
  4496. });
  4497. for (int tests = 0; tests < 2; ++tests) {
  4498. DestroyAndReopen(options);
  4499. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearTrace();
  4500. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  4501. Random rnd(301);
  4502. // The Put Phase.
  4503. for (int file = 0; file < kNumL0Files; ++file) {
  4504. for (int key = 0; key < kEntriesPerBuffer; ++key) {
  4505. ASSERT_OK(Put(std::to_string(key + file * kEntriesPerBuffer),
  4506. rnd.RandomString(kTestValueSize)));
  4507. }
  4508. ASSERT_OK(Flush());
  4509. }
  4510. // This makes sure a compaction won't be scheduled until
  4511. // we have done with the above Put Phase.
  4512. uint64_t num_running_compactions = 0;
  4513. ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumRunningCompactions,
  4514. &num_running_compactions));
  4515. ASSERT_EQ(num_running_compactions, 0);
  4516. TEST_SYNC_POINT("DBTest::ThreadStatusSingleCompaction:0");
  4517. ASSERT_EQ(NumTableFilesAtLevel(0),
  4518. options.level0_file_num_compaction_trigger);
  4519. // This makes sure at least one compaction is running.
  4520. TEST_SYNC_POINT("DBTest::ThreadStatusSingleCompaction:1");
  4521. if (options.enable_thread_tracking) {
  4522. // expecting one single L0 to L1 compaction
  4523. // This test is flaky and fails here.
  4524. bool match = VerifyOperationCount(env_, ThreadStatus::OP_COMPACTION, 1);
  4525. if (!match) {
  4526. ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumRunningCompactions,
  4527. &num_running_compactions));
  4528. fprintf(stderr, "running compaction: %" PRIu64 " lsm state: %s\n",
  4529. num_running_compactions, FilesPerLevel().c_str());
  4530. }
  4531. ASSERT_TRUE(match);
  4532. } else {
  4533. // If thread tracking is not enabled, compaction count should be 0.
  4534. ASSERT_TRUE(VerifyOperationCount(env_, ThreadStatus::OP_COMPACTION, 0));
  4535. }
  4536. ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumRunningCompactions,
  4537. &num_running_compactions));
  4538. ASSERT_EQ(num_running_compactions, 1);
  4539. // TODO(yhchiang): adding assert to verify each compaction stage.
  4540. TEST_SYNC_POINT("DBTest::ThreadStatusSingleCompaction:2");
  4541. // repeat the test with disabling thread tracking.
  4542. options.enable_thread_tracking = false;
  4543. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  4544. }
  4545. }
  4546. TEST_P(DBTestWithParam, PreShutdownManualCompaction) {
  4547. Options options = CurrentOptions();
  4548. options.max_subcompactions = max_subcompactions_;
  4549. CreateAndReopenWithCF({"pikachu"}, options);
  4550. // iter - 0 with 7 levels
  4551. // iter - 1 with 3 levels
  4552. for (int iter = 0; iter < 2; ++iter) {
  4553. MakeTables(3, "p", "q", 1);
  4554. ASSERT_EQ("1,1,1", FilesPerLevel(1));
  4555. // Compaction range falls before files
  4556. Compact(1, "", "c");
  4557. ASSERT_EQ("1,1,1", FilesPerLevel(1));
  4558. // Compaction range falls after files
  4559. Compact(1, "r", "z");
  4560. ASSERT_EQ("1,1,1", FilesPerLevel(1));
  4561. // Compaction range overlaps files
  4562. Compact(1, "p", "q");
  4563. ASSERT_EQ("0,0,1", FilesPerLevel(1));
  4564. // Populate a different range
  4565. MakeTables(3, "c", "e", 1);
  4566. ASSERT_EQ("1,1,2", FilesPerLevel(1));
  4567. // Compact just the new range
  4568. Compact(1, "b", "f");
  4569. ASSERT_EQ("0,0,2", FilesPerLevel(1));
  4570. // Compact all
  4571. MakeTables(1, "a", "z", 1);
  4572. ASSERT_EQ("1,0,2", FilesPerLevel(1));
  4573. CancelAllBackgroundWork(db_);
  4574. ASSERT_TRUE(
  4575. db_->CompactRange(CompactRangeOptions(), handles_[1], nullptr, nullptr)
  4576. .IsShutdownInProgress());
  4577. ASSERT_EQ("1,0,2", FilesPerLevel(1));
  4578. if (iter == 0) {
  4579. options = CurrentOptions();
  4580. options.num_levels = 3;
  4581. options.create_if_missing = true;
  4582. DestroyAndReopen(options);
  4583. CreateAndReopenWithCF({"pikachu"}, options);
  4584. }
  4585. }
  4586. }
  4587. TEST_F(DBTest, PreShutdownFlush) {
  4588. Options options = CurrentOptions();
  4589. CreateAndReopenWithCF({"pikachu"}, options);
  4590. ASSERT_OK(Put(1, "key", "value"));
  4591. CancelAllBackgroundWork(db_);
  4592. Status s =
  4593. db_->CompactRange(CompactRangeOptions(), handles_[1], nullptr, nullptr);
  4594. ASSERT_TRUE(s.IsShutdownInProgress());
  4595. }
  4596. TEST_P(DBTestWithParam, PreShutdownMultipleCompaction) {
  4597. const int kTestKeySize = 16;
  4598. const int kTestValueSize = 984;
  4599. const int kEntrySize = kTestKeySize + kTestValueSize;
  4600. const int kEntriesPerBuffer = 40;
  4601. const int kNumL0Files = 4;
  4602. const int kHighPriCount = 3;
  4603. const int kLowPriCount = 5;
  4604. env_->SetBackgroundThreads(kHighPriCount, Env::HIGH);
  4605. env_->SetBackgroundThreads(kLowPriCount, Env::LOW);
  4606. Options options;
  4607. options.create_if_missing = true;
  4608. options.write_buffer_size = kEntrySize * kEntriesPerBuffer;
  4609. options.compaction_style = kCompactionStyleLevel;
  4610. options.target_file_size_base = options.write_buffer_size;
  4611. options.max_bytes_for_level_base =
  4612. options.target_file_size_base * kNumL0Files;
  4613. options.compression = kNoCompression;
  4614. options = CurrentOptions(options);
  4615. options.env = env_;
  4616. options.enable_thread_tracking = true;
  4617. options.level0_file_num_compaction_trigger = kNumL0Files;
  4618. options.max_bytes_for_level_multiplier = 2;
  4619. options.max_background_compactions = kLowPriCount;
  4620. options.level0_stop_writes_trigger = 1 << 10;
  4621. options.level0_slowdown_writes_trigger = 1 << 10;
  4622. options.max_subcompactions = max_subcompactions_;
  4623. ASSERT_OK(TryReopen(options));
  4624. Random rnd(301);
  4625. std::vector<ThreadStatus> thread_list;
  4626. // Delay both flush and compaction
  4627. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
  4628. {{"FlushJob::FlushJob()", "CompactionJob::Run():Start"},
  4629. {"CompactionJob::Run():Start",
  4630. "DBTest::PreShutdownMultipleCompaction:Preshutdown"},
  4631. {"CompactionJob::Run():Start",
  4632. "DBTest::PreShutdownMultipleCompaction:VerifyCompaction"},
  4633. {"DBTest::PreShutdownMultipleCompaction:Preshutdown",
  4634. "CompactionJob::Run():End"},
  4635. {"CompactionJob::Run():End",
  4636. "DBTest::PreShutdownMultipleCompaction:VerifyPreshutdown"}});
  4637. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  4638. // Make rocksdb busy
  4639. int key = 0;
  4640. // check how many threads are doing compaction using GetThreadList
  4641. int operation_count[ThreadStatus::NUM_OP_TYPES] = {0};
  4642. for (int file = 0; file < 16 * kNumL0Files; ++file) {
  4643. for (int k = 0; k < kEntriesPerBuffer; ++k) {
  4644. ASSERT_OK(Put(std::to_string(key++), rnd.RandomString(kTestValueSize)));
  4645. }
  4646. ASSERT_OK(env_->GetThreadList(&thread_list));
  4647. for (const auto& thread : thread_list) {
  4648. operation_count[thread.operation_type]++;
  4649. }
  4650. // Speed up the test
  4651. if (operation_count[ThreadStatus::OP_FLUSH] > 1 &&
  4652. operation_count[ThreadStatus::OP_COMPACTION] >
  4653. 0.6 * options.max_background_compactions) {
  4654. break;
  4655. }
  4656. if (file == 15 * kNumL0Files) {
  4657. TEST_SYNC_POINT("DBTest::PreShutdownMultipleCompaction:Preshutdown");
  4658. }
  4659. }
  4660. TEST_SYNC_POINT("DBTest::PreShutdownMultipleCompaction:Preshutdown");
  4661. ASSERT_GE(operation_count[ThreadStatus::OP_COMPACTION], 1);
  4662. CancelAllBackgroundWork(db_);
  4663. TEST_SYNC_POINT("DBTest::PreShutdownMultipleCompaction:VerifyPreshutdown");
  4664. ASSERT_OK(dbfull()->TEST_WaitForBackgroundWork());
  4665. // Record the number of compactions at a time.
  4666. for (int i = 0; i < ThreadStatus::NUM_OP_TYPES; ++i) {
  4667. operation_count[i] = 0;
  4668. }
  4669. ASSERT_OK(env_->GetThreadList(&thread_list));
  4670. for (const auto& thread : thread_list) {
  4671. operation_count[thread.operation_type]++;
  4672. }
  4673. ASSERT_EQ(operation_count[ThreadStatus::OP_COMPACTION], 0);
  4674. }
  4675. TEST_P(DBTestWithParam, PreShutdownCompactionMiddle) {
  4676. const int kTestKeySize = 16;
  4677. const int kTestValueSize = 984;
  4678. const int kEntrySize = kTestKeySize + kTestValueSize;
  4679. const int kEntriesPerBuffer = 40;
  4680. const int kNumL0Files = 4;
  4681. const int kHighPriCount = 3;
  4682. const int kLowPriCount = 5;
  4683. env_->SetBackgroundThreads(kHighPriCount, Env::HIGH);
  4684. env_->SetBackgroundThreads(kLowPriCount, Env::LOW);
  4685. Options options;
  4686. options.create_if_missing = true;
  4687. options.write_buffer_size = kEntrySize * kEntriesPerBuffer;
  4688. options.compaction_style = kCompactionStyleLevel;
  4689. options.target_file_size_base = options.write_buffer_size;
  4690. options.max_bytes_for_level_base =
  4691. options.target_file_size_base * kNumL0Files;
  4692. options.compression = kNoCompression;
  4693. options = CurrentOptions(options);
  4694. options.env = env_;
  4695. options.enable_thread_tracking = true;
  4696. options.level0_file_num_compaction_trigger = kNumL0Files;
  4697. options.max_bytes_for_level_multiplier = 2;
  4698. options.max_background_compactions = kLowPriCount;
  4699. options.level0_stop_writes_trigger = 1 << 10;
  4700. options.level0_slowdown_writes_trigger = 1 << 10;
  4701. options.max_subcompactions = max_subcompactions_;
  4702. ASSERT_OK(TryReopen(options));
  4703. Random rnd(301);
  4704. std::vector<ThreadStatus> thread_list;
  4705. // Delay both flush and compaction
  4706. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
  4707. {{"DBTest::PreShutdownCompactionMiddle:Preshutdown",
  4708. "CompactionJob::Run():Inprogress"},
  4709. {"CompactionJob::Run():Start",
  4710. "DBTest::PreShutdownCompactionMiddle:VerifyCompaction"},
  4711. {"CompactionJob::Run():Inprogress", "CompactionJob::Run():End"},
  4712. {"CompactionJob::Run():End",
  4713. "DBTest::PreShutdownCompactionMiddle:VerifyPreshutdown"}});
  4714. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  4715. // Make rocksdb busy
  4716. int key = 0;
  4717. // check how many threads are doing compaction using GetThreadList
  4718. int operation_count[ThreadStatus::NUM_OP_TYPES] = {0};
  4719. for (int file = 0; file < 16 * kNumL0Files; ++file) {
  4720. for (int k = 0; k < kEntriesPerBuffer; ++k) {
  4721. ASSERT_OK(Put(std::to_string(key++), rnd.RandomString(kTestValueSize)));
  4722. }
  4723. ASSERT_OK(env_->GetThreadList(&thread_list));
  4724. for (const auto& thread : thread_list) {
  4725. operation_count[thread.operation_type]++;
  4726. }
  4727. // Speed up the test
  4728. if (operation_count[ThreadStatus::OP_FLUSH] > 1 &&
  4729. operation_count[ThreadStatus::OP_COMPACTION] >
  4730. 0.6 * options.max_background_compactions) {
  4731. break;
  4732. }
  4733. if (file == 15 * kNumL0Files) {
  4734. TEST_SYNC_POINT("DBTest::PreShutdownCompactionMiddle:VerifyCompaction");
  4735. }
  4736. }
  4737. ASSERT_GE(operation_count[ThreadStatus::OP_COMPACTION], 1);
  4738. CancelAllBackgroundWork(db_);
  4739. TEST_SYNC_POINT("DBTest::PreShutdownCompactionMiddle:Preshutdown");
  4740. TEST_SYNC_POINT("DBTest::PreShutdownCompactionMiddle:VerifyPreshutdown");
  4741. ASSERT_OK(dbfull()->TEST_WaitForBackgroundWork());
  4742. // Record the number of compactions at a time.
  4743. for (int i = 0; i < ThreadStatus::NUM_OP_TYPES; ++i) {
  4744. operation_count[i] = 0;
  4745. }
  4746. ASSERT_OK(env_->GetThreadList(&thread_list));
  4747. for (const auto& thread : thread_list) {
  4748. operation_count[thread.operation_type]++;
  4749. }
  4750. ASSERT_EQ(operation_count[ThreadStatus::OP_COMPACTION], 0);
  4751. }
  4752. #endif // ROCKSDB_USING_THREAD_STATUS
  4753. TEST_F(DBTest, FlushOnDestroy) {
  4754. WriteOptions wo;
  4755. wo.disableWAL = true;
  4756. ASSERT_OK(Put("foo", "v1", wo));
  4757. CancelAllBackgroundWork(db_);
  4758. }
  4759. TEST_F(DBTest, DynamicCompactionOptions) {
  4760. // minimum write buffer size is enforced at 64KB
  4761. const uint64_t k32KB = 1 << 15;
  4762. const uint64_t k64KB = 1 << 16;
  4763. const uint64_t k128KB = 1 << 17;
  4764. const uint64_t k1MB = 1 << 20;
  4765. const uint64_t k4KB = 1 << 12;
  4766. Options options;
  4767. options.level_compaction_dynamic_level_bytes = false;
  4768. options.env = env_;
  4769. options.create_if_missing = true;
  4770. options.compression = kNoCompression;
  4771. options.soft_pending_compaction_bytes_limit = 1024 * 1024;
  4772. options.write_buffer_size = k64KB;
  4773. options.arena_block_size = 4 * k4KB;
  4774. options.max_write_buffer_number = 2;
  4775. // Compaction related options
  4776. options.level0_file_num_compaction_trigger = 3;
  4777. options.level0_slowdown_writes_trigger = 4;
  4778. options.level0_stop_writes_trigger = 8;
  4779. options.target_file_size_base = k64KB;
  4780. options.max_compaction_bytes = options.target_file_size_base * 10;
  4781. options.target_file_size_multiplier = 1;
  4782. options.max_bytes_for_level_base = k128KB;
  4783. options.max_bytes_for_level_multiplier = 4;
  4784. // Block flush thread and disable compaction thread
  4785. env_->SetBackgroundThreads(1, Env::LOW);
  4786. env_->SetBackgroundThreads(1, Env::HIGH);
  4787. DestroyAndReopen(options);
  4788. auto gen_l0_kb = [this](int start, int size, int stride) {
  4789. Random rnd(301);
  4790. for (int i = 0; i < size; i++) {
  4791. ASSERT_OK(Put(Key(start + stride * i), rnd.RandomString(1024)));
  4792. }
  4793. ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
  4794. };
  4795. // Write 3 files that have the same key range.
  4796. // Since level0_file_num_compaction_trigger is 3, compaction should be
  4797. // triggered. The compaction should result in one L1 file
  4798. gen_l0_kb(0, 64, 1);
  4799. ASSERT_EQ(NumTableFilesAtLevel(0), 1);
  4800. gen_l0_kb(0, 64, 1);
  4801. ASSERT_EQ(NumTableFilesAtLevel(0), 2);
  4802. gen_l0_kb(0, 64, 1);
  4803. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  4804. ASSERT_EQ("0,1", FilesPerLevel());
  4805. std::vector<LiveFileMetaData> metadata;
  4806. db_->GetLiveFilesMetaData(&metadata);
  4807. ASSERT_EQ(1U, metadata.size());
  4808. ASSERT_LE(metadata[0].size, k64KB + k4KB);
  4809. ASSERT_GE(metadata[0].size, k64KB - k4KB);
  4810. // Test compaction trigger and target_file_size_base
  4811. // Reduce compaction trigger to 2, and reduce L1 file size to 32KB.
  4812. // Writing to 64KB L0 files should trigger a compaction. Since these
  4813. // 2 L0 files have the same key range, compaction merge them and should
  4814. // result in 2 32KB L1 files.
  4815. ASSERT_OK(
  4816. dbfull()->SetOptions({{"level0_file_num_compaction_trigger", "2"},
  4817. {"target_file_size_base", std::to_string(k32KB)}}));
  4818. gen_l0_kb(0, 64, 1);
  4819. ASSERT_EQ("1,1", FilesPerLevel());
  4820. gen_l0_kb(0, 64, 1);
  4821. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  4822. ASSERT_EQ("0,2", FilesPerLevel());
  4823. metadata.clear();
  4824. db_->GetLiveFilesMetaData(&metadata);
  4825. ASSERT_EQ(2U, metadata.size());
  4826. ASSERT_LE(metadata[0].size, k32KB + k4KB);
  4827. ASSERT_GE(metadata[0].size, k32KB - k4KB);
  4828. ASSERT_LE(metadata[1].size, k32KB + k4KB);
  4829. ASSERT_GE(metadata[1].size, k32KB - k4KB);
  4830. // Test max_bytes_for_level_base
  4831. // Increase level base size to 256KB and write enough data that will
  4832. // fill L1 and L2. L1 size should be around 256KB while L2 size should be
  4833. // around 256KB x 4.
  4834. ASSERT_OK(dbfull()->SetOptions(
  4835. {{"max_bytes_for_level_base", std::to_string(k1MB)}}));
  4836. // writing 96 x 64KB => 6 * 1024KB
  4837. // (L1 + L2) = (1 + 4) * 1024KB
  4838. for (int i = 0; i < 96; ++i) {
  4839. gen_l0_kb(i, 64, 96);
  4840. }
  4841. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  4842. ASSERT_GT(SizeAtLevel(1), k1MB / 2);
  4843. ASSERT_LT(SizeAtLevel(1), k1MB + k1MB / 2);
  4844. // Within (0.5, 1.5) of 4MB.
  4845. ASSERT_GT(SizeAtLevel(2), 2 * k1MB);
  4846. ASSERT_LT(SizeAtLevel(2), 6 * k1MB);
  4847. // Test max_bytes_for_level_multiplier and
  4848. // max_bytes_for_level_base. Now, reduce both mulitplier and level base,
  4849. // After filling enough data that can fit in L1 - L3, we should see L1 size
  4850. // reduces to 128KB from 256KB which was asserted previously. Same for L2.
  4851. ASSERT_OK(dbfull()->SetOptions(
  4852. {{"max_bytes_for_level_multiplier", "2"},
  4853. {"max_bytes_for_level_base", std::to_string(k128KB)}}));
  4854. // writing 20 x 64KB = 10 x 128KB
  4855. // (L1 + L2 + L3) = (1 + 2 + 4) * 128KB
  4856. for (int i = 0; i < 20; ++i) {
  4857. gen_l0_kb(i, 64, 32);
  4858. }
  4859. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  4860. uint64_t total_size = SizeAtLevel(1) + SizeAtLevel(2) + SizeAtLevel(3);
  4861. ASSERT_TRUE(total_size < k128KB * 7 * 1.5);
  4862. // Test level0_stop_writes_trigger.
  4863. // Clean up memtable and L0. Block compaction threads. If continue to write
  4864. // and flush memtables. We should see put stop after 8 memtable flushes
  4865. // since level0_stop_writes_trigger = 8
  4866. ASSERT_OK(dbfull()->TEST_FlushMemTable(true, true));
  4867. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  4868. // Block compaction
  4869. test::SleepingBackgroundTask sleeping_task_low;
  4870. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &sleeping_task_low,
  4871. Env::Priority::LOW);
  4872. sleeping_task_low.WaitUntilSleeping();
  4873. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  4874. int count = 0;
  4875. Random rnd(301);
  4876. WriteOptions wo;
  4877. while (count < 64) {
  4878. ASSERT_OK(Put(Key(count), rnd.RandomString(1024), wo));
  4879. ASSERT_OK(dbfull()->TEST_FlushMemTable(true, true));
  4880. count++;
  4881. if (dbfull()->TEST_write_controler().IsStopped()) {
  4882. sleeping_task_low.WakeUp();
  4883. break;
  4884. }
  4885. }
  4886. // Stop trigger = 8
  4887. ASSERT_EQ(count, 8);
  4888. // Unblock
  4889. sleeping_task_low.WaitUntilDone();
  4890. // Now reduce level0_stop_writes_trigger to 6. Clear up memtables and L0.
  4891. // Block compaction thread again. Perform the put and memtable flushes
  4892. // until we see the stop after 6 memtable flushes.
  4893. ASSERT_OK(dbfull()->SetOptions({{"level0_stop_writes_trigger", "6"}}));
  4894. ASSERT_OK(dbfull()->TEST_FlushMemTable(true));
  4895. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  4896. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  4897. // Block compaction again
  4898. sleeping_task_low.Reset();
  4899. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &sleeping_task_low,
  4900. Env::Priority::LOW);
  4901. sleeping_task_low.WaitUntilSleeping();
  4902. count = 0;
  4903. while (count < 64) {
  4904. ASSERT_OK(Put(Key(count), rnd.RandomString(1024), wo));
  4905. ASSERT_OK(dbfull()->TEST_FlushMemTable(true, true));
  4906. count++;
  4907. if (dbfull()->TEST_write_controler().IsStopped()) {
  4908. sleeping_task_low.WakeUp();
  4909. break;
  4910. }
  4911. }
  4912. ASSERT_EQ(count, 6);
  4913. // Unblock
  4914. sleeping_task_low.WaitUntilDone();
  4915. // Test disable_auto_compactions
  4916. // Compaction thread is unblocked but auto compaction is disabled. Write
  4917. // 4 L0 files and compaction should be triggered. If auto compaction is
  4918. // disabled, then TEST_WaitForCompact will be waiting for nothing. Number of
  4919. // L0 files do not change after the call.
  4920. ASSERT_OK(dbfull()->SetOptions({{"disable_auto_compactions", "true"}}));
  4921. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  4922. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  4923. for (int i = 0; i < 4; ++i) {
  4924. ASSERT_OK(Put(Key(i), rnd.RandomString(1024)));
  4925. // Wait for compaction so that put won't stop
  4926. ASSERT_OK(dbfull()->TEST_FlushMemTable(true));
  4927. }
  4928. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  4929. ASSERT_EQ(NumTableFilesAtLevel(0), 4);
  4930. // Enable auto compaction and perform the same test, # of L0 files should be
  4931. // reduced after compaction.
  4932. ASSERT_OK(dbfull()->SetOptions({{"disable_auto_compactions", "false"}}));
  4933. ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  4934. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  4935. for (int i = 0; i < 4; ++i) {
  4936. ASSERT_OK(Put(Key(i), rnd.RandomString(1024)));
  4937. // Wait for compaction so that put won't stop
  4938. ASSERT_OK(dbfull()->TEST_FlushMemTable(true));
  4939. }
  4940. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  4941. ASSERT_LT(NumTableFilesAtLevel(0), 4);
  4942. }
  4943. // Test dynamic FIFO compaction options.
  4944. // This test covers just option parsing and makes sure that the options are
  4945. // correctly assigned. Also look at DBOptionsTest.SetFIFOCompactionOptions
  4946. // test which makes sure that the FIFO compaction funcionality is working
  4947. // as expected on dynamically changing the options.
  4948. // Even more FIFOCompactionTests are at DBTest.FIFOCompaction* .
  4949. TEST_F(DBTest, DynamicFIFOCompactionOptions) {
  4950. Options options;
  4951. options.ttl = 0;
  4952. options.create_if_missing = true;
  4953. options.env = env_;
  4954. DestroyAndReopen(options);
  4955. // Initial defaults
  4956. ASSERT_EQ(dbfull()->GetOptions().compaction_options_fifo.max_table_files_size,
  4957. 1024 * 1024 * 1024);
  4958. ASSERT_EQ(dbfull()->GetOptions().ttl, 0);
  4959. ASSERT_EQ(dbfull()->GetOptions().compaction_options_fifo.allow_compaction,
  4960. false);
  4961. ASSERT_OK(dbfull()->SetOptions(
  4962. {{"compaction_options_fifo", "{max_table_files_size=23;}"}}));
  4963. ASSERT_EQ(dbfull()->GetOptions().compaction_options_fifo.max_table_files_size,
  4964. 23);
  4965. ASSERT_EQ(dbfull()->GetOptions().ttl, 0);
  4966. ASSERT_EQ(dbfull()->GetOptions().compaction_options_fifo.allow_compaction,
  4967. false);
  4968. ASSERT_OK(dbfull()->SetOptions({{"ttl", "97"}}));
  4969. ASSERT_EQ(dbfull()->GetOptions().compaction_options_fifo.max_table_files_size,
  4970. 23);
  4971. ASSERT_EQ(dbfull()->GetOptions().ttl, 97);
  4972. ASSERT_EQ(dbfull()->GetOptions().compaction_options_fifo.allow_compaction,
  4973. false);
  4974. ASSERT_OK(dbfull()->SetOptions({{"ttl", "203"}}));
  4975. ASSERT_EQ(dbfull()->GetOptions().compaction_options_fifo.max_table_files_size,
  4976. 23);
  4977. ASSERT_EQ(dbfull()->GetOptions().ttl, 203);
  4978. ASSERT_EQ(dbfull()->GetOptions().compaction_options_fifo.allow_compaction,
  4979. false);
  4980. ASSERT_OK(dbfull()->SetOptions(
  4981. {{"compaction_options_fifo", "{allow_compaction=true;}"}}));
  4982. ASSERT_EQ(dbfull()->GetOptions().compaction_options_fifo.max_table_files_size,
  4983. 23);
  4984. ASSERT_EQ(dbfull()->GetOptions().ttl, 203);
  4985. ASSERT_EQ(dbfull()->GetOptions().compaction_options_fifo.allow_compaction,
  4986. true);
  4987. ASSERT_OK(dbfull()->SetOptions(
  4988. {{"compaction_options_fifo", "{max_table_files_size=31;}"}}));
  4989. ASSERT_EQ(dbfull()->GetOptions().compaction_options_fifo.max_table_files_size,
  4990. 31);
  4991. ASSERT_EQ(dbfull()->GetOptions().ttl, 203);
  4992. ASSERT_EQ(dbfull()->GetOptions().compaction_options_fifo.allow_compaction,
  4993. true);
  4994. ASSERT_OK(dbfull()->SetOptions(
  4995. {{"compaction_options_fifo",
  4996. "{max_table_files_size=51;allow_compaction=true;}"}}));
  4997. ASSERT_OK(dbfull()->SetOptions({{"ttl", "49"}}));
  4998. ASSERT_EQ(dbfull()->GetOptions().compaction_options_fifo.max_table_files_size,
  4999. 51);
  5000. ASSERT_EQ(dbfull()->GetOptions().ttl, 49);
  5001. ASSERT_EQ(dbfull()->GetOptions().compaction_options_fifo.allow_compaction,
  5002. true);
  5003. }
  5004. TEST_F(DBTest, DynamicUniversalCompactionOptions) {
  5005. Options options;
  5006. options.create_if_missing = true;
  5007. options.env = env_;
  5008. DestroyAndReopen(options);
  5009. // Initial defaults
  5010. ASSERT_EQ(dbfull()->GetOptions().compaction_options_universal.size_ratio, 1U);
  5011. ASSERT_EQ(dbfull()->GetOptions().compaction_options_universal.min_merge_width,
  5012. 2u);
  5013. ASSERT_EQ(dbfull()->GetOptions().compaction_options_universal.max_merge_width,
  5014. UINT_MAX);
  5015. ASSERT_EQ(dbfull()
  5016. ->GetOptions()
  5017. .compaction_options_universal.max_size_amplification_percent,
  5018. 200u);
  5019. ASSERT_EQ(dbfull()
  5020. ->GetOptions()
  5021. .compaction_options_universal.compression_size_percent,
  5022. -1);
  5023. ASSERT_EQ(dbfull()->GetOptions().compaction_options_universal.stop_style,
  5024. kCompactionStopStyleTotalSize);
  5025. ASSERT_EQ(
  5026. dbfull()->GetOptions().compaction_options_universal.allow_trivial_move,
  5027. false);
  5028. ASSERT_EQ(dbfull()->GetOptions().compaction_options_universal.max_read_amp,
  5029. -1);
  5030. ASSERT_OK(dbfull()->SetOptions(
  5031. {{"compaction_options_universal", "{size_ratio=7;}"}}));
  5032. ASSERT_EQ(dbfull()->GetOptions().compaction_options_universal.size_ratio, 7u);
  5033. ASSERT_EQ(dbfull()->GetOptions().compaction_options_universal.min_merge_width,
  5034. 2u);
  5035. ASSERT_EQ(dbfull()->GetOptions().compaction_options_universal.max_merge_width,
  5036. UINT_MAX);
  5037. ASSERT_EQ(dbfull()
  5038. ->GetOptions()
  5039. .compaction_options_universal.max_size_amplification_percent,
  5040. 200u);
  5041. ASSERT_EQ(dbfull()
  5042. ->GetOptions()
  5043. .compaction_options_universal.compression_size_percent,
  5044. -1);
  5045. ASSERT_EQ(dbfull()->GetOptions().compaction_options_universal.stop_style,
  5046. kCompactionStopStyleTotalSize);
  5047. ASSERT_EQ(
  5048. dbfull()->GetOptions().compaction_options_universal.allow_trivial_move,
  5049. false);
  5050. ASSERT_EQ(dbfull()->GetOptions().compaction_options_universal.max_read_amp,
  5051. -1);
  5052. ASSERT_OK(dbfull()->SetOptions({{"compaction_options_universal",
  5053. "{min_merge_width=11;max_read_amp=0;}"}}));
  5054. ASSERT_EQ(dbfull()->GetOptions().compaction_options_universal.size_ratio, 7u);
  5055. ASSERT_EQ(dbfull()->GetOptions().compaction_options_universal.min_merge_width,
  5056. 11u);
  5057. ASSERT_EQ(dbfull()->GetOptions().compaction_options_universal.max_merge_width,
  5058. UINT_MAX);
  5059. ASSERT_EQ(dbfull()
  5060. ->GetOptions()
  5061. .compaction_options_universal.max_size_amplification_percent,
  5062. 200u);
  5063. ASSERT_EQ(dbfull()
  5064. ->GetOptions()
  5065. .compaction_options_universal.compression_size_percent,
  5066. -1);
  5067. ASSERT_EQ(dbfull()->GetOptions().compaction_options_universal.stop_style,
  5068. kCompactionStopStyleTotalSize);
  5069. ASSERT_EQ(
  5070. dbfull()->GetOptions().compaction_options_universal.allow_trivial_move,
  5071. false);
  5072. ASSERT_EQ(dbfull()->GetOptions().compaction_options_universal.max_read_amp,
  5073. 0);
  5074. }
  5075. TEST_F(DBTest, FileCreationRandomFailure) {
  5076. Options options;
  5077. options.env = env_;
  5078. options.create_if_missing = true;
  5079. options.write_buffer_size = 100000; // Small write buffer
  5080. options.target_file_size_base = 200000;
  5081. options.max_bytes_for_level_base = 1000000;
  5082. options.max_bytes_for_level_multiplier = 2;
  5083. DestroyAndReopen(options);
  5084. Random rnd(301);
  5085. constexpr int kCDTKeysPerBuffer = 4;
  5086. constexpr int kTestSize = kCDTKeysPerBuffer * 4096;
  5087. constexpr int kTotalIteration = 20;
  5088. // the second half of the test involves in random failure
  5089. // of file creation.
  5090. constexpr int kRandomFailureTest = kTotalIteration / 2;
  5091. std::vector<std::string> values;
  5092. for (int i = 0; i < kTestSize; ++i) {
  5093. values.emplace_back("NOT_FOUND");
  5094. }
  5095. for (int j = 0; j < kTotalIteration; ++j) {
  5096. if (j == kRandomFailureTest) {
  5097. env_->non_writeable_rate_.store(90);
  5098. }
  5099. for (int k = 0; k < kTestSize; ++k) {
  5100. // here we expect some of the Put fails.
  5101. std::string value = rnd.RandomString(100);
  5102. Status s = Put(Key(k), Slice(value));
  5103. if (s.ok()) {
  5104. // update the latest successful put
  5105. values[k] = value;
  5106. }
  5107. // But everything before we simulate the failure-test should succeed.
  5108. if (j < kRandomFailureTest) {
  5109. ASSERT_OK(s);
  5110. }
  5111. }
  5112. }
  5113. // If rocksdb does not do the correct job, internal assert will fail here.
  5114. ASSERT_TRUE(dbfull()->TEST_WaitForFlushMemTable().IsIOError());
  5115. ASSERT_TRUE(dbfull()->TEST_WaitForCompact().IsIOError());
  5116. // verify we have the latest successful update
  5117. for (int k = 0; k < kTestSize; ++k) {
  5118. auto v = Get(Key(k));
  5119. ASSERT_EQ(v, values[k]);
  5120. }
  5121. // reopen and reverify we have the latest successful update
  5122. env_->non_writeable_rate_.store(0);
  5123. Reopen(options);
  5124. for (int k = 0; k < kTestSize; ++k) {
  5125. auto v = Get(Key(k));
  5126. ASSERT_EQ(v, values[k]);
  5127. }
  5128. }
  5129. TEST_F(DBTest, DynamicMiscOptions) {
  5130. // Test max_sequential_skip_in_iterations
  5131. Options options;
  5132. options.env = env_;
  5133. options.create_if_missing = true;
  5134. options.max_sequential_skip_in_iterations = 16;
  5135. options.compression = kNoCompression;
  5136. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  5137. DestroyAndReopen(options);
  5138. auto assert_reseek_count = [this, &options](int key_start, int num_reseek) {
  5139. int key0 = key_start;
  5140. int key1 = key_start + 1;
  5141. int key2 = key_start + 2;
  5142. Random rnd(301);
  5143. ASSERT_OK(Put(Key(key0), rnd.RandomString(8)));
  5144. for (int i = 0; i < 10; ++i) {
  5145. ASSERT_OK(Put(Key(key1), rnd.RandomString(8)));
  5146. }
  5147. ASSERT_OK(Put(Key(key2), rnd.RandomString(8)));
  5148. std::unique_ptr<Iterator> iter(db_->NewIterator(ReadOptions()));
  5149. iter->Seek(Key(key1));
  5150. ASSERT_TRUE(iter->Valid());
  5151. ASSERT_EQ(iter->key().compare(Key(key1)), 0);
  5152. iter->Next();
  5153. ASSERT_TRUE(iter->Valid());
  5154. ASSERT_EQ(iter->key().compare(Key(key2)), 0);
  5155. ASSERT_EQ(num_reseek,
  5156. TestGetTickerCount(options, NUMBER_OF_RESEEKS_IN_ITERATION));
  5157. };
  5158. // No reseek
  5159. assert_reseek_count(100, 0);
  5160. ASSERT_OK(dbfull()->SetOptions({{"max_sequential_skip_in_iterations", "4"}}));
  5161. // Clear memtable and make new option effective
  5162. ASSERT_OK(dbfull()->TEST_FlushMemTable(true));
  5163. // Trigger reseek
  5164. assert_reseek_count(200, 1);
  5165. ASSERT_OK(
  5166. dbfull()->SetOptions({{"max_sequential_skip_in_iterations", "16"}}));
  5167. // Clear memtable and make new option effective
  5168. ASSERT_OK(dbfull()->TEST_FlushMemTable(true));
  5169. // No reseek
  5170. assert_reseek_count(300, 1);
  5171. MutableCFOptions mutable_cf_options;
  5172. CreateAndReopenWithCF({"pikachu"}, options);
  5173. // Test soft_pending_compaction_bytes_limit,
  5174. // hard_pending_compaction_bytes_limit
  5175. ASSERT_OK(dbfull()->SetOptions(
  5176. handles_[1], {{"soft_pending_compaction_bytes_limit", "200"},
  5177. {"hard_pending_compaction_bytes_limit", "300"}}));
  5178. ASSERT_OK(dbfull()->TEST_GetLatestMutableCFOptions(handles_[1],
  5179. &mutable_cf_options));
  5180. ASSERT_EQ(200, mutable_cf_options.soft_pending_compaction_bytes_limit);
  5181. ASSERT_EQ(300, mutable_cf_options.hard_pending_compaction_bytes_limit);
  5182. // Test report_bg_io_stats
  5183. ASSERT_OK(
  5184. dbfull()->SetOptions(handles_[1], {{"report_bg_io_stats", "true"}}));
  5185. // sanity check
  5186. ASSERT_OK(dbfull()->TEST_GetLatestMutableCFOptions(handles_[1],
  5187. &mutable_cf_options));
  5188. ASSERT_TRUE(mutable_cf_options.report_bg_io_stats);
  5189. // Test compression
  5190. // sanity check
  5191. ASSERT_OK(dbfull()->SetOptions({{"compression", "kNoCompression"}}));
  5192. ASSERT_OK(dbfull()->TEST_GetLatestMutableCFOptions(handles_[0],
  5193. &mutable_cf_options));
  5194. ASSERT_EQ(CompressionType::kNoCompression, mutable_cf_options.compression);
  5195. if (Snappy_Supported()) {
  5196. ASSERT_OK(dbfull()->SetOptions({{"compression", "kSnappyCompression"}}));
  5197. ASSERT_OK(dbfull()->TEST_GetLatestMutableCFOptions(handles_[0],
  5198. &mutable_cf_options));
  5199. ASSERT_EQ(CompressionType::kSnappyCompression,
  5200. mutable_cf_options.compression);
  5201. }
  5202. // Test paranoid_file_checks already done in db_block_cache_test
  5203. ASSERT_OK(
  5204. dbfull()->SetOptions(handles_[1], {{"paranoid_file_checks", "true"}}));
  5205. ASSERT_OK(dbfull()->TEST_GetLatestMutableCFOptions(handles_[1],
  5206. &mutable_cf_options));
  5207. ASSERT_TRUE(mutable_cf_options.report_bg_io_stats);
  5208. }
  5209. TEST_F(DBTest, L0L1L2AndUpHitCounter) {
  5210. const int kNumLevels = 3;
  5211. const int kNumKeysPerLevel = 10000;
  5212. const int kNumKeysPerDb = kNumLevels * kNumKeysPerLevel;
  5213. Options options = CurrentOptions();
  5214. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  5215. Reopen(options);
  5216. // After the below loop there will be one file on each of L0, L1, and L2.
  5217. int key = 0;
  5218. for (int output_level = kNumLevels - 1; output_level >= 0; --output_level) {
  5219. for (int i = 0; i < kNumKeysPerLevel; ++i) {
  5220. ASSERT_OK(Put(Key(key), "val"));
  5221. key++;
  5222. }
  5223. ASSERT_OK(Flush());
  5224. for (int input_level = 0; input_level < output_level; ++input_level) {
  5225. // `TEST_CompactRange(input_level, ...)` compacts from `input_level` to
  5226. // `input_level + 1`.
  5227. ASSERT_OK(dbfull()->TEST_CompactRange(input_level, nullptr, nullptr));
  5228. }
  5229. }
  5230. assert(key == kNumKeysPerDb);
  5231. ASSERT_EQ(0, TestGetTickerCount(options, GET_HIT_L0));
  5232. ASSERT_EQ(0, TestGetTickerCount(options, GET_HIT_L1));
  5233. ASSERT_EQ(0, TestGetTickerCount(options, GET_HIT_L2_AND_UP));
  5234. for (int i = 0; i < kNumKeysPerDb; i++) {
  5235. ASSERT_EQ(Get(Key(i)), "val");
  5236. }
  5237. ASSERT_EQ(kNumKeysPerLevel, TestGetTickerCount(options, GET_HIT_L0));
  5238. ASSERT_EQ(kNumKeysPerLevel, TestGetTickerCount(options, GET_HIT_L1));
  5239. ASSERT_EQ(kNumKeysPerLevel, TestGetTickerCount(options, GET_HIT_L2_AND_UP));
  5240. ASSERT_EQ(kNumKeysPerDb, TestGetTickerCount(options, GET_HIT_L0) +
  5241. TestGetTickerCount(options, GET_HIT_L1) +
  5242. TestGetTickerCount(options, GET_HIT_L2_AND_UP));
  5243. }
  5244. TEST_F(DBTest, EncodeDecompressedBlockSizeTest) {
  5245. // Allow testing format_version=1
  5246. bool& allow_unsupported_fv = TEST_AllowUnsupportedFormatVersion();
  5247. SaveAndRestore guard(&allow_unsupported_fv);
  5248. ASSERT_FALSE(allow_unsupported_fv);
  5249. // iter 0 -- zlib
  5250. // iter 1 -- bzip2
  5251. // iter 2 -- lz4
  5252. // iter 3 -- lz4HC
  5253. // iter 4 -- xpress
  5254. CompressionType compressions[] = {kZlibCompression, kBZip2Compression,
  5255. kLZ4Compression, kLZ4HCCompression,
  5256. kXpressCompression};
  5257. for (auto comp : compressions) {
  5258. if (!CompressionTypeSupported(comp)) {
  5259. continue;
  5260. }
  5261. // first_table_version 1 -- generate with table_version == 1, read with
  5262. // table_version == 2
  5263. // first_table_version 2 -- generate with table_version == 2, read with
  5264. // table_version == 1
  5265. for (int first_table_version = 1; first_table_version <= 2;
  5266. ++first_table_version) {
  5267. BlockBasedTableOptions table_options;
  5268. table_options.format_version = first_table_version;
  5269. table_options.filter_policy.reset(NewBloomFilterPolicy(10));
  5270. Options options = CurrentOptions();
  5271. // Hack to generate old files (checked in factory construction)
  5272. allow_unsupported_fv = true;
  5273. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  5274. ASSERT_EQ(options.table_factory->GetOptions<BlockBasedTableOptions>()
  5275. ->format_version,
  5276. first_table_version);
  5277. // Able to read old files without the hack
  5278. allow_unsupported_fv = false;
  5279. options.create_if_missing = true;
  5280. options.compression = comp;
  5281. DestroyAndReopen(options);
  5282. int kNumKeysWritten = 1000;
  5283. Random rnd(301);
  5284. for (int i = 0; i < kNumKeysWritten; ++i) {
  5285. // compressible string
  5286. ASSERT_OK(Put(Key(i), rnd.RandomString(128) + std::string(128, 'a')));
  5287. }
  5288. ASSERT_OK(Flush());
  5289. table_options.format_version = first_table_version == 1 ? 2 : 1;
  5290. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  5291. // format_version (for writing) is sanitized to minimum supported
  5292. ASSERT_EQ(options.table_factory->GetOptions<BlockBasedTableOptions>()
  5293. ->format_version,
  5294. BlockBasedTableFactory::kMinSupportedFormatVersion);
  5295. Reopen(options);
  5296. for (int i = 0; i < kNumKeysWritten; ++i) {
  5297. auto r = Get(Key(i));
  5298. ASSERT_EQ(r.substr(128), std::string(128, 'a'));
  5299. }
  5300. }
  5301. }
  5302. }
  5303. TEST_F(DBTest, CloseSpeedup) {
  5304. Options options = CurrentOptions();
  5305. options.compaction_style = kCompactionStyleLevel;
  5306. options.write_buffer_size = 110 << 10; // 110KB
  5307. options.arena_block_size = 4 << 10;
  5308. options.level0_file_num_compaction_trigger = 2;
  5309. options.num_levels = 4;
  5310. options.max_bytes_for_level_base = 400 * 1024;
  5311. options.max_write_buffer_number = 16;
  5312. // Block background threads
  5313. env_->SetBackgroundThreads(1, Env::LOW);
  5314. env_->SetBackgroundThreads(1, Env::HIGH);
  5315. test::SleepingBackgroundTask sleeping_task_low;
  5316. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &sleeping_task_low,
  5317. Env::Priority::LOW);
  5318. test::SleepingBackgroundTask sleeping_task_high;
  5319. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask,
  5320. &sleeping_task_high, Env::Priority::HIGH);
  5321. std::vector<std::string> filenames;
  5322. ASSERT_OK(env_->GetChildren(dbname_, &filenames));
  5323. // In Windows, LOCK file cannot be deleted because it is locked by db_test
  5324. // After closing db_test, the LOCK file is unlocked and can be deleted
  5325. // Delete archival files.
  5326. bool deleteDir = true;
  5327. for (size_t i = 0; i < filenames.size(); ++i) {
  5328. Status s = env_->DeleteFile(dbname_ + "/" + filenames[i]);
  5329. if (!s.ok()) {
  5330. deleteDir = false;
  5331. }
  5332. }
  5333. if (deleteDir) {
  5334. ASSERT_OK(env_->DeleteDir(dbname_));
  5335. }
  5336. DestroyAndReopen(options);
  5337. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  5338. env_->SetBackgroundThreads(1, Env::LOW);
  5339. env_->SetBackgroundThreads(1, Env::HIGH);
  5340. Random rnd(301);
  5341. int key_idx = 0;
  5342. // First three 110KB files are not going to level 2
  5343. // After that, (100K, 200K)
  5344. for (int num = 0; num < 5; num++) {
  5345. GenerateNewFile(&rnd, &key_idx, true);
  5346. }
  5347. ASSERT_EQ(0, GetSstFileCount(dbname_));
  5348. Close();
  5349. ASSERT_EQ(0, GetSstFileCount(dbname_));
  5350. // Unblock background threads
  5351. sleeping_task_high.WakeUp();
  5352. sleeping_task_high.WaitUntilDone();
  5353. sleeping_task_low.WakeUp();
  5354. sleeping_task_low.WaitUntilDone();
  5355. Destroy(options);
  5356. }
  5357. class DelayedMergeOperator : public MergeOperator {
  5358. private:
  5359. DBTest* db_test_;
  5360. public:
  5361. explicit DelayedMergeOperator(DBTest* d) : db_test_(d) {}
  5362. bool FullMergeV2(const MergeOperationInput& merge_in,
  5363. MergeOperationOutput* merge_out) const override {
  5364. db_test_->env_->MockSleepForMicroseconds(1000 *
  5365. merge_in.operand_list.size());
  5366. merge_out->new_value = "";
  5367. return true;
  5368. }
  5369. const char* Name() const override { return "DelayedMergeOperator"; }
  5370. };
  5371. TEST_F(DBTest, MergeTestTime) {
  5372. std::string one, two, three;
  5373. PutFixed64(&one, 1);
  5374. PutFixed64(&two, 2);
  5375. PutFixed64(&three, 3);
  5376. // Enable time profiling
  5377. SetPerfLevel(kEnableTime);
  5378. Options options = CurrentOptions();
  5379. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  5380. options.merge_operator.reset(new DelayedMergeOperator(this));
  5381. SetTimeElapseOnlySleepOnReopen(&options);
  5382. DestroyAndReopen(options);
  5383. // NOTE: Presumed unnecessary and removed: resetting mock time in env
  5384. ASSERT_EQ(TestGetTickerCount(options, MERGE_OPERATION_TOTAL_TIME), 0);
  5385. ASSERT_OK(db_->Put(WriteOptions(), "foo", one));
  5386. ASSERT_OK(Flush());
  5387. ASSERT_OK(db_->Merge(WriteOptions(), "foo", two));
  5388. ASSERT_OK(Flush());
  5389. ASSERT_OK(db_->Merge(WriteOptions(), "foo", three));
  5390. ASSERT_OK(Flush());
  5391. ReadOptions opt;
  5392. opt.verify_checksums = true;
  5393. opt.snapshot = nullptr;
  5394. std::string result;
  5395. ASSERT_OK(db_->Get(opt, "foo", &result));
  5396. ASSERT_EQ(2000000, TestGetTickerCount(options, MERGE_OPERATION_TOTAL_TIME));
  5397. ReadOptions read_options;
  5398. std::unique_ptr<Iterator> iter(db_->NewIterator(read_options));
  5399. int count = 0;
  5400. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  5401. ASSERT_OK(iter->status());
  5402. ++count;
  5403. }
  5404. ASSERT_OK(iter->status());
  5405. ASSERT_EQ(1, count);
  5406. ASSERT_EQ(4000000, TestGetTickerCount(options, MERGE_OPERATION_TOTAL_TIME));
  5407. #ifdef ROCKSDB_USING_THREAD_STATUS
  5408. ASSERT_GT(TestGetTickerCount(options, FLUSH_WRITE_BYTES), 0);
  5409. #endif // ROCKSDB_USING_THREAD_STATUS
  5410. }
  5411. TEST_P(DBTestWithParam, MergeCompactionTimeTest) {
  5412. SetPerfLevel(kEnableTime);
  5413. Options options = CurrentOptions();
  5414. options.compaction_filter_factory = std::make_shared<KeepFilterFactory>();
  5415. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  5416. options.merge_operator.reset(new DelayedMergeOperator(this));
  5417. options.disable_auto_compactions = true;
  5418. options.max_subcompactions = max_subcompactions_;
  5419. SetTimeElapseOnlySleepOnReopen(&options);
  5420. DestroyAndReopen(options);
  5421. constexpr unsigned n = 1000;
  5422. for (unsigned i = 0; i < n; i++) {
  5423. ASSERT_OK(db_->Merge(WriteOptions(), "foo", "TEST"));
  5424. ASSERT_OK(Flush());
  5425. }
  5426. ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
  5427. CompactRangeOptions cro;
  5428. cro.exclusive_manual_compaction = exclusive_manual_compaction_;
  5429. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  5430. ASSERT_EQ(uint64_t{n} * 1000000U,
  5431. TestGetTickerCount(options, MERGE_OPERATION_TOTAL_TIME));
  5432. }
  5433. TEST_P(DBTestWithParam, FilterCompactionTimeTest) {
  5434. Options options = CurrentOptions();
  5435. options.compaction_filter_factory =
  5436. std::make_shared<DelayFilterFactory>(this);
  5437. options.disable_auto_compactions = true;
  5438. options.create_if_missing = true;
  5439. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  5440. options.statistics->set_stats_level(kExceptTimeForMutex);
  5441. options.max_subcompactions = max_subcompactions_;
  5442. SetTimeElapseOnlySleepOnReopen(&options);
  5443. DestroyAndReopen(options);
  5444. unsigned n = 0;
  5445. // put some data
  5446. for (int table = 0; table < 4; ++table) {
  5447. for (int i = 0; i < 10 + table; ++i) {
  5448. ASSERT_OK(Put(std::to_string(table * 100 + i), "val"));
  5449. ++n;
  5450. }
  5451. ASSERT_OK(Flush());
  5452. }
  5453. CompactRangeOptions cro;
  5454. cro.exclusive_manual_compaction = exclusive_manual_compaction_;
  5455. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  5456. ASSERT_EQ(0U, CountLiveFiles());
  5457. Reopen(options);
  5458. Iterator* itr = db_->NewIterator(ReadOptions());
  5459. itr->SeekToFirst();
  5460. ASSERT_OK(itr->status());
  5461. ASSERT_EQ(uint64_t{n} * 1000000U,
  5462. TestGetTickerCount(options, FILTER_OPERATION_TOTAL_TIME));
  5463. delete itr;
  5464. }
  5465. #ifndef OS_WIN
  5466. // CPUMicros() is not supported. See WinClock::CPUMicros().
  5467. TEST_P(DBTestWithParam, CompactionTotalTimeTest) {
  5468. int record_count = 0;
  5469. class TestStatistics : public StatisticsImpl {
  5470. public:
  5471. explicit TestStatistics(int* record_count)
  5472. : StatisticsImpl(nullptr), record_count_(record_count) {}
  5473. void recordTick(uint32_t ticker_type, uint64_t count) override {
  5474. if (ticker_type == COMPACTION_CPU_TOTAL_TIME) {
  5475. ASSERT_GT(count, 0);
  5476. (*record_count_)++;
  5477. }
  5478. StatisticsImpl::recordTick(ticker_type, count);
  5479. }
  5480. int* record_count_;
  5481. };
  5482. Options options = CurrentOptions();
  5483. options.disable_auto_compactions = true;
  5484. options.create_if_missing = true;
  5485. options.statistics = std::make_shared<TestStatistics>(&record_count);
  5486. options.statistics->set_stats_level(kExceptTimeForMutex);
  5487. options.max_subcompactions = max_subcompactions_;
  5488. DestroyAndReopen(options);
  5489. int n = 0;
  5490. for (int table = 0; table < 4; ++table) {
  5491. for (int i = 0; i < 1000; ++i) {
  5492. ASSERT_OK(Put(std::to_string(table * 1000 + i), "val"));
  5493. ++n;
  5494. }
  5495. // Overlapping tables
  5496. ASSERT_OK(Put(std::to_string(0), "val"));
  5497. ++n;
  5498. ASSERT_OK(Flush());
  5499. }
  5500. CompactRangeOptions cro;
  5501. cro.exclusive_manual_compaction = exclusive_manual_compaction_;
  5502. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  5503. // Hard-coded number in CompactionJob::ProcessKeyValueCompaction().
  5504. const int kRecordStatsEvery = 1000;
  5505. // The stat COMPACTION_CPU_TOTAL_TIME should be recorded
  5506. // during compaction and once more after compaction.
  5507. ASSERT_EQ(n / kRecordStatsEvery + 1, record_count);
  5508. // Check that COMPACTION_CPU_TOTAL_TIME correctly
  5509. // records compaction time after a compaction.
  5510. HistogramData h;
  5511. options.statistics->histogramData(COMPACTION_CPU_TIME, &h);
  5512. ASSERT_EQ(1, h.count);
  5513. ASSERT_EQ(h.max, TestGetTickerCount(options, COMPACTION_CPU_TOTAL_TIME));
  5514. }
  5515. #endif
  5516. TEST_F(DBTest, TestLogCleanup) {
  5517. Options options = CurrentOptions();
  5518. options.write_buffer_size = 64 * 1024; // very small
  5519. // only two memtables allowed ==> only two log files
  5520. options.max_write_buffer_number = 2;
  5521. Reopen(options);
  5522. for (int i = 0; i < 100000; ++i) {
  5523. ASSERT_OK(Put(Key(i), "val"));
  5524. // only 2 memtables will be alive, so wals_to_free needs to always be below
  5525. // 2
  5526. ASSERT_LT(dbfull()->TEST_LogsToFreeSize(), static_cast<size_t>(3));
  5527. }
  5528. }
  5529. TEST_F(DBTest, EmptyCompactedDB) {
  5530. Options options = CurrentOptions();
  5531. options.max_open_files = -1;
  5532. Close();
  5533. ASSERT_OK(ReadOnlyReopen(options));
  5534. Status s = Put("new", "value");
  5535. ASSERT_TRUE(s.IsNotSupported());
  5536. Close();
  5537. }
  5538. TEST_F(DBTest, SuggestCompactRangeTest) {
  5539. class CompactionFilterFactoryGetContext : public CompactionFilterFactory {
  5540. public:
  5541. std::unique_ptr<CompactionFilter> CreateCompactionFilter(
  5542. const CompactionFilter::Context& context) override {
  5543. saved_context = context;
  5544. std::unique_ptr<CompactionFilter> empty_filter;
  5545. return empty_filter;
  5546. }
  5547. const char* Name() const override {
  5548. return "CompactionFilterFactoryGetContext";
  5549. }
  5550. static bool IsManual(CompactionFilterFactory* compaction_filter_factory) {
  5551. return static_cast<CompactionFilterFactoryGetContext*>(
  5552. compaction_filter_factory)
  5553. ->saved_context.is_manual_compaction;
  5554. }
  5555. CompactionFilter::Context saved_context;
  5556. };
  5557. Options options = CurrentOptions();
  5558. options.memtable_factory.reset(test::NewSpecialSkipListFactory(
  5559. DBTestBase::kNumKeysByGenerateNewRandomFile));
  5560. options.compaction_style = kCompactionStyleLevel;
  5561. options.compaction_filter_factory.reset(
  5562. new CompactionFilterFactoryGetContext());
  5563. options.write_buffer_size = 200 << 10;
  5564. options.arena_block_size = 4 << 10;
  5565. options.level0_file_num_compaction_trigger = 4;
  5566. options.num_levels = 4;
  5567. options.compression = kNoCompression;
  5568. options.max_bytes_for_level_base = 450 << 10;
  5569. options.target_file_size_base = 98 << 10;
  5570. options.max_compaction_bytes = static_cast<uint64_t>(1) << 60; // inf
  5571. Reopen(options);
  5572. Random rnd(301);
  5573. for (int num = 0; num < 10; num++) {
  5574. GenerateNewRandomFile(&rnd);
  5575. }
  5576. ASSERT_TRUE(!CompactionFilterFactoryGetContext::IsManual(
  5577. options.compaction_filter_factory.get()));
  5578. // make sure either L0 or L1 has file
  5579. while (NumTableFilesAtLevel(0) == 0 && NumTableFilesAtLevel(1) == 0) {
  5580. GenerateNewRandomFile(&rnd);
  5581. }
  5582. // compact it three times
  5583. for (int i = 0; i < 3; ++i) {
  5584. ASSERT_OK(experimental::SuggestCompactRange(db_, nullptr, nullptr));
  5585. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  5586. }
  5587. // All files are compacted
  5588. ASSERT_EQ(0, NumTableFilesAtLevel(0));
  5589. ASSERT_EQ(0, NumTableFilesAtLevel(1));
  5590. GenerateNewRandomFile(&rnd);
  5591. ASSERT_EQ(1, NumTableFilesAtLevel(0));
  5592. // nonoverlapping with the file on level 0
  5593. Slice start("a"), end("b");
  5594. ASSERT_OK(experimental::SuggestCompactRange(db_, &start, &end));
  5595. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  5596. // should not compact the level 0 file
  5597. ASSERT_EQ(1, NumTableFilesAtLevel(0));
  5598. start = Slice("j");
  5599. end = Slice("m");
  5600. ASSERT_OK(experimental::SuggestCompactRange(db_, &start, &end));
  5601. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  5602. // SuggestCompactRange() is not going to be reported as manual compaction
  5603. ASSERT_TRUE(!CompactionFilterFactoryGetContext::IsManual(
  5604. options.compaction_filter_factory.get()));
  5605. // now it should compact the level 0 file
  5606. // as it's a trivial move to L1, it triggers another one to compact to L2
  5607. ASSERT_EQ(0, NumTableFilesAtLevel(0));
  5608. ASSERT_EQ(0, NumTableFilesAtLevel(1));
  5609. }
  5610. TEST_F(DBTest, SuggestCompactRangeUniversal) {
  5611. Options options = CurrentOptions();
  5612. options.memtable_factory.reset(test::NewSpecialSkipListFactory(
  5613. DBTestBase::kNumKeysByGenerateNewRandomFile));
  5614. options.compaction_style = kCompactionStyleUniversal;
  5615. options.write_buffer_size = 200 << 10;
  5616. options.arena_block_size = 4 << 10;
  5617. options.level0_file_num_compaction_trigger = 4;
  5618. options.num_levels = 4;
  5619. options.compression = kNoCompression;
  5620. options.max_bytes_for_level_base = 450 << 10;
  5621. options.target_file_size_base = 98 << 10;
  5622. options.max_compaction_bytes = static_cast<uint64_t>(1) << 60; // inf
  5623. Reopen(options);
  5624. Random rnd(301);
  5625. for (int num = 0; num < 10; num++) {
  5626. GenerateNewRandomFile(&rnd);
  5627. }
  5628. ASSERT_EQ("1,2,3,4", FilesPerLevel());
  5629. for (int i = 0; i < 3; i++) {
  5630. ASSERT_OK(
  5631. db_->SuggestCompactRange(db_->DefaultColumnFamily(), nullptr, nullptr));
  5632. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  5633. }
  5634. // All files are compacted
  5635. ASSERT_EQ(0, NumTableFilesAtLevel(0));
  5636. ASSERT_EQ(0, NumTableFilesAtLevel(1));
  5637. ASSERT_EQ(0, NumTableFilesAtLevel(2));
  5638. GenerateNewRandomFile(&rnd);
  5639. ASSERT_EQ(1, NumTableFilesAtLevel(0));
  5640. // nonoverlapping with the file on level 0
  5641. Slice start("a"), end("b");
  5642. ASSERT_OK(experimental::SuggestCompactRange(db_, &start, &end));
  5643. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  5644. // should not compact the level 0 file
  5645. ASSERT_EQ(1, NumTableFilesAtLevel(0));
  5646. start = Slice("j");
  5647. end = Slice("m");
  5648. ASSERT_OK(experimental::SuggestCompactRange(db_, &start, &end));
  5649. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  5650. // now it should compact the level 0 file to the last level
  5651. ASSERT_EQ(0, NumTableFilesAtLevel(0));
  5652. ASSERT_EQ(0, NumTableFilesAtLevel(1));
  5653. }
  5654. TEST_F(DBTest, PromoteL0) {
  5655. Options options = CurrentOptions();
  5656. options.disable_auto_compactions = true;
  5657. options.write_buffer_size = 10 * 1024 * 1024;
  5658. // Exercise what was a use-after-free (ASAN failure) under ~VersionSet()
  5659. options.uncache_aggressiveness = 300;
  5660. DestroyAndReopen(options);
  5661. // non overlapping ranges
  5662. std::vector<std::pair<int32_t, int32_t>> ranges = {
  5663. {81, 160}, {0, 80}, {161, 240}, {241, 320}};
  5664. int32_t value_size = 10 * 1024; // 10 KB
  5665. Random rnd(301);
  5666. std::map<int32_t, std::string> values;
  5667. for (const auto& range : ranges) {
  5668. for (int32_t j = range.first; j < range.second; j++) {
  5669. values[j] = rnd.RandomString(value_size);
  5670. ASSERT_OK(Put(Key(j), values[j]));
  5671. }
  5672. ASSERT_OK(Flush());
  5673. }
  5674. int32_t level0_files = NumTableFilesAtLevel(0, 0);
  5675. ASSERT_EQ(level0_files, ranges.size());
  5676. ASSERT_EQ(NumTableFilesAtLevel(1, 0), 0); // No files in L1
  5677. // Promote L0 level to L2.
  5678. ASSERT_OK(experimental::PromoteL0(db_, db_->DefaultColumnFamily(), 2));
  5679. // We expect that all the files were trivially moved from L0 to L2
  5680. ASSERT_EQ(NumTableFilesAtLevel(0, 0), 0);
  5681. ASSERT_EQ(NumTableFilesAtLevel(2, 0), level0_files);
  5682. for (const auto& kv : values) {
  5683. ASSERT_EQ(Get(Key(kv.first)), kv.second);
  5684. }
  5685. }
  5686. TEST_F(DBTest, PromoteL0Failure) {
  5687. Options options = CurrentOptions();
  5688. options.disable_auto_compactions = true;
  5689. options.write_buffer_size = 10 * 1024 * 1024;
  5690. DestroyAndReopen(options);
  5691. // Produce two L0 files with overlapping ranges.
  5692. ASSERT_OK(Put(Key(0), ""));
  5693. ASSERT_OK(Put(Key(3), ""));
  5694. ASSERT_OK(Flush());
  5695. ASSERT_OK(Put(Key(1), ""));
  5696. ASSERT_OK(Flush());
  5697. Status status;
  5698. // Fails because L0 has overlapping files.
  5699. status = experimental::PromoteL0(db_, db_->DefaultColumnFamily());
  5700. ASSERT_TRUE(status.IsInvalidArgument());
  5701. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  5702. // Now there is a file in L1.
  5703. ASSERT_GE(NumTableFilesAtLevel(1, 0), 1);
  5704. ASSERT_OK(Put(Key(5), ""));
  5705. ASSERT_OK(Flush());
  5706. // Fails because L1 is non-empty.
  5707. status = experimental::PromoteL0(db_, db_->DefaultColumnFamily());
  5708. ASSERT_TRUE(status.IsInvalidArgument());
  5709. }
  5710. // Github issue #596
  5711. TEST_F(DBTest, CompactRangeWithEmptyBottomLevel) {
  5712. const int kNumLevels = 2;
  5713. const int kNumL0Files = 2;
  5714. Options options = CurrentOptions();
  5715. options.disable_auto_compactions = true;
  5716. options.num_levels = kNumLevels;
  5717. DestroyAndReopen(options);
  5718. Random rnd(301);
  5719. for (int i = 0; i < kNumL0Files; ++i) {
  5720. ASSERT_OK(Put(Key(0), rnd.RandomString(1024)));
  5721. ASSERT_OK(Flush());
  5722. }
  5723. ASSERT_EQ(NumTableFilesAtLevel(0), kNumL0Files);
  5724. ASSERT_EQ(NumTableFilesAtLevel(1), 0);
  5725. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  5726. ASSERT_EQ(NumTableFilesAtLevel(0), 0);
  5727. ASSERT_EQ(NumTableFilesAtLevel(1), kNumL0Files);
  5728. }
  5729. TEST_F(DBTest, AutomaticConflictsWithManualCompaction) {
  5730. const int kNumL0Files = 50;
  5731. Options options = CurrentOptions();
  5732. options.level0_file_num_compaction_trigger = 4;
  5733. // never slowdown / stop
  5734. options.level0_slowdown_writes_trigger = 999999;
  5735. options.level0_stop_writes_trigger = 999999;
  5736. options.max_background_compactions = 10;
  5737. DestroyAndReopen(options);
  5738. // schedule automatic compactions after the manual one starts, but before it
  5739. // finishes to ensure conflict.
  5740. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
  5741. {{"DBImpl::BackgroundCompaction:Start",
  5742. "DBTest::AutomaticConflictsWithManualCompaction:PrePuts"},
  5743. {"DBTest::AutomaticConflictsWithManualCompaction:PostPuts",
  5744. "DBImpl::BackgroundCompaction:NonTrivial:AfterRun"}});
  5745. std::atomic<int> callback_count(0);
  5746. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  5747. "DBImpl::MaybeScheduleFlushOrCompaction:Conflict",
  5748. [&](void* /*arg*/) { callback_count.fetch_add(1); });
  5749. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  5750. Random rnd(301);
  5751. for (int i = 0; i < 2; ++i) {
  5752. // put two keys to ensure no trivial move
  5753. for (int j = 0; j < 2; ++j) {
  5754. ASSERT_OK(Put(Key(j), rnd.RandomString(1024)));
  5755. }
  5756. ASSERT_OK(Flush());
  5757. }
  5758. port::Thread manual_compaction_thread([this]() {
  5759. CompactRangeOptions croptions;
  5760. croptions.exclusive_manual_compaction = true;
  5761. ASSERT_OK(db_->CompactRange(croptions, nullptr, nullptr));
  5762. });
  5763. TEST_SYNC_POINT("DBTest::AutomaticConflictsWithManualCompaction:PrePuts");
  5764. for (int i = 0; i < kNumL0Files; ++i) {
  5765. // put two keys to ensure no trivial move
  5766. for (int j = 0; j < 2; ++j) {
  5767. ASSERT_OK(Put(Key(j), rnd.RandomString(1024)));
  5768. }
  5769. ASSERT_OK(Flush());
  5770. }
  5771. TEST_SYNC_POINT("DBTest::AutomaticConflictsWithManualCompaction:PostPuts");
  5772. ASSERT_GE(callback_count.load(), 1);
  5773. for (int i = 0; i < 2; ++i) {
  5774. ASSERT_NE("NOT_FOUND", Get(Key(i)));
  5775. }
  5776. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  5777. manual_compaction_thread.join();
  5778. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  5779. }
  5780. TEST_F(DBTest, CompactFilesShouldTriggerAutoCompaction) {
  5781. Options options = CurrentOptions();
  5782. options.max_background_compactions = 1;
  5783. options.level0_file_num_compaction_trigger = 4;
  5784. options.level0_slowdown_writes_trigger = 36;
  5785. options.level0_stop_writes_trigger = 36;
  5786. DestroyAndReopen(options);
  5787. // generate files for manual compaction
  5788. Random rnd(301);
  5789. for (int i = 0; i < 2; ++i) {
  5790. // put two keys to ensure no trivial move
  5791. for (int j = 0; j < 2; ++j) {
  5792. ASSERT_OK(Put(Key(j), rnd.RandomString(1024)));
  5793. }
  5794. ASSERT_OK(Flush());
  5795. }
  5796. ROCKSDB_NAMESPACE::ColumnFamilyMetaData cf_meta_data;
  5797. db_->GetColumnFamilyMetaData(db_->DefaultColumnFamily(), &cf_meta_data);
  5798. std::vector<std::string> input_files;
  5799. input_files.push_back(cf_meta_data.levels[0].files[0].name);
  5800. SyncPoint::GetInstance()->LoadDependency({
  5801. {"CompactFilesImpl:0",
  5802. "DBTest::CompactFilesShouldTriggerAutoCompaction:Begin"},
  5803. {"DBTest::CompactFilesShouldTriggerAutoCompaction:End",
  5804. "CompactFilesImpl:1"},
  5805. });
  5806. SyncPoint::GetInstance()->EnableProcessing();
  5807. port::Thread manual_compaction_thread([&]() {
  5808. auto s = db_->CompactFiles(CompactionOptions(), db_->DefaultColumnFamily(),
  5809. input_files, 0);
  5810. ASSERT_OK(s);
  5811. });
  5812. TEST_SYNC_POINT("DBTest::CompactFilesShouldTriggerAutoCompaction:Begin");
  5813. // generate enough files to trigger compaction
  5814. for (int i = 0; i < 20; ++i) {
  5815. for (int j = 0; j < 2; ++j) {
  5816. ASSERT_OK(Put(Key(j), rnd.RandomString(1024)));
  5817. }
  5818. ASSERT_OK(Flush());
  5819. }
  5820. db_->GetColumnFamilyMetaData(db_->DefaultColumnFamily(), &cf_meta_data);
  5821. ASSERT_GT(cf_meta_data.levels[0].files.size(),
  5822. options.level0_file_num_compaction_trigger);
  5823. TEST_SYNC_POINT("DBTest::CompactFilesShouldTriggerAutoCompaction:End");
  5824. manual_compaction_thread.join();
  5825. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  5826. db_->GetColumnFamilyMetaData(db_->DefaultColumnFamily(), &cf_meta_data);
  5827. ASSERT_LE(cf_meta_data.levels[0].files.size(),
  5828. options.level0_file_num_compaction_trigger);
  5829. }
  5830. // Github issue #595
  5831. // Large write batch with column families
  5832. TEST_F(DBTest, LargeBatchWithColumnFamilies) {
  5833. Options options = CurrentOptions();
  5834. options.env = env_;
  5835. options.write_buffer_size = 100000; // Small write buffer
  5836. CreateAndReopenWithCF({"pikachu"}, options);
  5837. int64_t j = 0;
  5838. for (int i = 0; i < 5; i++) {
  5839. for (int pass = 1; pass <= 3; pass++) {
  5840. WriteBatch batch;
  5841. size_t write_size = 1024 * 1024 * (5 + i);
  5842. fprintf(stderr, "prepare: %" ROCKSDB_PRIszt " MB, pass:%d\n",
  5843. (write_size / 1024 / 1024), pass);
  5844. for (;;) {
  5845. std::string data(3000, j++ % 127 + 20);
  5846. data += std::to_string(j);
  5847. ASSERT_OK(batch.Put(handles_[0], Slice(data), Slice(data)));
  5848. if (batch.GetDataSize() > write_size) {
  5849. break;
  5850. }
  5851. }
  5852. fprintf(stderr, "write: %" ROCKSDB_PRIszt " MB\n",
  5853. (batch.GetDataSize() / 1024 / 1024));
  5854. ASSERT_OK(dbfull()->Write(WriteOptions(), &batch));
  5855. fprintf(stderr, "done\n");
  5856. }
  5857. }
  5858. // make sure we can re-open it.
  5859. ASSERT_OK(TryReopenWithColumnFamilies({"default", "pikachu"}, options));
  5860. }
  5861. // Make sure that Flushes can proceed in parallel with CompactRange()
  5862. TEST_F(DBTest, FlushesInParallelWithCompactRange) {
  5863. // iter == 0 -- leveled
  5864. // iter == 1 -- leveled, but throw in a flush between two levels compacting
  5865. // iter == 2 -- universal
  5866. for (int iter = 0; iter < 3; ++iter) {
  5867. Options options = CurrentOptions();
  5868. if (iter < 2) {
  5869. options.compaction_style = kCompactionStyleLevel;
  5870. } else {
  5871. options.compaction_style = kCompactionStyleUniversal;
  5872. }
  5873. options.write_buffer_size = 110 << 10;
  5874. options.level0_file_num_compaction_trigger = 4;
  5875. options.num_levels = 4;
  5876. options.compression = kNoCompression;
  5877. options.max_bytes_for_level_base = 450 << 10;
  5878. options.target_file_size_base = 98 << 10;
  5879. options.max_write_buffer_number = 2;
  5880. DestroyAndReopen(options);
  5881. Random rnd(301);
  5882. for (int num = 0; num < 14; num++) {
  5883. GenerateNewRandomFile(&rnd);
  5884. }
  5885. if (iter == 1) {
  5886. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
  5887. {{"DBImpl::RunManualCompaction()::1",
  5888. "DBTest::FlushesInParallelWithCompactRange:1"},
  5889. {"DBTest::FlushesInParallelWithCompactRange:2",
  5890. "DBImpl::RunManualCompaction()::2"}});
  5891. } else {
  5892. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
  5893. {{"CompactionJob::Run():Start",
  5894. "DBTest::FlushesInParallelWithCompactRange:1"},
  5895. {"DBTest::FlushesInParallelWithCompactRange:2",
  5896. "CompactionJob::Run():End"}});
  5897. }
  5898. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  5899. std::vector<port::Thread> threads;
  5900. threads.emplace_back([&]() { Compact("a", "z"); });
  5901. TEST_SYNC_POINT("DBTest::FlushesInParallelWithCompactRange:1");
  5902. // this has to start a flush. if flushes are blocked, this will try to
  5903. // create
  5904. // 3 memtables, and that will fail because max_write_buffer_number is 2
  5905. for (int num = 0; num < 3; num++) {
  5906. GenerateNewRandomFile(&rnd, /* nowait */ true);
  5907. }
  5908. TEST_SYNC_POINT("DBTest::FlushesInParallelWithCompactRange:2");
  5909. for (auto& t : threads) {
  5910. t.join();
  5911. }
  5912. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  5913. }
  5914. }
  5915. TEST_F(DBTest, DelayedWriteRate) {
  5916. const int kEntriesPerMemTable = 100;
  5917. const int kTotalFlushes = 12;
  5918. Options options = CurrentOptions();
  5919. env_->SetBackgroundThreads(1, Env::LOW);
  5920. options.env = env_;
  5921. options.write_buffer_size = 100000000;
  5922. options.max_write_buffer_number = 256;
  5923. options.max_background_compactions = 1;
  5924. options.level0_file_num_compaction_trigger = 3;
  5925. options.level0_slowdown_writes_trigger = 3;
  5926. options.level0_stop_writes_trigger = 999999;
  5927. options.delayed_write_rate = 20000000; // Start with 200MB/s
  5928. options.memtable_factory.reset(
  5929. test::NewSpecialSkipListFactory(kEntriesPerMemTable));
  5930. SetTimeElapseOnlySleepOnReopen(&options);
  5931. CreateAndReopenWithCF({"pikachu"}, options);
  5932. // Block compactions
  5933. test::SleepingBackgroundTask sleeping_task_low;
  5934. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &sleeping_task_low,
  5935. Env::Priority::LOW);
  5936. for (int i = 0; i < 3; i++) {
  5937. ASSERT_OK(Put(Key(i), std::string(10000, 'x')));
  5938. ASSERT_OK(Flush());
  5939. }
  5940. // These writes will be slowed down to 1KB/s
  5941. uint64_t estimated_sleep_time = 0;
  5942. Random rnd(301);
  5943. ASSERT_OK(Put("", ""));
  5944. uint64_t cur_rate = options.delayed_write_rate;
  5945. for (int i = 0; i < kTotalFlushes; i++) {
  5946. uint64_t size_memtable = 0;
  5947. for (int j = 0; j < kEntriesPerMemTable; j++) {
  5948. auto rand_num = rnd.Uniform(20);
  5949. // Spread the size range to more.
  5950. size_t entry_size = rand_num * rand_num * rand_num;
  5951. WriteOptions wo;
  5952. ASSERT_OK(Put(Key(i), std::string(entry_size, 'x'), wo));
  5953. size_memtable += entry_size + 18;
  5954. // Occasionally sleep a while
  5955. if (rnd.Uniform(20) == 6) {
  5956. env_->SleepForMicroseconds(2666);
  5957. }
  5958. }
  5959. ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
  5960. estimated_sleep_time += size_memtable * 1000000u / cur_rate;
  5961. // Slow down twice. One for memtable switch and one for flush finishes.
  5962. cur_rate = static_cast<uint64_t>(static_cast<double>(cur_rate) *
  5963. kIncSlowdownRatio * kIncSlowdownRatio);
  5964. }
  5965. // Estimate the total sleep time fall into the rough range.
  5966. ASSERT_GT(env_->NowMicros(), estimated_sleep_time / 2);
  5967. ASSERT_LT(env_->NowMicros(), estimated_sleep_time * 2);
  5968. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  5969. sleeping_task_low.WakeUp();
  5970. sleeping_task_low.WaitUntilDone();
  5971. }
  5972. TEST_F(DBTest, HardLimit) {
  5973. Options options = CurrentOptions();
  5974. options.env = env_;
  5975. env_->SetBackgroundThreads(1, Env::LOW);
  5976. options.max_write_buffer_number = 256;
  5977. options.write_buffer_size = 110 << 10; // 110KB
  5978. options.arena_block_size = 4 * 1024;
  5979. options.level0_file_num_compaction_trigger = 4;
  5980. options.level0_slowdown_writes_trigger = 999999;
  5981. options.level0_stop_writes_trigger = 999999;
  5982. options.hard_pending_compaction_bytes_limit = 800 << 10;
  5983. options.max_bytes_for_level_base = 10000000000u;
  5984. options.max_background_compactions = 1;
  5985. options.memtable_factory.reset(
  5986. test::NewSpecialSkipListFactory(KNumKeysByGenerateNewFile - 1));
  5987. env_->SetBackgroundThreads(1, Env::LOW);
  5988. test::SleepingBackgroundTask sleeping_task_low;
  5989. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &sleeping_task_low,
  5990. Env::Priority::LOW);
  5991. CreateAndReopenWithCF({"pikachu"}, options);
  5992. std::atomic<int> callback_count(0);
  5993. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  5994. "DBImpl::DelayWrite:Wait", [&](void* /*arg*/) {
  5995. callback_count.fetch_add(1);
  5996. sleeping_task_low.WakeUp();
  5997. });
  5998. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  5999. Random rnd(301);
  6000. int key_idx = 0;
  6001. for (int num = 0; num < 5; num++) {
  6002. GenerateNewFile(&rnd, &key_idx, true);
  6003. ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
  6004. }
  6005. ASSERT_EQ(0, callback_count.load());
  6006. for (int num = 0; num < 5; num++) {
  6007. GenerateNewFile(&rnd, &key_idx, true);
  6008. ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
  6009. }
  6010. ASSERT_GE(callback_count.load(), 1);
  6011. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  6012. sleeping_task_low.WaitUntilDone();
  6013. }
  6014. #if !defined(ROCKSDB_DISABLE_STALL_NOTIFICATION)
  6015. class WriteStallListener : public EventListener {
  6016. public:
  6017. WriteStallListener() : condition_(WriteStallCondition::kNormal) {}
  6018. void OnStallConditionsChanged(const WriteStallInfo& info) override {
  6019. MutexLock l(&mutex_);
  6020. condition_ = info.condition.cur;
  6021. }
  6022. bool CheckCondition(WriteStallCondition expected) {
  6023. MutexLock l(&mutex_);
  6024. return expected == condition_;
  6025. }
  6026. private:
  6027. port::Mutex mutex_;
  6028. WriteStallCondition condition_;
  6029. };
  6030. TEST_F(DBTest, SoftLimit) {
  6031. Options options = CurrentOptions();
  6032. options.env = env_;
  6033. options.write_buffer_size = 100000; // Small write buffer
  6034. options.max_write_buffer_number = 256;
  6035. options.level0_file_num_compaction_trigger = 1;
  6036. options.level0_slowdown_writes_trigger = 3;
  6037. options.level0_stop_writes_trigger = 999999;
  6038. options.delayed_write_rate = 20000; // About 200KB/s limited rate
  6039. options.soft_pending_compaction_bytes_limit = 160000;
  6040. options.target_file_size_base = 99999999; // All into one file
  6041. options.max_bytes_for_level_base = 50000;
  6042. options.max_bytes_for_level_multiplier = 10;
  6043. options.max_background_compactions = 1;
  6044. options.compression = kNoCompression;
  6045. WriteStallListener* listener = new WriteStallListener();
  6046. options.listeners.emplace_back(listener);
  6047. // FlushMemtable with opt.wait=true does not wait for
  6048. // `OnStallConditionsChanged` being called. The event listener is triggered
  6049. // on `JobContext::Clean`, which happens after flush result is installed.
  6050. // We use sync point to create a custom WaitForFlush that waits for
  6051. // context cleanup.
  6052. port::Mutex flush_mutex;
  6053. port::CondVar flush_cv(&flush_mutex);
  6054. bool flush_finished = false;
  6055. auto InstallFlushCallback = [&]() {
  6056. {
  6057. MutexLock l(&flush_mutex);
  6058. flush_finished = false;
  6059. }
  6060. SyncPoint::GetInstance()->SetCallBack(
  6061. "DBImpl::BackgroundCallFlush:ContextCleanedUp", [&](void*) {
  6062. {
  6063. MutexLock l(&flush_mutex);
  6064. flush_finished = true;
  6065. }
  6066. flush_cv.SignalAll();
  6067. });
  6068. };
  6069. auto WaitForFlush = [&]() {
  6070. {
  6071. MutexLock l(&flush_mutex);
  6072. while (!flush_finished) {
  6073. flush_cv.Wait();
  6074. }
  6075. }
  6076. SyncPoint::GetInstance()->ClearCallBack(
  6077. "DBImpl::BackgroundCallFlush:ContextCleanedUp");
  6078. };
  6079. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  6080. Reopen(options);
  6081. // Generating 360KB in Level 3
  6082. for (int i = 0; i < 72; i++) {
  6083. ASSERT_OK(Put(Key(i), std::string(5000, 'x')));
  6084. if (i % 10 == 0) {
  6085. ASSERT_OK(dbfull()->TEST_FlushMemTable(true, true));
  6086. }
  6087. }
  6088. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  6089. MoveFilesToLevel(3);
  6090. // Generating 360KB in Level 2
  6091. for (int i = 0; i < 72; i++) {
  6092. ASSERT_OK(Put(Key(i), std::string(5000, 'x')));
  6093. if (i % 10 == 0) {
  6094. ASSERT_OK(dbfull()->TEST_FlushMemTable(true, true));
  6095. }
  6096. }
  6097. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  6098. MoveFilesToLevel(2);
  6099. ASSERT_OK(Put(Key(0), ""));
  6100. test::SleepingBackgroundTask sleeping_task_low;
  6101. // Block compactions
  6102. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &sleeping_task_low,
  6103. Env::Priority::LOW);
  6104. sleeping_task_low.WaitUntilSleeping();
  6105. // Create 3 L0 files, making score of L0 to be 3.
  6106. for (int i = 0; i < 3; i++) {
  6107. ASSERT_OK(Put(Key(i), std::string(5000, 'x')));
  6108. ASSERT_OK(Put(Key(100 - i), std::string(5000, 'x')));
  6109. // Flush the file. File size is around 30KB.
  6110. InstallFlushCallback();
  6111. ASSERT_OK(dbfull()->TEST_FlushMemTable(true, true));
  6112. WaitForFlush();
  6113. }
  6114. ASSERT_TRUE(dbfull()->TEST_write_controler().NeedsDelay());
  6115. ASSERT_TRUE(listener->CheckCondition(WriteStallCondition::kDelayed));
  6116. sleeping_task_low.WakeUp();
  6117. sleeping_task_low.WaitUntilDone();
  6118. sleeping_task_low.Reset();
  6119. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  6120. // Now there is one L1 file but doesn't trigger soft_rate_limit
  6121. //
  6122. // TODO: soft_rate_limit is depreciated. If this test
  6123. // relies on soft_rate_limit, then we need to change the test.
  6124. //
  6125. // The L1 file size is around 30KB.
  6126. ASSERT_EQ(NumTableFilesAtLevel(1), 1);
  6127. ASSERT_TRUE(!dbfull()->TEST_write_controler().NeedsDelay());
  6128. ASSERT_TRUE(listener->CheckCondition(WriteStallCondition::kNormal));
  6129. // Only allow one compactin going through.
  6130. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  6131. "BackgroundCallCompaction:0", [&](void* /*arg*/) {
  6132. // Schedule a sleeping task.
  6133. sleeping_task_low.Reset();
  6134. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask,
  6135. &sleeping_task_low, Env::Priority::LOW);
  6136. });
  6137. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &sleeping_task_low,
  6138. Env::Priority::LOW);
  6139. sleeping_task_low.WaitUntilSleeping();
  6140. // Create 3 L0 files, making score of L0 to be 3
  6141. for (int i = 0; i < 3; i++) {
  6142. ASSERT_OK(Put(Key(10 + i), std::string(5000, 'x')));
  6143. ASSERT_OK(Put(Key(90 - i), std::string(5000, 'x')));
  6144. // Flush the file. File size is around 30KB.
  6145. InstallFlushCallback();
  6146. ASSERT_OK(dbfull()->TEST_FlushMemTable(true, true));
  6147. WaitForFlush();
  6148. }
  6149. // Wake up sleep task to enable compaction to run and waits
  6150. // for it to go to sleep state again to make sure one compaction
  6151. // goes through.
  6152. sleeping_task_low.WakeUp();
  6153. sleeping_task_low.WaitUntilSleeping();
  6154. // Now there is one L1 file (around 60KB) which exceeds 50KB base by 10KB
  6155. // Given level multiplier 10, estimated pending compaction is around 100KB
  6156. // doesn't trigger soft_pending_compaction_bytes_limit
  6157. ASSERT_EQ(NumTableFilesAtLevel(1), 1);
  6158. ASSERT_TRUE(!dbfull()->TEST_write_controler().NeedsDelay());
  6159. ASSERT_TRUE(listener->CheckCondition(WriteStallCondition::kNormal));
  6160. // Create 3 L0 files, making score of L0 to be 3, higher than L0.
  6161. for (int i = 0; i < 3; i++) {
  6162. ASSERT_OK(Put(Key(20 + i), std::string(5000, 'x')));
  6163. ASSERT_OK(Put(Key(80 - i), std::string(5000, 'x')));
  6164. // Flush the file. File size is around 30KB.
  6165. InstallFlushCallback();
  6166. ASSERT_OK(dbfull()->TEST_FlushMemTable(true, true));
  6167. WaitForFlush();
  6168. }
  6169. // Wake up sleep task to enable compaction to run and waits
  6170. // for it to go to sleep state again to make sure one compaction
  6171. // goes through.
  6172. sleeping_task_low.WakeUp();
  6173. sleeping_task_low.WaitUntilSleeping();
  6174. // Now there is one L1 file (around 90KB) which exceeds 50KB base by 40KB
  6175. // L2 size is 360KB, so the estimated level fanout 4, estimated pending
  6176. // compaction is around 200KB
  6177. // triggerring soft_pending_compaction_bytes_limit
  6178. ASSERT_EQ(NumTableFilesAtLevel(1), 1);
  6179. ASSERT_TRUE(dbfull()->TEST_write_controler().NeedsDelay());
  6180. ASSERT_TRUE(listener->CheckCondition(WriteStallCondition::kDelayed));
  6181. sleeping_task_low.WakeUp();
  6182. sleeping_task_low.WaitUntilSleeping();
  6183. ASSERT_TRUE(!dbfull()->TEST_write_controler().NeedsDelay());
  6184. ASSERT_TRUE(listener->CheckCondition(WriteStallCondition::kNormal));
  6185. // shrink level base so L2 will hit soft limit easier.
  6186. ASSERT_OK(dbfull()->SetOptions({
  6187. {"max_bytes_for_level_base", "5000"},
  6188. }));
  6189. ASSERT_OK(Put("", ""));
  6190. ASSERT_OK(Flush());
  6191. ASSERT_TRUE(dbfull()->TEST_write_controler().NeedsDelay());
  6192. ASSERT_TRUE(listener->CheckCondition(WriteStallCondition::kDelayed));
  6193. sleeping_task_low.WaitUntilSleeping();
  6194. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  6195. sleeping_task_low.WakeUp();
  6196. sleeping_task_low.WaitUntilDone();
  6197. }
  6198. TEST_F(DBTest, LastWriteBufferDelay) {
  6199. Options options = CurrentOptions();
  6200. options.env = env_;
  6201. options.write_buffer_size = 100000;
  6202. options.max_write_buffer_number = 4;
  6203. options.delayed_write_rate = 20000;
  6204. options.compression = kNoCompression;
  6205. options.disable_auto_compactions = true;
  6206. int kNumKeysPerMemtable = 3;
  6207. options.memtable_factory.reset(
  6208. test::NewSpecialSkipListFactory(kNumKeysPerMemtable));
  6209. Reopen(options);
  6210. test::SleepingBackgroundTask sleeping_task;
  6211. // Block flushes
  6212. env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &sleeping_task,
  6213. Env::Priority::HIGH);
  6214. sleeping_task.WaitUntilSleeping();
  6215. // Create 3 L0 files, making score of L0 to be 3.
  6216. for (int i = 0; i < 3; i++) {
  6217. // Fill one mem table
  6218. for (int j = 0; j < kNumKeysPerMemtable; j++) {
  6219. ASSERT_OK(Put(Key(j), ""));
  6220. }
  6221. ASSERT_TRUE(!dbfull()->TEST_write_controler().NeedsDelay());
  6222. }
  6223. // Inserting a new entry would create a new mem table, triggering slow down.
  6224. ASSERT_OK(Put(Key(0), ""));
  6225. ASSERT_TRUE(dbfull()->TEST_write_controler().NeedsDelay());
  6226. sleeping_task.WakeUp();
  6227. sleeping_task.WaitUntilDone();
  6228. }
  6229. #endif // !defined(ROCKSDB_DISABLE_STALL_NOTIFICATION)
  6230. TEST_F(DBTest, CreateColumnFamilyShouldFailOnIncompatibleOptions) {
  6231. Options options = CurrentOptions();
  6232. options.max_open_files = 100;
  6233. Reopen(options);
  6234. ColumnFamilyOptions cf_options(options);
  6235. // ttl is now supported when max_open_files is -1.
  6236. cf_options.ttl = 3600;
  6237. ColumnFamilyHandle* handle;
  6238. ASSERT_OK(db_->CreateColumnFamily(cf_options, "pikachu", &handle));
  6239. delete handle;
  6240. }
  6241. TEST_F(DBTest, RowCache) {
  6242. Options options = CurrentOptions();
  6243. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  6244. LRUCacheOptions cache_options;
  6245. cache_options.capacity = 8192;
  6246. options.row_cache = cache_options.MakeSharedRowCache();
  6247. // BEGIN check that Cache classes as aliases of each other.
  6248. // Currently, RowCache and BlockCache are aliases for Cache.
  6249. // This is expected to change (carefully, intentionally)
  6250. std::shared_ptr<RowCache> row_cache = options.row_cache;
  6251. std::shared_ptr<Cache> cache = row_cache;
  6252. std::shared_ptr<BlockCache> block_cache = row_cache;
  6253. row_cache = cache;
  6254. block_cache = cache;
  6255. row_cache = block_cache;
  6256. cache = block_cache;
  6257. // END check that Cache classes as aliases of each other.
  6258. DestroyAndReopen(options);
  6259. ASSERT_OK(Put("foo", "bar"));
  6260. ASSERT_OK(Flush());
  6261. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), 0);
  6262. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 0);
  6263. ASSERT_EQ(Get("foo"), "bar");
  6264. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), 0);
  6265. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 1);
  6266. ASSERT_EQ(Get("foo"), "bar");
  6267. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), 1);
  6268. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 1);
  6269. // Also test non-OK cache insertion (would be ASAN failure on memory leak)
  6270. class FailInsertionCache : public CacheWrapper {
  6271. public:
  6272. using CacheWrapper::CacheWrapper;
  6273. const char* Name() const override { return "FailInsertionCache"; }
  6274. Status Insert(const Slice&, Cache::ObjectPtr, const CacheItemHelper*,
  6275. size_t, Handle** = nullptr, Priority = Priority::LOW,
  6276. const Slice& /*compressed*/ = Slice(),
  6277. CompressionType /*type*/ = kNoCompression) override {
  6278. return Status::MemoryLimit();
  6279. }
  6280. };
  6281. options.row_cache = std::make_shared<FailInsertionCache>(options.row_cache);
  6282. ASSERT_OK(options.statistics->Reset());
  6283. Reopen(options);
  6284. ASSERT_EQ(Get("foo"), "bar");
  6285. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 1);
  6286. ASSERT_EQ(Get("foo"), "bar");
  6287. // Test condition requires row cache insertion to fail
  6288. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 2);
  6289. }
  6290. TEST_F(DBTest, PinnableSliceAndRowCache) {
  6291. Options options = CurrentOptions();
  6292. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  6293. options.row_cache = NewLRUCache(8192);
  6294. DestroyAndReopen(options);
  6295. ASSERT_OK(Put("foo", "bar"));
  6296. ASSERT_OK(Flush());
  6297. ASSERT_EQ(Get("foo"), "bar");
  6298. ASSERT_EQ(static_cast<LRUCache*>(options.row_cache.get())->TEST_GetLRUSize(),
  6299. 1);
  6300. {
  6301. PinnableSlice pin_slice;
  6302. ASSERT_EQ(Get("foo", &pin_slice), Status::OK());
  6303. ASSERT_EQ(pin_slice.ToString(), "bar");
  6304. // Entry is already in cache, lookup will remove the element from lru
  6305. ASSERT_EQ(
  6306. static_cast<LRUCache*>(options.row_cache.get())->TEST_GetLRUSize(), 0);
  6307. }
  6308. // After PinnableSlice destruction element is added back in LRU
  6309. ASSERT_EQ(static_cast<LRUCache*>(options.row_cache.get())->TEST_GetLRUSize(),
  6310. 1);
  6311. }
  6312. TEST_F(DBTest, ReusePinnableSlice) {
  6313. Options options = CurrentOptions();
  6314. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  6315. options.row_cache = NewLRUCache(8192);
  6316. DestroyAndReopen(options);
  6317. ASSERT_OK(Put("foo", "bar"));
  6318. ASSERT_OK(Flush());
  6319. ASSERT_EQ(Get("foo"), "bar");
  6320. ASSERT_EQ(static_cast<LRUCache*>(options.row_cache.get())->TEST_GetLRUSize(),
  6321. 1);
  6322. {
  6323. PinnableSlice pin_slice;
  6324. ASSERT_EQ(Get("foo", &pin_slice), Status::OK());
  6325. ASSERT_EQ(Get("foo", &pin_slice), Status::OK());
  6326. ASSERT_EQ(pin_slice.ToString(), "bar");
  6327. // Entry is already in cache, lookup will remove the element from lru
  6328. ASSERT_EQ(
  6329. static_cast<LRUCache*>(options.row_cache.get())->TEST_GetLRUSize(), 0);
  6330. }
  6331. // After PinnableSlice destruction element is added back in LRU
  6332. ASSERT_EQ(static_cast<LRUCache*>(options.row_cache.get())->TEST_GetLRUSize(),
  6333. 1);
  6334. {
  6335. std::vector<Slice> multiget_keys;
  6336. multiget_keys.emplace_back("foo");
  6337. std::vector<PinnableSlice> multiget_values(1);
  6338. std::vector<Status> statuses({Status::NotFound()});
  6339. ReadOptions ropt;
  6340. dbfull()->MultiGet(ropt, dbfull()->DefaultColumnFamily(),
  6341. multiget_keys.size(), multiget_keys.data(),
  6342. multiget_values.data(), statuses.data());
  6343. ASSERT_EQ(Status::OK(), statuses[0]);
  6344. dbfull()->MultiGet(ropt, dbfull()->DefaultColumnFamily(),
  6345. multiget_keys.size(), multiget_keys.data(),
  6346. multiget_values.data(), statuses.data());
  6347. ASSERT_EQ(Status::OK(), statuses[0]);
  6348. // Entry is already in cache, lookup will remove the element from lru
  6349. ASSERT_EQ(
  6350. static_cast<LRUCache*>(options.row_cache.get())->TEST_GetLRUSize(), 0);
  6351. }
  6352. // After PinnableSlice destruction element is added back in LRU
  6353. ASSERT_EQ(static_cast<LRUCache*>(options.row_cache.get())->TEST_GetLRUSize(),
  6354. 1);
  6355. {
  6356. std::vector<ColumnFamilyHandle*> multiget_cfs;
  6357. multiget_cfs.push_back(dbfull()->DefaultColumnFamily());
  6358. std::vector<Slice> multiget_keys;
  6359. multiget_keys.emplace_back("foo");
  6360. std::vector<PinnableSlice> multiget_values(1);
  6361. std::vector<Status> statuses({Status::NotFound()});
  6362. ReadOptions ropt;
  6363. dbfull()->MultiGet(ropt, multiget_keys.size(), multiget_cfs.data(),
  6364. multiget_keys.data(), multiget_values.data(),
  6365. statuses.data());
  6366. ASSERT_EQ(Status::OK(), statuses[0]);
  6367. dbfull()->MultiGet(ropt, multiget_keys.size(), multiget_cfs.data(),
  6368. multiget_keys.data(), multiget_values.data(),
  6369. statuses.data());
  6370. ASSERT_EQ(Status::OK(), statuses[0]);
  6371. // Entry is already in cache, lookup will remove the element from lru
  6372. ASSERT_EQ(
  6373. static_cast<LRUCache*>(options.row_cache.get())->TEST_GetLRUSize(), 0);
  6374. }
  6375. // After PinnableSlice destruction element is added back in LRU
  6376. ASSERT_EQ(static_cast<LRUCache*>(options.row_cache.get())->TEST_GetLRUSize(),
  6377. 1);
  6378. }
  6379. TEST_F(DBTest, DeletingOldWalAfterDrop) {
  6380. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
  6381. {{"Test:AllowFlushes", "DBImpl::BGWorkFlush"},
  6382. {"DBImpl::BGWorkFlush:done", "Test:WaitForFlush"}});
  6383. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearTrace();
  6384. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  6385. Options options = CurrentOptions();
  6386. options.max_total_wal_size = 8192;
  6387. options.compression = kNoCompression;
  6388. options.write_buffer_size = 1 << 20;
  6389. options.level0_file_num_compaction_trigger = (1 << 30);
  6390. options.level0_slowdown_writes_trigger = (1 << 30);
  6391. options.level0_stop_writes_trigger = (1 << 30);
  6392. options.disable_auto_compactions = true;
  6393. DestroyAndReopen(options);
  6394. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  6395. CreateColumnFamilies({"cf1", "cf2"}, options);
  6396. ASSERT_OK(Put(0, "key1", DummyString(8192)));
  6397. ASSERT_OK(Put(0, "key2", DummyString(8192)));
  6398. // the oldest wal should now be getting_flushed
  6399. ASSERT_OK(db_->DropColumnFamily(handles_[0]));
  6400. // all flushes should now do nothing because their CF is dropped
  6401. TEST_SYNC_POINT("Test:AllowFlushes");
  6402. TEST_SYNC_POINT("Test:WaitForFlush");
  6403. uint64_t lognum1 = dbfull()->TEST_LogfileNumber();
  6404. ASSERT_OK(Put(1, "key3", DummyString(8192)));
  6405. ASSERT_OK(Put(1, "key4", DummyString(8192)));
  6406. // new wal should have been created
  6407. uint64_t lognum2 = dbfull()->TEST_LogfileNumber();
  6408. EXPECT_GT(lognum2, lognum1);
  6409. }
  6410. TEST_F(DBTest, UnsupportedManualSync) {
  6411. DestroyAndReopen(CurrentOptions());
  6412. env_->is_wal_sync_thread_safe_.store(false);
  6413. Status s = db_->SyncWAL();
  6414. ASSERT_TRUE(s.IsNotSupported());
  6415. }
  6416. INSTANTIATE_TEST_CASE_P(DBTestWithParam, DBTestWithParam,
  6417. ::testing::Combine(::testing::Values(1, 4),
  6418. ::testing::Bool()));
  6419. TEST_F(DBTest, PauseBackgroundWorkTest) {
  6420. Options options = CurrentOptions();
  6421. options.write_buffer_size = 100000; // Small write buffer
  6422. Reopen(options);
  6423. std::vector<port::Thread> threads;
  6424. std::atomic<bool> done(false);
  6425. ASSERT_OK(db_->PauseBackgroundWork());
  6426. threads.emplace_back([&]() {
  6427. Random rnd(301);
  6428. for (int i = 0; i < 10000; ++i) {
  6429. ASSERT_OK(Put(rnd.RandomString(10), rnd.RandomString(10)));
  6430. }
  6431. done.store(true);
  6432. });
  6433. env_->SleepForMicroseconds(200000);
  6434. // make sure the thread is not done
  6435. ASSERT_FALSE(done.load());
  6436. ASSERT_OK(db_->ContinueBackgroundWork());
  6437. for (auto& t : threads) {
  6438. t.join();
  6439. }
  6440. // now it's done
  6441. ASSERT_TRUE(done.load());
  6442. }
  6443. // Keep spawning short-living threads that create an iterator and quit.
  6444. // Meanwhile in another thread keep flushing memtables.
  6445. // This used to cause a deadlock.
  6446. TEST_F(DBTest, ThreadLocalPtrDeadlock) {
  6447. std::atomic<int> flushes_done{0};
  6448. std::atomic<int> threads_destroyed{0};
  6449. auto done = [&] { return flushes_done.load() > 10; };
  6450. port::Thread flushing_thread([&] {
  6451. for (int i = 0; !done(); ++i) {
  6452. ASSERT_OK(db_->Put(WriteOptions(), Slice("hi"),
  6453. Slice(std::to_string(i).c_str())));
  6454. ASSERT_OK(db_->Flush(FlushOptions()));
  6455. int cnt = ++flushes_done;
  6456. fprintf(stderr, "Flushed %d times\n", cnt);
  6457. }
  6458. });
  6459. std::vector<port::Thread> thread_spawning_threads(10);
  6460. for (auto& t : thread_spawning_threads) {
  6461. t = port::Thread([&] {
  6462. while (!done()) {
  6463. {
  6464. port::Thread tmp_thread([&] {
  6465. auto it = db_->NewIterator(ReadOptions());
  6466. ASSERT_OK(it->status());
  6467. delete it;
  6468. });
  6469. tmp_thread.join();
  6470. }
  6471. ++threads_destroyed;
  6472. }
  6473. });
  6474. }
  6475. for (auto& t : thread_spawning_threads) {
  6476. t.join();
  6477. }
  6478. flushing_thread.join();
  6479. fprintf(stderr, "Done. Flushed %d times, destroyed %d threads\n",
  6480. flushes_done.load(), threads_destroyed.load());
  6481. }
  6482. TEST_F(DBTest, LargeBlockSizeTest) {
  6483. Options options = CurrentOptions();
  6484. CreateAndReopenWithCF({"pikachu"}, options);
  6485. ASSERT_OK(Put(0, "foo", "bar"));
  6486. BlockBasedTableOptions table_options;
  6487. table_options.block_size = 8LL * 1024 * 1024 * 1024LL;
  6488. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  6489. ASSERT_NOK(TryReopenWithColumnFamilies({"default", "pikachu"}, options));
  6490. }
  6491. TEST_F(DBTest, CreationTimeOfOldestFile) {
  6492. const int kNumKeysPerFile = 32;
  6493. const int kNumLevelFiles = 2;
  6494. const int kValueSize = 100;
  6495. Options options = CurrentOptions();
  6496. options.max_open_files = -1;
  6497. env_->SetMockSleep();
  6498. options.env = env_;
  6499. // NOTE: Presumed unnecessary and removed: resetting mock time in env
  6500. DestroyAndReopen(options);
  6501. bool set_file_creation_time_to_zero = true;
  6502. int idx = 0;
  6503. int64_t time_1 = 0;
  6504. ASSERT_OK(env_->GetCurrentTime(&time_1));
  6505. const uint64_t uint_time_1 = static_cast<uint64_t>(time_1);
  6506. // Add 50 hours
  6507. env_->MockSleepForSeconds(50 * 60 * 60);
  6508. int64_t time_2 = 0;
  6509. ASSERT_OK(env_->GetCurrentTime(&time_2));
  6510. const uint64_t uint_time_2 = static_cast<uint64_t>(time_2);
  6511. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  6512. "PropertyBlockBuilder::AddTableProperty:Start", [&](void* arg) {
  6513. TableProperties* props = static_cast<TableProperties*>(arg);
  6514. if (set_file_creation_time_to_zero) {
  6515. if (idx == 0) {
  6516. props->file_creation_time = 0;
  6517. idx++;
  6518. } else if (idx == 1) {
  6519. props->file_creation_time = uint_time_1;
  6520. idx = 0;
  6521. }
  6522. } else {
  6523. if (idx == 0) {
  6524. props->file_creation_time = uint_time_1;
  6525. idx++;
  6526. } else if (idx == 1) {
  6527. props->file_creation_time = uint_time_2;
  6528. }
  6529. }
  6530. });
  6531. // Set file creation time in manifest all to 0.
  6532. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  6533. "FileMetaData::FileMetaData", [&](void* arg) {
  6534. FileMetaData* meta = static_cast<FileMetaData*>(arg);
  6535. meta->file_creation_time = 0;
  6536. });
  6537. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  6538. Random rnd(301);
  6539. for (int i = 0; i < kNumLevelFiles; ++i) {
  6540. for (int j = 0; j < kNumKeysPerFile; ++j) {
  6541. ASSERT_OK(
  6542. Put(Key(i * kNumKeysPerFile + j), rnd.RandomString(kValueSize)));
  6543. }
  6544. ASSERT_OK(Flush());
  6545. }
  6546. // At this point there should be 2 files, one with file_creation_time = 0 and
  6547. // the other non-zero. GetCreationTimeOfOldestFile API should return 0.
  6548. uint64_t creation_time;
  6549. Status s1 = dbfull()->GetCreationTimeOfOldestFile(&creation_time);
  6550. ASSERT_EQ(0, creation_time);
  6551. ASSERT_EQ(s1, Status::OK());
  6552. // Testing with non-zero file creation time.
  6553. set_file_creation_time_to_zero = false;
  6554. options = CurrentOptions();
  6555. options.max_open_files = -1;
  6556. options.env = env_;
  6557. // NOTE: Presumed unnecessary and removed: resetting mock time in env
  6558. DestroyAndReopen(options);
  6559. for (int i = 0; i < kNumLevelFiles; ++i) {
  6560. for (int j = 0; j < kNumKeysPerFile; ++j) {
  6561. ASSERT_OK(
  6562. Put(Key(i * kNumKeysPerFile + j), rnd.RandomString(kValueSize)));
  6563. }
  6564. ASSERT_OK(Flush());
  6565. }
  6566. // At this point there should be 2 files with non-zero file creation time.
  6567. // GetCreationTimeOfOldestFile API should return non-zero value.
  6568. uint64_t ctime;
  6569. Status s2 = dbfull()->GetCreationTimeOfOldestFile(&ctime);
  6570. ASSERT_EQ(uint_time_1, ctime);
  6571. ASSERT_EQ(s2, Status::OK());
  6572. // Testing with max_open_files != -1
  6573. options = CurrentOptions();
  6574. options.max_open_files = 10;
  6575. DestroyAndReopen(options);
  6576. Status s3 = dbfull()->GetCreationTimeOfOldestFile(&ctime);
  6577. ASSERT_EQ(s3, Status::NotSupported());
  6578. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  6579. }
  6580. TEST_F(DBTest, MemoryUsageWithMaxWriteBufferSizeToMaintain) {
  6581. Options options = CurrentOptions();
  6582. options.max_write_buffer_size_to_maintain = 10000;
  6583. options.write_buffer_size = 160000;
  6584. Reopen(options);
  6585. Random rnd(301);
  6586. bool memory_limit_exceeded = false;
  6587. ColumnFamilyData* cfd =
  6588. static_cast<ColumnFamilyHandleImpl*>(db_->DefaultColumnFamily())->cfd();
  6589. for (int i = 0; i < 1000; i++) {
  6590. std::string value = rnd.RandomString(1000);
  6591. ASSERT_OK(Put("keykey_" + std::to_string(i), value));
  6592. ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
  6593. const uint64_t cur_active_mem = cfd->mem()->ApproximateMemoryUsage();
  6594. const uint64_t size_all_mem_table =
  6595. cur_active_mem + cfd->imm()->ApproximateMemoryUsage();
  6596. // Errors out if memory usage keeps on increasing beyond the limit.
  6597. // Once memory limit exceeds, memory_limit_exceeded is set and if
  6598. // size_all_mem_table doesn't drop out in the next write then it errors out
  6599. // (not expected behaviour). If memory usage drops then
  6600. // memory_limit_exceeded is set to false.
  6601. if ((size_all_mem_table > cur_active_mem) &&
  6602. (cur_active_mem >=
  6603. static_cast<uint64_t>(options.max_write_buffer_size_to_maintain)) &&
  6604. (size_all_mem_table >
  6605. static_cast<uint64_t>(options.max_write_buffer_size_to_maintain) +
  6606. options.write_buffer_size)) {
  6607. ASSERT_FALSE(memory_limit_exceeded);
  6608. memory_limit_exceeded = true;
  6609. } else {
  6610. memory_limit_exceeded = false;
  6611. }
  6612. }
  6613. }
  6614. TEST_F(DBTest, ShuttingDownNotBlockStalledWrites) {
  6615. Options options = CurrentOptions();
  6616. options.disable_auto_compactions = true;
  6617. Reopen(options);
  6618. Random rnd(403);
  6619. for (int i = 0; i < 20; i++) {
  6620. ASSERT_OK(Put("key_" + std::to_string(i), rnd.RandomString(10)));
  6621. ASSERT_OK(Flush());
  6622. }
  6623. ASSERT_EQ(GetSstFileCount(dbname_), 20);
  6624. // We need !disable_auto_compactions for writes to stall but also want to
  6625. // delay compaction so stalled writes unblocked due to kShutdownInProgress. BG
  6626. // compaction will first wait for the sync point
  6627. // DBTest::ShuttingDownNotBlockStalledWrites. Then it waits extra 2 sec to
  6628. // allow CancelAllBackgroundWork() to set shutting_down_.
  6629. SyncPoint::GetInstance()->SetCallBack(
  6630. "BackgroundCallCompaction:0",
  6631. [&](void* /* arg */) { env_->SleepForMicroseconds(2 * 1000 * 1000); });
  6632. SyncPoint::GetInstance()->LoadDependency(
  6633. {{"DBImpl::DelayWrite:Wait", "DBTest::ShuttingDownNotBlockStalledWrites"},
  6634. {"DBTest::ShuttingDownNotBlockStalledWrites",
  6635. "BackgroundCallCompaction:0"}});
  6636. SyncPoint::GetInstance()->EnableProcessing();
  6637. options.level0_stop_writes_trigger = 20;
  6638. options.disable_auto_compactions = false;
  6639. Reopen(options);
  6640. std::thread thd([&]() {
  6641. Status s = Put("key_" + std::to_string(101), "101");
  6642. ASSERT_EQ(s.code(), Status::kShutdownInProgress);
  6643. });
  6644. TEST_SYNC_POINT("DBTest::ShuttingDownNotBlockStalledWrites");
  6645. CancelAllBackgroundWork(db_, true);
  6646. thd.join();
  6647. }
  6648. } // namespace ROCKSDB_NAMESPACE
  6649. int main(int argc, char** argv) {
  6650. ROCKSDB_NAMESPACE::port::InstallStackTraceHandler();
  6651. ::testing::InitGoogleTest(&argc, argv);
  6652. RegisterCustomObjects(argc, argv);
  6653. return RUN_ALL_TESTS();
  6654. }