table_test.cc 352 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  7. // Use of this source code is governed by a BSD-style license that can be
  8. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  9. #include "rocksdb/table.h"
  10. #include <gtest/gtest.h>
  11. #include <algorithm>
  12. #include <cstddef>
  13. #include <cstdio>
  14. #include <iomanip>
  15. #include <iostream>
  16. #include <map>
  17. #include <memory>
  18. #include <string>
  19. #include <unordered_set>
  20. #include <vector>
  21. #include "cache/lru_cache.h"
  22. #include "db/db_test_util.h"
  23. #include "db/dbformat.h"
  24. #include "db/memtable.h"
  25. #include "db/write_batch_internal.h"
  26. #include "memtable/stl_wrappers.h"
  27. #include "monitoring/statistics_impl.h"
  28. #include "options/cf_options.h"
  29. #include "options/options_helper.h"
  30. #include "port/port.h"
  31. #include "port/stack_trace.h"
  32. #include "rocksdb/cache.h"
  33. #include "rocksdb/compression_type.h"
  34. #include "rocksdb/convenience.h"
  35. #include "rocksdb/db.h"
  36. #include "rocksdb/env.h"
  37. #include "rocksdb/external_table.h"
  38. #include "rocksdb/file_checksum.h"
  39. #include "rocksdb/file_system.h"
  40. #include "rocksdb/filter_policy.h"
  41. #include "rocksdb/iterator.h"
  42. #include "rocksdb/memtablerep.h"
  43. #include "rocksdb/options.h"
  44. #include "rocksdb/perf_context.h"
  45. #include "rocksdb/slice_transform.h"
  46. #include "rocksdb/sst_file_reader.h"
  47. #include "rocksdb/statistics.h"
  48. #include "rocksdb/table_properties.h"
  49. #include "rocksdb/trace_record.h"
  50. #include "rocksdb/unique_id.h"
  51. #include "rocksdb/user_defined_index.h"
  52. #include "rocksdb/utilities/object_registry.h"
  53. #include "rocksdb/write_buffer_manager.h"
  54. #include "table/block_based/block.h"
  55. #include "table/block_based/block_based_table_builder.h"
  56. #include "table/block_based/block_based_table_factory.h"
  57. #include "table/block_based/block_based_table_iterator.h"
  58. #include "table/block_based/block_based_table_reader.h"
  59. #include "table/block_based/block_builder.h"
  60. #include "table/block_based/filter_policy_internal.h"
  61. #include "table/block_based/flush_block_policy_impl.h"
  62. #include "table/block_fetcher.h"
  63. #include "table/format.h"
  64. #include "table/get_context.h"
  65. #include "table/internal_iterator.h"
  66. #include "table/meta_blocks.h"
  67. #include "table/plain/plain_table_factory.h"
  68. #include "table/sst_file_writer_collectors.h"
  69. #include "table/unique_id_impl.h"
  70. #include "test_util/sync_point.h"
  71. #include "test_util/testharness.h"
  72. #include "test_util/testutil.h"
  73. #include "util/coding.h"
  74. #include "util/compression.h"
  75. #include "util/file_checksum_helper.h"
  76. #include "util/random.h"
  77. #include "util/string_util.h"
  78. #include "utilities/memory_allocators.h"
  79. #include "utilities/merge_operators.h"
  80. namespace ROCKSDB_NAMESPACE {
  81. namespace {
  82. const std::string kDummyValue(10000, 'o');
  83. constexpr auto kVerbose = false;
  84. // DummyPropertiesCollector used to test BlockBasedTableProperties
  85. class DummyPropertiesCollector : public TablePropertiesCollector {
  86. public:
  87. const char* Name() const override { return "DummyPropertiesCollector"; }
  88. Status Finish(UserCollectedProperties* /*properties*/) override {
  89. return Status::OK();
  90. }
  91. Status Add(const Slice& /*user_key*/, const Slice& /*value*/) override {
  92. return Status::OK();
  93. }
  94. UserCollectedProperties GetReadableProperties() const override {
  95. return UserCollectedProperties{};
  96. }
  97. };
  98. class DummyPropertiesCollectorFactory1
  99. : public TablePropertiesCollectorFactory {
  100. public:
  101. TablePropertiesCollector* CreateTablePropertiesCollector(
  102. TablePropertiesCollectorFactory::Context /*context*/) override {
  103. return new DummyPropertiesCollector();
  104. }
  105. const char* Name() const override {
  106. return "DummyPropertiesCollectorFactory1";
  107. }
  108. };
  109. class DummyPropertiesCollectorFactory2
  110. : public TablePropertiesCollectorFactory {
  111. public:
  112. TablePropertiesCollector* CreateTablePropertiesCollector(
  113. TablePropertiesCollectorFactory::Context /*context*/) override {
  114. return new DummyPropertiesCollector();
  115. }
  116. const char* Name() const override {
  117. return "DummyPropertiesCollectorFactory2";
  118. }
  119. };
  120. // Return reverse of "key".
  121. // Used to test non-lexicographic comparators.
  122. std::string Reverse(const Slice& key) {
  123. auto rev = key.ToString();
  124. std::reverse(rev.begin(), rev.end());
  125. return rev;
  126. }
  127. class ReverseKeyComparator : public Comparator {
  128. public:
  129. const char* Name() const override {
  130. return "rocksdb.ReverseBytewiseComparator";
  131. }
  132. int Compare(const Slice& a, const Slice& b) const override {
  133. return BytewiseComparator()->Compare(Reverse(a), Reverse(b));
  134. }
  135. void FindShortestSeparator(std::string* start,
  136. const Slice& limit) const override {
  137. std::string s = Reverse(*start);
  138. std::string l = Reverse(limit);
  139. BytewiseComparator()->FindShortestSeparator(&s, l);
  140. *start = Reverse(s);
  141. }
  142. void FindShortSuccessor(std::string* key) const override {
  143. std::string s = Reverse(*key);
  144. BytewiseComparator()->FindShortSuccessor(&s);
  145. *key = Reverse(s);
  146. }
  147. };
  148. ReverseKeyComparator reverse_key_comparator;
  149. void Increment(const Comparator* cmp, std::string* key) {
  150. if (cmp == BytewiseComparator()) {
  151. key->push_back('\0');
  152. } else {
  153. assert(cmp == &reverse_key_comparator);
  154. std::string rev = Reverse(*key);
  155. rev.push_back('\0');
  156. *key = Reverse(rev);
  157. }
  158. }
  159. const auto kUnknownColumnFamily =
  160. TablePropertiesCollectorFactory::Context::kUnknownColumnFamily;
  161. } // namespace
  162. // Helper class for tests to unify the interface between
  163. // BlockBuilder/TableBuilder and Block/Table.
  164. class Constructor {
  165. public:
  166. explicit Constructor(const Comparator* cmp)
  167. : data_(stl_wrappers::LessOfComparator(cmp)) {}
  168. virtual ~Constructor() = default;
  169. void Add(const std::string& key, const Slice& value) {
  170. data_[key] = value.ToString();
  171. }
  172. // Finish constructing the data structure with all the keys that have
  173. // been added so far. Returns the keys in sorted order in "*keys"
  174. // and stores the key/value pairs in "*kvmap"
  175. void Finish(const Options& options, const ImmutableOptions& ioptions,
  176. const MutableCFOptions& moptions,
  177. const BlockBasedTableOptions& table_options,
  178. const InternalKeyComparator& internal_comparator,
  179. std::vector<std::string>* keys, stl_wrappers::KVMap* kvmap) {
  180. last_internal_comparator_ = &internal_comparator;
  181. *kvmap = data_;
  182. keys->clear();
  183. for (const auto& kv : data_) {
  184. keys->push_back(kv.first);
  185. }
  186. data_.clear();
  187. Status s = FinishImpl(options, ioptions, moptions, table_options,
  188. internal_comparator, *kvmap);
  189. ASSERT_TRUE(s.ok()) << s.ToString();
  190. }
  191. // Construct the data structure from the data in "data"
  192. virtual Status FinishImpl(const Options& options,
  193. const ImmutableOptions& ioptions,
  194. const MutableCFOptions& moptions,
  195. const BlockBasedTableOptions& table_options,
  196. const InternalKeyComparator& internal_comparator,
  197. const stl_wrappers::KVMap& data) = 0;
  198. virtual InternalIterator* NewIterator(
  199. const SliceTransform* prefix_extractor = nullptr) const = 0;
  200. virtual const stl_wrappers::KVMap& data() { return data_; }
  201. virtual bool IsArenaMode() const { return false; }
  202. virtual DB* db() const { return nullptr; } // Overridden in DBConstructor
  203. virtual bool AnywayDeleteIterator() const { return false; }
  204. protected:
  205. const InternalKeyComparator* last_internal_comparator_;
  206. private:
  207. stl_wrappers::KVMap data_;
  208. };
  209. // A helper class that converts internal format keys into user keys
  210. class KeyConvertingIterator : public InternalIterator {
  211. public:
  212. explicit KeyConvertingIterator(InternalIterator* iter,
  213. bool arena_mode = false)
  214. : iter_(iter), arena_mode_(arena_mode) {}
  215. ~KeyConvertingIterator() override {
  216. if (arena_mode_) {
  217. iter_->~InternalIterator();
  218. } else {
  219. delete iter_;
  220. }
  221. }
  222. bool Valid() const override { return iter_->Valid() && status_.ok(); }
  223. void Seek(const Slice& target) override {
  224. ParsedInternalKey ikey(target, kMaxSequenceNumber, kTypeValue);
  225. std::string encoded;
  226. AppendInternalKey(&encoded, ikey);
  227. iter_->Seek(encoded);
  228. }
  229. void SeekForPrev(const Slice& target) override {
  230. ParsedInternalKey ikey(target, kMaxSequenceNumber, kTypeValue);
  231. std::string encoded;
  232. AppendInternalKey(&encoded, ikey);
  233. iter_->SeekForPrev(encoded);
  234. }
  235. void SeekToFirst() override { iter_->SeekToFirst(); }
  236. void SeekToLast() override { iter_->SeekToLast(); }
  237. void Next() override { iter_->Next(); }
  238. void Prev() override { iter_->Prev(); }
  239. IterBoundCheck UpperBoundCheckResult() override {
  240. return iter_->UpperBoundCheckResult();
  241. }
  242. Slice key() const override {
  243. assert(Valid());
  244. ParsedInternalKey parsed_key;
  245. Status pik_status =
  246. ParseInternalKey(iter_->key(), &parsed_key, true /* log_err_key */);
  247. if (!pik_status.ok()) {
  248. status_ = pik_status;
  249. return Slice(status_.getState());
  250. }
  251. return parsed_key.user_key;
  252. }
  253. Slice value() const override { return iter_->value(); }
  254. Status status() const override {
  255. return status_.ok() ? iter_->status() : status_;
  256. }
  257. private:
  258. mutable Status status_;
  259. InternalIterator* iter_;
  260. bool arena_mode_;
  261. // No copying allowed
  262. KeyConvertingIterator(const KeyConvertingIterator&) = delete;
  263. void operator=(const KeyConvertingIterator&) = delete;
  264. };
  265. // `BlockConstructor` APIs always accept/return user keys.
  266. class BlockConstructor : public Constructor {
  267. public:
  268. explicit BlockConstructor(const Comparator* cmp)
  269. : Constructor(cmp), comparator_(cmp), block_(nullptr) {}
  270. ~BlockConstructor() override { delete block_; }
  271. Status FinishImpl(const Options& /*options*/,
  272. const ImmutableOptions& /*ioptions*/,
  273. const MutableCFOptions& /*moptions*/,
  274. const BlockBasedTableOptions& table_options,
  275. const InternalKeyComparator& /*internal_comparator*/,
  276. const stl_wrappers::KVMap& kv_map) override {
  277. delete block_;
  278. block_ = nullptr;
  279. BlockBuilder builder(table_options.block_restart_interval);
  280. for (const auto& kv : kv_map) {
  281. // `DataBlockIter` assumes it reads only internal keys. `BlockConstructor`
  282. // clients provide user keys, so we need to convert to internal key format
  283. // before writing the data block.
  284. ParsedInternalKey ikey(kv.first, kMaxSequenceNumber, kTypeValue);
  285. std::string encoded;
  286. AppendInternalKey(&encoded, ikey);
  287. builder.Add(encoded, kv.second);
  288. }
  289. // Open the block
  290. data_ = builder.Finish().ToString();
  291. BlockContents contents;
  292. contents.data = data_;
  293. block_ = new Block(std::move(contents));
  294. return Status::OK();
  295. }
  296. InternalIterator* NewIterator(
  297. const SliceTransform* /*prefix_extractor*/) const override {
  298. // `DataBlockIter` returns the internal keys it reads.
  299. // `KeyConvertingIterator` converts them to user keys before they are
  300. // exposed to the `BlockConstructor` clients.
  301. return new KeyConvertingIterator(
  302. block_->NewDataIterator(comparator_, kDisableGlobalSequenceNumber));
  303. }
  304. private:
  305. const Comparator* comparator_;
  306. std::string data_;
  307. Block* block_;
  308. BlockConstructor() = delete;
  309. };
  310. class TableConstructor : public Constructor {
  311. public:
  312. explicit TableConstructor(const Comparator* cmp,
  313. bool convert_to_internal_key = false,
  314. int level = -1, SequenceNumber largest_seqno = 0)
  315. : Constructor(cmp),
  316. largest_seqno_(largest_seqno),
  317. convert_to_internal_key_(convert_to_internal_key),
  318. level_(level) {
  319. env_ = ROCKSDB_NAMESPACE::Env::Default();
  320. }
  321. ~TableConstructor() override { Reset(); }
  322. Status FinishImpl(const Options& options, const ImmutableOptions& ioptions,
  323. const MutableCFOptions& moptions,
  324. const BlockBasedTableOptions& /*table_options*/,
  325. const InternalKeyComparator& internal_comparator,
  326. const stl_wrappers::KVMap& kv_map) override {
  327. Reset();
  328. soptions.use_mmap_reads = ioptions.allow_mmap_reads;
  329. std::unique_ptr<FSWritableFile> sink(new test::StringSink());
  330. file_writer_.reset(new WritableFileWriter(
  331. std::move(sink), "" /* don't care */, FileOptions()));
  332. std::unique_ptr<TableBuilder> builder;
  333. InternalTblPropCollFactories internal_tbl_prop_coll_factories;
  334. if (largest_seqno_ != 0) {
  335. // Pretend that it's an external file written by SstFileWriter.
  336. internal_tbl_prop_coll_factories.emplace_back(
  337. new SstFileWriterPropertiesCollectorFactory(2 /* version */,
  338. 0 /* global_seqno*/));
  339. }
  340. std::string column_family_name;
  341. const ReadOptions read_options;
  342. const WriteOptions write_options;
  343. builder.reset(moptions.table_factory->NewTableBuilder(
  344. TableBuilderOptions(
  345. ioptions, moptions, read_options, write_options,
  346. internal_comparator, &internal_tbl_prop_coll_factories,
  347. options.compression, options.compression_opts, kUnknownColumnFamily,
  348. column_family_name, level_, kUnknownNewestKeyTime),
  349. file_writer_.get()));
  350. for (const auto& kv : kv_map) {
  351. if (convert_to_internal_key_) {
  352. ParsedInternalKey ikey(kv.first, kMaxSequenceNumber, kTypeValue);
  353. std::string encoded;
  354. AppendInternalKey(&encoded, ikey);
  355. builder->Add(encoded, kv.second);
  356. } else {
  357. builder->Add(kv.first, kv.second);
  358. }
  359. EXPECT_OK(builder->status());
  360. }
  361. Status s = builder->Finish();
  362. EXPECT_OK(file_writer_->Flush(IOOptions()));
  363. EXPECT_TRUE(s.ok()) << s.ToString();
  364. EXPECT_EQ(TEST_GetSink()->contents().size(), builder->FileSize());
  365. // Open the table
  366. file_num_ = cur_file_num_++;
  367. return Reopen(ioptions, moptions);
  368. }
  369. InternalIterator* NewIterator(
  370. const SliceTransform* prefix_extractor) const override {
  371. InternalIterator* iter = table_reader_->NewIterator(
  372. read_options_, prefix_extractor, /*arena=*/nullptr,
  373. /*skip_filters=*/false, TableReaderCaller::kUncategorized);
  374. if (convert_to_internal_key_) {
  375. return new KeyConvertingIterator(iter);
  376. } else {
  377. return iter;
  378. }
  379. }
  380. uint64_t ApproximateOffsetOf(const Slice& key) const {
  381. const ReadOptions read_options;
  382. if (convert_to_internal_key_) {
  383. InternalKey ikey(key, kMaxSequenceNumber, kTypeValue);
  384. const Slice skey = ikey.Encode();
  385. return table_reader_->ApproximateOffsetOf(
  386. read_options, skey, TableReaderCaller::kUncategorized);
  387. }
  388. return table_reader_->ApproximateOffsetOf(
  389. read_options, key, TableReaderCaller::kUncategorized);
  390. }
  391. virtual Status Reopen(const ImmutableOptions& ioptions,
  392. const MutableCFOptions& moptions) {
  393. std::unique_ptr<FSRandomAccessFile> source(new test::StringSource(
  394. TEST_GetSink()->contents(), file_num_, ioptions.allow_mmap_reads));
  395. file_reader_.reset(new RandomAccessFileReader(std::move(source), "test"));
  396. return moptions.table_factory->NewTableReader(
  397. TableReaderOptions(ioptions, moptions.prefix_extractor,
  398. moptions.compression_manager.get(), soptions,
  399. *last_internal_comparator_,
  400. 0 /* block_protection_bytes_per_key */,
  401. /*skip_filters*/ false,
  402. /*immortal*/ false, false, level_,
  403. &block_cache_tracer_, moptions.write_buffer_size, "",
  404. file_num_, kNullUniqueId64x2, largest_seqno_),
  405. std::move(file_reader_), TEST_GetSink()->contents().size(),
  406. &table_reader_);
  407. }
  408. virtual TableReader* GetTableReader() { return table_reader_.get(); }
  409. bool AnywayDeleteIterator() const override {
  410. return convert_to_internal_key_;
  411. }
  412. void ResetTableReader() { table_reader_.reset(); }
  413. bool ConvertToInternalKey() { return convert_to_internal_key_; }
  414. test::StringSink* TEST_GetSink() {
  415. return static_cast<test::StringSink*>(file_writer_->writable_file());
  416. }
  417. BlockCacheTracer block_cache_tracer_;
  418. Env* env_;
  419. private:
  420. void Reset() {
  421. file_num_ = 0;
  422. table_reader_.reset();
  423. file_writer_.reset();
  424. file_reader_.reset();
  425. }
  426. const ReadOptions read_options_;
  427. uint64_t file_num_;
  428. std::unique_ptr<WritableFileWriter> file_writer_;
  429. std::unique_ptr<RandomAccessFileReader> file_reader_;
  430. std::unique_ptr<TableReader> table_reader_;
  431. SequenceNumber largest_seqno_;
  432. bool convert_to_internal_key_;
  433. int level_;
  434. TableConstructor() = delete;
  435. static uint64_t cur_file_num_;
  436. EnvOptions soptions;
  437. };
  438. uint64_t TableConstructor::cur_file_num_ = 1;
  439. class MemTableConstructor : public Constructor {
  440. public:
  441. explicit MemTableConstructor(const Comparator* cmp, WriteBufferManager* wb)
  442. : Constructor(cmp),
  443. internal_comparator_(cmp),
  444. write_buffer_manager_(wb),
  445. table_factory_(new SkipListFactory) {
  446. options_.memtable_factory = table_factory_;
  447. ImmutableOptions ioptions(options_);
  448. memtable_ =
  449. new MemTable(internal_comparator_, ioptions, MutableCFOptions(options_),
  450. wb, kMaxSequenceNumber, 0 /* column_family_id */);
  451. memtable_->Ref();
  452. }
  453. ~MemTableConstructor() override { delete memtable_->Unref(); }
  454. Status FinishImpl(const Options&, const ImmutableOptions& ioptions,
  455. const MutableCFOptions& /*moptions*/,
  456. const BlockBasedTableOptions& /*table_options*/,
  457. const InternalKeyComparator& /*internal_comparator*/,
  458. const stl_wrappers::KVMap& kv_map) override {
  459. delete memtable_->Unref();
  460. ImmutableOptions mem_ioptions(ioptions);
  461. memtable_ = new MemTable(internal_comparator_, mem_ioptions,
  462. MutableCFOptions(options_), write_buffer_manager_,
  463. kMaxSequenceNumber, 0 /* column_family_id */);
  464. memtable_->Ref();
  465. int seq = 1;
  466. for (const auto& kv : kv_map) {
  467. Status s = memtable_->Add(seq, kTypeValue, kv.first, kv.second,
  468. nullptr /* kv_prot_info */);
  469. if (!s.ok()) {
  470. return s;
  471. }
  472. seq++;
  473. }
  474. return Status::OK();
  475. }
  476. InternalIterator* NewIterator(
  477. const SliceTransform* /*prefix_extractor*/) const override {
  478. return new KeyConvertingIterator(
  479. memtable_->NewIterator(ReadOptions(), /*seqno_to_time_mapping=*/nullptr,
  480. &arena_, /*prefix_extractor=*/nullptr,
  481. /*for_flush=*/false),
  482. true);
  483. }
  484. bool AnywayDeleteIterator() const override { return true; }
  485. bool IsArenaMode() const override { return true; }
  486. private:
  487. mutable Arena arena_;
  488. InternalKeyComparator internal_comparator_;
  489. Options options_;
  490. WriteBufferManager* write_buffer_manager_;
  491. MemTable* memtable_;
  492. std::shared_ptr<SkipListFactory> table_factory_;
  493. };
  494. class InternalIteratorFromIterator : public InternalIterator {
  495. public:
  496. explicit InternalIteratorFromIterator(Iterator* it) : it_(it) {}
  497. bool Valid() const override { return it_->Valid(); }
  498. void Seek(const Slice& target) override { it_->Seek(target); }
  499. void SeekForPrev(const Slice& target) override { it_->SeekForPrev(target); }
  500. void SeekToFirst() override { it_->SeekToFirst(); }
  501. void SeekToLast() override { it_->SeekToLast(); }
  502. void Next() override { it_->Next(); }
  503. void Prev() override { it_->Prev(); }
  504. Slice key() const override { return it_->key(); }
  505. Slice value() const override { return it_->value(); }
  506. Status status() const override { return it_->status(); }
  507. private:
  508. std::unique_ptr<Iterator> it_;
  509. };
  510. class DBConstructor : public Constructor {
  511. public:
  512. explicit DBConstructor(const Comparator* cmp)
  513. : Constructor(cmp), comparator_(cmp) {
  514. db_ = nullptr;
  515. NewDB();
  516. }
  517. ~DBConstructor() override { delete db_; }
  518. Status FinishImpl(const Options& /*options*/,
  519. const ImmutableOptions& /*ioptions*/,
  520. const MutableCFOptions& /*moptions*/,
  521. const BlockBasedTableOptions& /*table_options*/,
  522. const InternalKeyComparator& /*internal_comparator*/,
  523. const stl_wrappers::KVMap& kv_map) override {
  524. delete db_;
  525. db_ = nullptr;
  526. NewDB();
  527. for (const auto& kv : kv_map) {
  528. WriteBatch batch;
  529. EXPECT_OK(batch.Put(kv.first, kv.second));
  530. EXPECT_TRUE(db_->Write(WriteOptions(), &batch).ok());
  531. }
  532. return Status::OK();
  533. }
  534. InternalIterator* NewIterator(
  535. const SliceTransform* /*prefix_extractor*/) const override {
  536. return new InternalIteratorFromIterator(db_->NewIterator(ReadOptions()));
  537. }
  538. DB* db() const override { return db_; }
  539. private:
  540. void NewDB() {
  541. std::string name = test::PerThreadDBPath("table_testdb");
  542. Options options;
  543. options.comparator = comparator_;
  544. Status status = DestroyDB(name, options);
  545. ASSERT_TRUE(status.ok()) << status.ToString();
  546. options.create_if_missing = true;
  547. options.error_if_exists = true;
  548. options.write_buffer_size = 10000; // Something small to force merging
  549. status = DB::Open(options, name, &db_);
  550. ASSERT_TRUE(status.ok()) << status.ToString();
  551. }
  552. const Comparator* comparator_;
  553. DB* db_;
  554. };
  555. enum TestType {
  556. BLOCK_BASED_TABLE_TEST,
  557. PLAIN_TABLE_SEMI_FIXED_PREFIX,
  558. PLAIN_TABLE_FULL_STR_PREFIX,
  559. PLAIN_TABLE_TOTAL_ORDER,
  560. BLOCK_TEST,
  561. MEMTABLE_TEST,
  562. DB_TEST
  563. };
  564. struct TestArgs {
  565. TestType type;
  566. bool reverse_compare;
  567. int restart_interval;
  568. CompressionType compression;
  569. uint32_t compression_parallel_threads;
  570. uint32_t format_version;
  571. bool use_mmap;
  572. };
  573. std::ostream& operator<<(std::ostream& os, const TestArgs& args) {
  574. os << "type: " << args.type << " reverse_compare: " << args.reverse_compare
  575. << " restart_interval: " << args.restart_interval
  576. << " compression: " << args.compression
  577. << " compression_parallel_threads: " << args.compression_parallel_threads
  578. << " format_version: " << args.format_version
  579. << " use_mmap: " << args.use_mmap;
  580. return os;
  581. }
  582. static std::vector<TestArgs> GenerateArgList() {
  583. std::vector<TestArgs> test_args;
  584. std::vector<TestType> test_types = {BLOCK_BASED_TABLE_TEST,
  585. PLAIN_TABLE_SEMI_FIXED_PREFIX,
  586. PLAIN_TABLE_FULL_STR_PREFIX,
  587. PLAIN_TABLE_TOTAL_ORDER,
  588. BLOCK_TEST,
  589. MEMTABLE_TEST,
  590. DB_TEST};
  591. std::vector<bool> reverse_compare_types = {false, true};
  592. std::vector<int> restart_intervals = {16, 1, 1024};
  593. std::vector<uint32_t> compression_parallel_threads = {1, 4};
  594. // Only add compression if it is supported
  595. std::vector<std::pair<CompressionType, bool>> compression_types;
  596. compression_types.emplace_back(kNoCompression, false);
  597. if (Snappy_Supported()) {
  598. compression_types.emplace_back(kSnappyCompression, false);
  599. }
  600. if (Zlib_Supported()) {
  601. compression_types.emplace_back(kZlibCompression, false);
  602. compression_types.emplace_back(kZlibCompression, true);
  603. }
  604. if (BZip2_Supported()) {
  605. compression_types.emplace_back(kBZip2Compression, false);
  606. compression_types.emplace_back(kBZip2Compression, true);
  607. }
  608. if (LZ4_Supported()) {
  609. compression_types.emplace_back(kLZ4Compression, false);
  610. compression_types.emplace_back(kLZ4Compression, true);
  611. compression_types.emplace_back(kLZ4HCCompression, false);
  612. compression_types.emplace_back(kLZ4HCCompression, true);
  613. }
  614. if (XPRESS_Supported()) {
  615. compression_types.emplace_back(kXpressCompression, false);
  616. compression_types.emplace_back(kXpressCompression, true);
  617. }
  618. if (ZSTD_Supported()) {
  619. compression_types.emplace_back(kZSTD, false);
  620. compression_types.emplace_back(kZSTD, true);
  621. }
  622. for (auto test_type : test_types) {
  623. for (auto reverse_compare : reverse_compare_types) {
  624. if (test_type == PLAIN_TABLE_SEMI_FIXED_PREFIX ||
  625. test_type == PLAIN_TABLE_FULL_STR_PREFIX ||
  626. test_type == PLAIN_TABLE_TOTAL_ORDER) {
  627. // Plain table doesn't use restart index or compression.
  628. TestArgs one_arg;
  629. one_arg.type = test_type;
  630. one_arg.reverse_compare = reverse_compare;
  631. one_arg.restart_interval = restart_intervals[0];
  632. one_arg.compression = compression_types[0].first;
  633. one_arg.compression_parallel_threads = 1;
  634. one_arg.format_version = 0;
  635. one_arg.use_mmap = true;
  636. test_args.push_back(one_arg);
  637. one_arg.use_mmap = false;
  638. test_args.push_back(one_arg);
  639. continue;
  640. }
  641. for (auto restart_interval : restart_intervals) {
  642. for (auto compression_type : compression_types) {
  643. for (auto num_threads : compression_parallel_threads) {
  644. TestArgs one_arg;
  645. one_arg.type = test_type;
  646. one_arg.reverse_compare = reverse_compare;
  647. one_arg.restart_interval = restart_interval;
  648. one_arg.compression = compression_type.first;
  649. one_arg.compression_parallel_threads = num_threads;
  650. one_arg.format_version = compression_type.second ? 2 : 1;
  651. one_arg.use_mmap = false;
  652. test_args.push_back(one_arg);
  653. }
  654. }
  655. }
  656. }
  657. }
  658. return test_args;
  659. }
  660. // In order to make all tests run for plain table format, including
  661. // those operating on empty keys, create a new prefix transformer which
  662. // return fixed prefix if the slice is not shorter than the prefix length,
  663. // and the full slice if it is shorter.
  664. class FixedOrLessPrefixTransform : public SliceTransform {
  665. private:
  666. const size_t prefix_len_;
  667. public:
  668. explicit FixedOrLessPrefixTransform(size_t prefix_len)
  669. : prefix_len_(prefix_len) {}
  670. const char* Name() const override { return "rocksdb.FixedPrefix"; }
  671. Slice Transform(const Slice& src) const override {
  672. assert(InDomain(src));
  673. if (src.size() < prefix_len_) {
  674. return src;
  675. }
  676. return Slice(src.data(), prefix_len_);
  677. }
  678. bool InDomain(const Slice& /*src*/) const override { return true; }
  679. bool InRange(const Slice& dst) const override {
  680. return (dst.size() <= prefix_len_);
  681. }
  682. bool FullLengthEnabled(size_t* /*len*/) const override { return false; }
  683. };
  684. class HarnessTest : public testing::Test {
  685. public:
  686. explicit HarnessTest(const TestArgs& args)
  687. : args_(args),
  688. ioptions_(options_),
  689. moptions_(options_),
  690. write_buffer_(options_.db_write_buffer_size),
  691. support_prev_(true),
  692. only_support_prefix_seek_(false) {
  693. options_.compression = args_.compression;
  694. options_.compression_opts.parallel_threads =
  695. args_.compression_parallel_threads;
  696. // Use shorter block size for tests to exercise block boundary
  697. // conditions more.
  698. if (args_.reverse_compare) {
  699. options_.comparator = &reverse_key_comparator;
  700. }
  701. internal_comparator_.reset(
  702. new test::PlainInternalKeyComparator(options_.comparator));
  703. options_.allow_mmap_reads = args_.use_mmap;
  704. switch (args_.type) {
  705. case BLOCK_BASED_TABLE_TEST:
  706. table_options_.flush_block_policy_factory.reset(
  707. new FlushBlockBySizePolicyFactory());
  708. table_options_.block_size = 256;
  709. table_options_.block_restart_interval = args_.restart_interval;
  710. table_options_.index_block_restart_interval = args_.restart_interval;
  711. table_options_.format_version = args_.format_version;
  712. options_.table_factory.reset(
  713. new BlockBasedTableFactory(table_options_));
  714. constructor_.reset(new TableConstructor(
  715. options_.comparator, true /* convert_to_internal_key_ */));
  716. internal_comparator_.reset(
  717. new InternalKeyComparator(options_.comparator));
  718. break;
  719. case PLAIN_TABLE_SEMI_FIXED_PREFIX:
  720. support_prev_ = false;
  721. only_support_prefix_seek_ = true;
  722. options_.prefix_extractor.reset(new FixedOrLessPrefixTransform(2));
  723. options_.table_factory.reset(NewPlainTableFactory());
  724. constructor_.reset(new TableConstructor(
  725. options_.comparator, true /* convert_to_internal_key_ */));
  726. internal_comparator_.reset(
  727. new InternalKeyComparator(options_.comparator));
  728. break;
  729. case PLAIN_TABLE_FULL_STR_PREFIX:
  730. support_prev_ = false;
  731. only_support_prefix_seek_ = true;
  732. options_.prefix_extractor.reset(NewNoopTransform());
  733. options_.table_factory.reset(NewPlainTableFactory());
  734. constructor_.reset(new TableConstructor(
  735. options_.comparator, true /* convert_to_internal_key_ */));
  736. internal_comparator_.reset(
  737. new InternalKeyComparator(options_.comparator));
  738. break;
  739. case PLAIN_TABLE_TOTAL_ORDER:
  740. support_prev_ = false;
  741. only_support_prefix_seek_ = false;
  742. options_.prefix_extractor = nullptr;
  743. {
  744. PlainTableOptions plain_table_options;
  745. plain_table_options.user_key_len = kPlainTableVariableLength;
  746. plain_table_options.bloom_bits_per_key = 0;
  747. plain_table_options.hash_table_ratio = 0;
  748. options_.table_factory.reset(
  749. NewPlainTableFactory(plain_table_options));
  750. }
  751. constructor_.reset(new TableConstructor(
  752. options_.comparator, true /* convert_to_internal_key_ */));
  753. internal_comparator_.reset(
  754. new InternalKeyComparator(options_.comparator));
  755. break;
  756. case BLOCK_TEST:
  757. table_options_.block_size = 256;
  758. options_.table_factory.reset(
  759. new BlockBasedTableFactory(table_options_));
  760. constructor_.reset(new BlockConstructor(options_.comparator));
  761. break;
  762. case MEMTABLE_TEST:
  763. table_options_.block_size = 256;
  764. options_.table_factory.reset(
  765. new BlockBasedTableFactory(table_options_));
  766. constructor_.reset(
  767. new MemTableConstructor(options_.comparator, &write_buffer_));
  768. break;
  769. case DB_TEST:
  770. table_options_.block_size = 256;
  771. options_.table_factory.reset(
  772. new BlockBasedTableFactory(table_options_));
  773. constructor_.reset(new DBConstructor(options_.comparator));
  774. break;
  775. }
  776. ioptions_ = ImmutableOptions(options_);
  777. moptions_ = MutableCFOptions(options_);
  778. }
  779. void Add(const std::string& key, const std::string& value) {
  780. constructor_->Add(key, value);
  781. }
  782. void Test(Random* rnd) {
  783. std::vector<std::string> keys;
  784. stl_wrappers::KVMap data;
  785. constructor_->Finish(options_, ioptions_, moptions_, table_options_,
  786. *internal_comparator_, &keys, &data);
  787. TestForwardScan(keys, data);
  788. if (support_prev_) {
  789. TestBackwardScan(keys, data);
  790. }
  791. TestRandomAccess(rnd, keys, data);
  792. }
  793. void TestForwardScan(const std::vector<std::string>& /*keys*/,
  794. const stl_wrappers::KVMap& data) {
  795. InternalIterator* iter = constructor_->NewIterator();
  796. ASSERT_TRUE(!iter->Valid());
  797. iter->SeekToFirst();
  798. ASSERT_OK(iter->status());
  799. for (stl_wrappers::KVMap::const_iterator model_iter = data.begin();
  800. model_iter != data.end(); ++model_iter) {
  801. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  802. iter->Next();
  803. ASSERT_OK(iter->status());
  804. }
  805. ASSERT_TRUE(!iter->Valid());
  806. ASSERT_OK(iter->status());
  807. if (constructor_->IsArenaMode() && !constructor_->AnywayDeleteIterator()) {
  808. iter->~InternalIterator();
  809. } else {
  810. delete iter;
  811. }
  812. }
  813. void TestBackwardScan(const std::vector<std::string>& /*keys*/,
  814. const stl_wrappers::KVMap& data) {
  815. InternalIterator* iter = constructor_->NewIterator();
  816. ASSERT_TRUE(!iter->Valid());
  817. iter->SeekToLast();
  818. ASSERT_OK(iter->status());
  819. for (stl_wrappers::KVMap::const_reverse_iterator model_iter = data.rbegin();
  820. model_iter != data.rend(); ++model_iter) {
  821. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  822. iter->Prev();
  823. ASSERT_OK(iter->status());
  824. }
  825. ASSERT_TRUE(!iter->Valid());
  826. ASSERT_OK(iter->status());
  827. if (constructor_->IsArenaMode() && !constructor_->AnywayDeleteIterator()) {
  828. iter->~InternalIterator();
  829. } else {
  830. delete iter;
  831. }
  832. }
  833. void TestRandomAccess(Random* rnd, const std::vector<std::string>& keys,
  834. const stl_wrappers::KVMap& data) {
  835. InternalIterator* iter = constructor_->NewIterator();
  836. ASSERT_TRUE(!iter->Valid());
  837. stl_wrappers::KVMap::const_iterator model_iter = data.begin();
  838. if (kVerbose) {
  839. fprintf(stderr, "---\n");
  840. }
  841. for (int i = 0; i < 200; i++) {
  842. const int toss = rnd->Uniform(support_prev_ ? 5 : 3);
  843. switch (toss) {
  844. case 0: {
  845. if (iter->Valid()) {
  846. if (kVerbose) {
  847. fprintf(stderr, "Next\n");
  848. }
  849. iter->Next();
  850. ASSERT_OK(iter->status());
  851. ++model_iter;
  852. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  853. }
  854. break;
  855. }
  856. case 1: {
  857. if (kVerbose) {
  858. fprintf(stderr, "SeekToFirst\n");
  859. }
  860. iter->SeekToFirst();
  861. ASSERT_OK(iter->status());
  862. model_iter = data.begin();
  863. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  864. break;
  865. }
  866. case 2: {
  867. std::string key = PickRandomKey(rnd, keys);
  868. model_iter = data.lower_bound(key);
  869. if (kVerbose) {
  870. fprintf(stderr, "Seek '%s'\n", EscapeString(key).c_str());
  871. }
  872. iter->Seek(Slice(key));
  873. ASSERT_OK(iter->status());
  874. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  875. break;
  876. }
  877. case 3: {
  878. if (iter->Valid()) {
  879. if (kVerbose) {
  880. fprintf(stderr, "Prev\n");
  881. }
  882. iter->Prev();
  883. ASSERT_OK(iter->status());
  884. if (model_iter == data.begin()) {
  885. model_iter = data.end(); // Wrap around to invalid value
  886. } else {
  887. --model_iter;
  888. }
  889. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  890. }
  891. break;
  892. }
  893. case 4: {
  894. if (kVerbose) {
  895. fprintf(stderr, "SeekToLast\n");
  896. }
  897. iter->SeekToLast();
  898. ASSERT_OK(iter->status());
  899. if (keys.empty()) {
  900. model_iter = data.end();
  901. } else {
  902. std::string last = data.rbegin()->first;
  903. model_iter = data.lower_bound(last);
  904. }
  905. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  906. break;
  907. }
  908. }
  909. }
  910. if (constructor_->IsArenaMode() && !constructor_->AnywayDeleteIterator()) {
  911. iter->~InternalIterator();
  912. } else {
  913. delete iter;
  914. }
  915. }
  916. std::string ToString(const stl_wrappers::KVMap& data,
  917. const stl_wrappers::KVMap::const_iterator& it) {
  918. if (it == data.end()) {
  919. return "END";
  920. } else {
  921. return "'" + it->first + "->" + it->second + "'";
  922. }
  923. }
  924. std::string ToString(const stl_wrappers::KVMap& data,
  925. const stl_wrappers::KVMap::const_reverse_iterator& it) {
  926. if (it == data.rend()) {
  927. return "END";
  928. } else {
  929. return "'" + it->first + "->" + it->second + "'";
  930. }
  931. }
  932. std::string ToString(const InternalIterator* it) {
  933. if (!it->Valid()) {
  934. return "END";
  935. } else {
  936. return "'" + it->key().ToString() + "->" + it->value().ToString() + "'";
  937. }
  938. }
  939. std::string PickRandomKey(Random* rnd, const std::vector<std::string>& keys) {
  940. if (keys.empty()) {
  941. return "foo";
  942. } else {
  943. const int index = rnd->Uniform(static_cast<int>(keys.size()));
  944. std::string result = keys[index];
  945. switch (rnd->Uniform(support_prev_ ? 3 : 1)) {
  946. case 0:
  947. // Return an existing key
  948. break;
  949. case 1: {
  950. // Attempt to return something smaller than an existing key
  951. if (result.size() > 0 && result[result.size() - 1] > '\0' &&
  952. (!only_support_prefix_seek_ ||
  953. options_.prefix_extractor->Transform(result).size() <
  954. result.size())) {
  955. result[result.size() - 1]--;
  956. }
  957. break;
  958. }
  959. case 2: {
  960. // Return something larger than an existing key
  961. Increment(options_.comparator, &result);
  962. break;
  963. }
  964. }
  965. return result;
  966. }
  967. }
  968. // Returns nullptr if not running against a DB
  969. DB* db() const { return constructor_->db(); }
  970. private:
  971. TestArgs args_;
  972. Options options_;
  973. ImmutableOptions ioptions_;
  974. MutableCFOptions moptions_;
  975. BlockBasedTableOptions table_options_;
  976. std::unique_ptr<Constructor> constructor_;
  977. WriteBufferManager write_buffer_;
  978. bool support_prev_;
  979. bool only_support_prefix_seek_;
  980. std::shared_ptr<InternalKeyComparator> internal_comparator_;
  981. };
  982. class ParameterizedHarnessTest : public HarnessTest,
  983. public testing::WithParamInterface<TestArgs> {
  984. public:
  985. ParameterizedHarnessTest() : HarnessTest(GetParam()) {}
  986. };
  987. INSTANTIATE_TEST_CASE_P(TableTest, ParameterizedHarnessTest,
  988. ::testing::ValuesIn(GenerateArgList()));
  989. class DBHarnessTest : public HarnessTest {
  990. public:
  991. DBHarnessTest()
  992. : HarnessTest(TestArgs{DB_TEST, /* reverse_compare */ false,
  993. /* restart_interval */ 16, kNoCompression,
  994. /* compression_parallel_threads */ 1,
  995. /* format_version */ 0, /* use_mmap */ false}) {}
  996. };
  997. static bool Between(uint64_t val, uint64_t low, uint64_t high) {
  998. bool result = (val >= low) && (val <= high);
  999. if (!result) {
  1000. fprintf(stderr, "Value %llu is not in range [%llu, %llu]\n",
  1001. (unsigned long long)(val), (unsigned long long)(low),
  1002. (unsigned long long)(high));
  1003. }
  1004. return result;
  1005. }
  1006. // Tests against all kinds of tables
  1007. class TableTest : public testing::Test {
  1008. public:
  1009. const InternalKeyComparator& GetPlainInternalComparator(
  1010. const Comparator* comp) {
  1011. if (!plain_internal_comparator) {
  1012. plain_internal_comparator.reset(
  1013. new test::PlainInternalKeyComparator(comp));
  1014. }
  1015. return *plain_internal_comparator;
  1016. }
  1017. void IndexTest(BlockBasedTableOptions table_options);
  1018. private:
  1019. std::unique_ptr<InternalKeyComparator> plain_internal_comparator;
  1020. };
  1021. class GeneralTableTest : public TableTest {};
  1022. class BlockBasedTableTestBase : public TableTest {};
  1023. class BlockBasedTableTest : public BlockBasedTableTestBase,
  1024. virtual public ::testing::WithParamInterface<
  1025. std::tuple<uint32_t, size_t, size_t>> {
  1026. public:
  1027. BlockBasedTableTest() : format_(std::get<0>(GetParam())) {
  1028. env_ = Env::Default();
  1029. }
  1030. BlockBasedTableOptions GetBlockBasedTableOptions() {
  1031. BlockBasedTableOptions options;
  1032. options.format_version = format_;
  1033. auto param = GetParam();
  1034. options.super_block_alignment_size = std::get<1>(param);
  1035. options.super_block_alignment_space_overhead_ratio = std::get<2>(param);
  1036. return options;
  1037. }
  1038. void SetupTracingTest(TableConstructor* c) {
  1039. test_path_ = test::PerThreadDBPath("block_based_table_tracing_test");
  1040. EXPECT_OK(env_->CreateDir(test_path_));
  1041. trace_file_path_ = test_path_ + "/block_cache_trace_file";
  1042. BlockCacheTraceWriterOptions trace_writer_opt;
  1043. BlockCacheTraceOptions trace_opt;
  1044. std::unique_ptr<TraceWriter> trace_writer;
  1045. EXPECT_OK(NewFileTraceWriter(env_, EnvOptions(), trace_file_path_,
  1046. &trace_writer));
  1047. std::unique_ptr<BlockCacheTraceWriter> block_cache_trace_writer =
  1048. NewBlockCacheTraceWriter(env_->GetSystemClock().get(), trace_writer_opt,
  1049. std::move(trace_writer));
  1050. ASSERT_NE(block_cache_trace_writer, nullptr);
  1051. // Always return Status::OK().
  1052. ASSERT_OK(c->block_cache_tracer_.StartTrace(
  1053. trace_opt, std::move(block_cache_trace_writer)));
  1054. {
  1055. InternalKey internal_key(auto_add_key1, 0, kTypeValue);
  1056. std::string encoded_key = internal_key.Encode().ToString();
  1057. c->Add(encoded_key, kDummyValue);
  1058. }
  1059. {
  1060. InternalKey internal_key(auto_add_key2, 0, kTypeValue);
  1061. std::string encoded_key = internal_key.Encode().ToString();
  1062. c->Add(encoded_key, kDummyValue);
  1063. }
  1064. }
  1065. void VerifyBlockAccessTrace(
  1066. TableConstructor* c,
  1067. const std::vector<BlockCacheTraceRecord>& expected_records) {
  1068. c->block_cache_tracer_.EndTrace();
  1069. {
  1070. std::unique_ptr<TraceReader> trace_reader;
  1071. Status s = NewFileTraceReader(env_, EnvOptions(), trace_file_path_,
  1072. &trace_reader);
  1073. EXPECT_OK(s);
  1074. BlockCacheTraceReader reader(std::move(trace_reader));
  1075. BlockCacheTraceHeader header;
  1076. EXPECT_OK(reader.ReadHeader(&header));
  1077. uint32_t index = 0;
  1078. while (s.ok()) {
  1079. SCOPED_TRACE("expected_records[" + std::to_string(index) + "]");
  1080. BlockCacheTraceRecord access;
  1081. s = reader.ReadAccess(&access);
  1082. if (!s.ok()) {
  1083. break;
  1084. }
  1085. ASSERT_LT(index, expected_records.size());
  1086. EXPECT_NE("", access.block_key);
  1087. EXPECT_EQ(access.block_type, expected_records[index].block_type);
  1088. EXPECT_GT(access.block_size, 0);
  1089. EXPECT_EQ(access.caller, expected_records[index].caller);
  1090. EXPECT_EQ(access.no_insert, expected_records[index].no_insert);
  1091. EXPECT_EQ(access.is_cache_hit, expected_records[index].is_cache_hit);
  1092. EXPECT_EQ(access.get_id, expected_records[index].get_id);
  1093. // The well-populated cases
  1094. if (access.caller == TableReaderCaller::kUserGet ||
  1095. (access.caller == TableReaderCaller::kUserMultiGet &&
  1096. access.block_type == TraceType::kBlockTraceDataBlock)) {
  1097. EXPECT_EQ(access.referenced_key,
  1098. expected_records[index].referenced_key);
  1099. EXPECT_EQ(access.get_from_user_specified_snapshot,
  1100. expected_records[index].get_from_user_specified_snapshot);
  1101. if (access.block_type == TraceType::kBlockTraceDataBlock) {
  1102. EXPECT_GT(access.referenced_data_size, 0);
  1103. EXPECT_GT(access.num_keys_in_block, 0);
  1104. if (access.caller == TableReaderCaller::kUserMultiGet) {
  1105. // Test num_keys_in_block estimate, assuming default restart
  1106. // interval of 16 and just one interval.
  1107. // Rounding depends on get_id.
  1108. if (access.get_id & 1) {
  1109. EXPECT_EQ(access.num_keys_in_block, 9);
  1110. } else {
  1111. EXPECT_EQ(access.num_keys_in_block, 8);
  1112. }
  1113. }
  1114. EXPECT_EQ(access.referenced_key_exist_in_block,
  1115. expected_records[index].referenced_key_exist_in_block);
  1116. }
  1117. } else {
  1118. EXPECT_EQ(access.referenced_key, "");
  1119. EXPECT_FALSE(access.get_from_user_specified_snapshot);
  1120. EXPECT_EQ(access.referenced_data_size, 0);
  1121. EXPECT_EQ(access.num_keys_in_block, 0);
  1122. EXPECT_FALSE(access.referenced_key_exist_in_block);
  1123. }
  1124. index++;
  1125. }
  1126. EXPECT_EQ(index, expected_records.size());
  1127. }
  1128. EXPECT_OK(env_->DeleteFile(trace_file_path_));
  1129. EXPECT_OK(env_->DeleteDir(test_path_));
  1130. }
  1131. protected:
  1132. uint64_t IndexUncompressedHelper(bool indexCompress);
  1133. const std::string auto_add_key1 = "aak01";
  1134. const std::string auto_add_key2 = "aak02";
  1135. private:
  1136. uint32_t format_;
  1137. Env* env_;
  1138. std::string trace_file_path_;
  1139. std::string test_path_;
  1140. };
  1141. class PlainTableTest : public TableTest {};
  1142. class TablePropertyTest : public testing::Test {};
  1143. class BBTTailPrefetchTest : public TableTest {};
  1144. // The helper class to test the file checksum
  1145. class FileChecksumTestHelper {
  1146. public:
  1147. FileChecksumTestHelper(bool convert_to_internal_key = false)
  1148. : convert_to_internal_key_(convert_to_internal_key) {}
  1149. ~FileChecksumTestHelper() = default;
  1150. void CreateWritableFile() {
  1151. sink_ = new test::StringSink();
  1152. std::unique_ptr<FSWritableFile> holder(sink_);
  1153. file_writer_.reset(new WritableFileWriter(
  1154. std::move(holder), "" /* don't care */, FileOptions()));
  1155. }
  1156. void SetFileChecksumGenerator(FileChecksumGenerator* checksum_generator) {
  1157. if (file_writer_ != nullptr) {
  1158. file_writer_->TEST_SetFileChecksumGenerator(checksum_generator);
  1159. } else {
  1160. delete checksum_generator;
  1161. }
  1162. }
  1163. WritableFileWriter* GetFileWriter() { return file_writer_.get(); }
  1164. Status ResetTableBuilder(std::unique_ptr<TableBuilder>&& builder) {
  1165. assert(builder != nullptr);
  1166. table_builder_ = std::move(builder);
  1167. return Status::OK();
  1168. }
  1169. void AddKVtoKVMap(int num_entries) {
  1170. Random rnd(test::RandomSeed());
  1171. for (int i = 0; i < num_entries; i++) {
  1172. std::string v = rnd.RandomString(100);
  1173. kv_map_[test::RandomKey(&rnd, 20)] = v;
  1174. }
  1175. }
  1176. Status WriteKVAndFlushTable() {
  1177. for (const auto& kv : kv_map_) {
  1178. if (convert_to_internal_key_) {
  1179. ParsedInternalKey ikey(kv.first, kMaxSequenceNumber, kTypeValue);
  1180. std::string encoded;
  1181. AppendInternalKey(&encoded, ikey);
  1182. table_builder_->Add(encoded, kv.second);
  1183. } else {
  1184. table_builder_->Add(kv.first, kv.second);
  1185. }
  1186. EXPECT_TRUE(table_builder_->status().ok());
  1187. }
  1188. Status s = table_builder_->Finish();
  1189. EXPECT_OK(file_writer_->Flush(IOOptions()));
  1190. EXPECT_OK(s);
  1191. EXPECT_EQ(sink_->contents().size(), table_builder_->FileSize());
  1192. return s;
  1193. }
  1194. std::string GetFileChecksum() {
  1195. EXPECT_OK(file_writer_->Close(IOOptions()));
  1196. return table_builder_->GetFileChecksum();
  1197. }
  1198. const char* GetFileChecksumFuncName() {
  1199. return table_builder_->GetFileChecksumFuncName();
  1200. }
  1201. Status CalculateFileChecksum(FileChecksumGenerator* file_checksum_generator,
  1202. std::string* checksum) {
  1203. assert(file_checksum_generator != nullptr);
  1204. cur_file_num_ = checksum_file_num_++;
  1205. test::StringSink* ss_rw =
  1206. static_cast<test::StringSink*>(file_writer_->writable_file());
  1207. std::unique_ptr<FSRandomAccessFile> source(
  1208. new test::StringSource(ss_rw->contents()));
  1209. file_reader_.reset(new RandomAccessFileReader(std::move(source), "test"));
  1210. std::unique_ptr<char[]> scratch(new char[2048]);
  1211. Slice result;
  1212. uint64_t offset = 0;
  1213. Status s;
  1214. s = file_reader_->Read(IOOptions(), offset, 2048, &result, scratch.get(),
  1215. nullptr);
  1216. if (!s.ok()) {
  1217. return s;
  1218. }
  1219. while (result.size() != 0) {
  1220. file_checksum_generator->Update(scratch.get(), result.size());
  1221. offset += static_cast<uint64_t>(result.size());
  1222. s = file_reader_->Read(IOOptions(), offset, 2048, &result, scratch.get(),
  1223. nullptr);
  1224. if (!s.ok()) {
  1225. return s;
  1226. }
  1227. }
  1228. EXPECT_EQ(offset, static_cast<uint64_t>(table_builder_->FileSize()));
  1229. file_checksum_generator->Finalize();
  1230. *checksum = file_checksum_generator->GetChecksum();
  1231. return Status::OK();
  1232. }
  1233. private:
  1234. bool convert_to_internal_key_;
  1235. uint64_t cur_file_num_;
  1236. std::unique_ptr<WritableFileWriter> file_writer_;
  1237. std::unique_ptr<RandomAccessFileReader> file_reader_;
  1238. std::unique_ptr<TableBuilder> table_builder_;
  1239. stl_wrappers::KVMap kv_map_;
  1240. test::StringSink* sink_ = nullptr;
  1241. static uint64_t checksum_file_num_;
  1242. };
  1243. uint64_t FileChecksumTestHelper::checksum_file_num_ = 1;
  1244. INSTANTIATE_TEST_CASE_P(
  1245. FormatVersions, BlockBasedTableTest,
  1246. testing::Combine(testing::ValuesIn(test::kFooterFormatVersionsToTest),
  1247. testing::Values(0, 128 * 1024, 512 * 1024,
  1248. 2 * 1024 * 1024),
  1249. testing::Values(2048, 32, 128)));
  1250. // This test serves as the living tutorial for the prefix scan of user collected
  1251. // properties.
  1252. TEST_F(TablePropertyTest, PrefixScanTest) {
  1253. UserCollectedProperties props{
  1254. {"num.111.1", "1"}, {"num.111.2", "2"}, {"num.111.3", "3"},
  1255. {"num.333.1", "1"}, {"num.333.2", "2"}, {"num.333.3", "3"},
  1256. {"num.555.1", "1"}, {"num.555.2", "2"}, {"num.555.3", "3"},
  1257. };
  1258. // prefixes that exist
  1259. for (const std::string prefix : {"num.111", "num.333", "num.555"}) {
  1260. int num = 0;
  1261. for (auto pos = props.lower_bound(prefix);
  1262. pos != props.end() &&
  1263. pos->first.compare(0, prefix.size(), prefix) == 0;
  1264. ++pos) {
  1265. ++num;
  1266. auto key = prefix + "." + std::to_string(num);
  1267. ASSERT_EQ(key, pos->first);
  1268. ASSERT_EQ(std::to_string(num), pos->second);
  1269. }
  1270. ASSERT_EQ(3, num);
  1271. }
  1272. // prefixes that don't exist
  1273. for (const std::string prefix :
  1274. {"num.000", "num.222", "num.444", "num.666"}) {
  1275. auto pos = props.lower_bound(prefix);
  1276. ASSERT_TRUE(pos == props.end() ||
  1277. pos->first.compare(0, prefix.size(), prefix) != 0);
  1278. }
  1279. }
  1280. namespace {
  1281. struct TestIds {
  1282. UniqueId64x3 internal_id;
  1283. UniqueId64x3 external_id;
  1284. };
  1285. inline bool operator==(const TestIds& lhs, const TestIds& rhs) {
  1286. return lhs.internal_id == rhs.internal_id &&
  1287. lhs.external_id == rhs.external_id;
  1288. }
  1289. std::ostream& operator<<(std::ostream& os, const TestIds& ids) {
  1290. return os << std::hex << "{{{ 0x" << ids.internal_id[0] << "U, 0x"
  1291. << ids.internal_id[1] << "U, 0x" << ids.internal_id[2]
  1292. << "U }}, {{ 0x" << ids.external_id[0] << "U, 0x"
  1293. << ids.external_id[1] << "U, 0x" << ids.external_id[2] << "U }}}";
  1294. }
  1295. TestIds GetUniqueId(TableProperties* tp, std::unordered_set<uint64_t>* seen,
  1296. const std::string& db_id, const std::string& db_session_id,
  1297. uint64_t file_number) {
  1298. // First test session id logic
  1299. if (db_session_id.size() == 20) {
  1300. uint64_t upper;
  1301. uint64_t lower;
  1302. EXPECT_OK(DecodeSessionId(db_session_id, &upper, &lower));
  1303. EXPECT_EQ(EncodeSessionId(upper, lower), db_session_id);
  1304. }
  1305. // Get external using public API
  1306. tp->db_id = db_id;
  1307. tp->db_session_id = db_session_id;
  1308. tp->orig_file_number = file_number;
  1309. TestIds t;
  1310. {
  1311. std::string euid;
  1312. EXPECT_OK(GetExtendedUniqueIdFromTableProperties(*tp, &euid));
  1313. EXPECT_EQ(euid.size(), 24U);
  1314. t.external_id[0] = DecodeFixed64(euid.data());
  1315. t.external_id[1] = DecodeFixed64(&euid[8]);
  1316. t.external_id[2] = DecodeFixed64(&euid[16]);
  1317. std::string uid;
  1318. EXPECT_OK(GetUniqueIdFromTableProperties(*tp, &uid));
  1319. EXPECT_EQ(uid.size(), 16U);
  1320. EXPECT_EQ(uid, euid.substr(0, 16));
  1321. EXPECT_EQ(t.external_id[0], DecodeFixed64(uid.data()));
  1322. EXPECT_EQ(t.external_id[1], DecodeFixed64(&uid[8]));
  1323. }
  1324. // All these should be effectively random
  1325. EXPECT_TRUE(seen->insert(t.external_id[0]).second);
  1326. EXPECT_TRUE(seen->insert(t.external_id[1]).second);
  1327. EXPECT_TRUE(seen->insert(t.external_id[2]).second);
  1328. // Get internal with internal API
  1329. EXPECT_OK(GetSstInternalUniqueId(db_id, db_session_id, file_number,
  1330. &t.internal_id));
  1331. EXPECT_NE(t.internal_id, kNullUniqueId64x3);
  1332. // Verify relationship
  1333. UniqueId64x3 tmp = t.internal_id;
  1334. InternalUniqueIdToExternal(&tmp);
  1335. EXPECT_EQ(tmp, t.external_id);
  1336. ExternalUniqueIdToInternal(&tmp);
  1337. EXPECT_EQ(tmp, t.internal_id);
  1338. // And 128-bit internal version
  1339. UniqueId64x2 tmp2{};
  1340. EXPECT_OK(GetSstInternalUniqueId(db_id, db_session_id, file_number, &tmp2));
  1341. EXPECT_NE(tmp2, kNullUniqueId64x2);
  1342. EXPECT_EQ(tmp2[0], t.internal_id[0]);
  1343. EXPECT_EQ(tmp2[1], t.internal_id[1]);
  1344. InternalUniqueIdToExternal(&tmp2);
  1345. EXPECT_EQ(tmp2[0], t.external_id[0]);
  1346. EXPECT_EQ(tmp2[1], t.external_id[1]);
  1347. ExternalUniqueIdToInternal(&tmp2);
  1348. EXPECT_EQ(tmp2[0], t.internal_id[0]);
  1349. EXPECT_EQ(tmp2[1], t.internal_id[1]);
  1350. return t;
  1351. }
  1352. } // namespace
  1353. TEST_F(TablePropertyTest, UniqueIdsSchemaAndQuality) {
  1354. // To ensure the computation only depends on the expected entries, we set
  1355. // the rest randomly
  1356. TableProperties tp;
  1357. TEST_SetRandomTableProperties(&tp);
  1358. // DB id is normally RFC-4122
  1359. const std::string db_id1 = "7265b6eb-4e42-4aec-86a4-0dc5e73a228d";
  1360. // Allow other forms of DB id
  1361. const std::string db_id2 = "1728000184588763620";
  1362. const std::string db_id3 = "x";
  1363. // DB session id is normally 20 chars in base-36, but 13 to 24 chars
  1364. // is ok, roughly 64 to 128 bits.
  1365. const std::string ses_id1 = "ABCDEFGHIJ0123456789";
  1366. // Same trailing 13 digits
  1367. const std::string ses_id2 = "HIJ0123456789";
  1368. const std::string ses_id3 = "0123ABCDEFGHIJ0123456789";
  1369. // Different trailing 12 digits
  1370. const std::string ses_id4 = "ABCDEFGH888888888888";
  1371. // And change length
  1372. const std::string ses_id5 = "ABCDEFGHIJ012";
  1373. const std::string ses_id6 = "ABCDEFGHIJ0123456789ABCD";
  1374. using T = TestIds;
  1375. std::unordered_set<uint64_t> seen;
  1376. // Establish a stable schema for the unique IDs. These values must not
  1377. // change for existing table files.
  1378. // (Note: parens needed for macro parsing, extra braces needed for some
  1379. // compilers.)
  1380. EXPECT_EQ(
  1381. GetUniqueId(&tp, &seen, db_id1, ses_id1, 1),
  1382. T({{{0x61d7dcf415d9cf19U, 0x160d77aae90757fdU, 0x907f41dfd90724ffU}},
  1383. {{0xf0bd230365df7464U, 0xca089303f3648eb4U, 0x4b44f7e7324b2817U}}}));
  1384. // Only change internal_id[1] with file number
  1385. EXPECT_EQ(
  1386. GetUniqueId(&tp, &seen, db_id1, ses_id1, 2),
  1387. T({{{0x61d7dcf415d9cf19U, 0x160d77aae90757feU, 0x907f41dfd90724ffU}},
  1388. {{0xf13fdf7adcfebb6dU, 0x97cd2226cc033ea2U, 0x198c438182091f0eU}}}));
  1389. EXPECT_EQ(
  1390. GetUniqueId(&tp, &seen, db_id1, ses_id1, 123456789),
  1391. T({{{0x61d7dcf415d9cf19U, 0x160d77aaee5c9ae9U, 0x907f41dfd90724ffU}},
  1392. {{0x81fbcebe1ac6c4f0U, 0x6b14a64cfdc0f1c4U, 0x7d8fb6eaf18edbb3U}}}));
  1393. // Change internal_id[1] and internal_id[2] with db_id
  1394. EXPECT_EQ(
  1395. GetUniqueId(&tp, &seen, db_id2, ses_id1, 1),
  1396. T({{{0x61d7dcf415d9cf19U, 0xf89c471f572f0d25U, 0x1f0f2a5eb0e6257eU}},
  1397. {{0x7f1d01d453616991U, 0x32ddf2afec804ab2U, 0xd10a1ee2f0c7d9c1U}}}));
  1398. EXPECT_EQ(
  1399. GetUniqueId(&tp, &seen, db_id3, ses_id1, 1),
  1400. T({{{0x61d7dcf415d9cf19U, 0xfed297a8154a57d0U, 0x8b931b9cdebd9e8U}},
  1401. {{0x62b2f43183f6894bU, 0x897ff2b460eefad1U, 0xf4ec189fb2d15e04U}}}));
  1402. // Keeping same last 13 digits of ses_id keeps same internal_id[0]
  1403. EXPECT_EQ(
  1404. GetUniqueId(&tp, &seen, db_id1, ses_id2, 1),
  1405. T({{{0x61d7dcf415d9cf19U, 0x5f6cc4fa2d528c8U, 0x7b70845d5bfb5446U}},
  1406. {{0x96d1c83ffcc94266U, 0x82663eac0ec6e14aU, 0x94a88b49678b77f6U}}}));
  1407. EXPECT_EQ(
  1408. GetUniqueId(&tp, &seen, db_id1, ses_id3, 1),
  1409. T({{{0x61d7dcf415d9cf19U, 0xfc7232879db37ea2U, 0xc0378d74ea4c89cdU}},
  1410. {{0xdf2ef57e98776905U, 0xda5b31c987da833bU, 0x79c1b4bd0a9e760dU}}}));
  1411. // Changing last 12 digits of ses_id only changes internal_id[0]
  1412. // (vs. db_id1, ses_id1, 1)
  1413. EXPECT_EQ(
  1414. GetUniqueId(&tp, &seen, db_id1, ses_id4, 1),
  1415. T({{{0x4f07cc0d003a83a8U, 0x160d77aae90757fdU, 0x907f41dfd90724ffU}},
  1416. {{0xbcf85336a9f71f04U, 0x4f2949e2f3adb60dU, 0x9ca0def976abfa10U}}}));
  1417. // ses_id can change everything.
  1418. EXPECT_EQ(
  1419. GetUniqueId(&tp, &seen, db_id1, ses_id5, 1),
  1420. T({{{0x94b8768e43f87ce6U, 0xc2559653ac4e7c93U, 0xde6dff6bbb1223U}},
  1421. {{0x5a9537af681817fbU, 0x1afcd1fecaead5eaU, 0x767077ad9ebe0008U}}}));
  1422. EXPECT_EQ(
  1423. GetUniqueId(&tp, &seen, db_id1, ses_id6, 1),
  1424. T({{{0x43cfb0ffa3b710edU, 0x263c580426406a1bU, 0xfacc91379a80d29dU}},
  1425. {{0xfa90547d84cb1cdbU, 0x2afe99c641992d4aU, 0x205b7f7b60e51cc2U}}}));
  1426. // Now verify more thoroughly that any small change in inputs completely
  1427. // changes external unique id.
  1428. // (Relying on 'seen' checks etc. in GetUniqueId)
  1429. std::string db_id = "00000000-0000-0000-0000-000000000000";
  1430. std::string ses_id = "000000000000000000000000";
  1431. uint64_t file_num = 1;
  1432. // change db_id
  1433. for (size_t i = 0; i < db_id.size(); ++i) {
  1434. if (db_id[i] == '-') {
  1435. continue;
  1436. }
  1437. for (char alt : std::string("123456789abcdef")) {
  1438. db_id[i] = alt;
  1439. GetUniqueId(&tp, &seen, db_id, ses_id, file_num);
  1440. }
  1441. db_id[i] = '0';
  1442. }
  1443. // change ses_id
  1444. for (size_t i = 0; i < ses_id.size(); ++i) {
  1445. for (char alt : std::string("123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")) {
  1446. ses_id[i] = alt;
  1447. GetUniqueId(&tp, &seen, db_id, ses_id, file_num);
  1448. }
  1449. ses_id[i] = '0';
  1450. }
  1451. // change file_num
  1452. for (int i = 1; i < 64; ++i) {
  1453. GetUniqueId(&tp, &seen, db_id, ses_id, file_num << i);
  1454. }
  1455. // Verify that "all zeros" in first 128 bits is equivalent for internal and
  1456. // external IDs. This way, as long as we avoid "all zeros" in internal IDs,
  1457. // we avoid it in external IDs.
  1458. {
  1459. UniqueId64x3 id1{{0, 0, Random::GetTLSInstance()->Next64()}};
  1460. UniqueId64x3 id2 = id1;
  1461. InternalUniqueIdToExternal(&id1);
  1462. EXPECT_EQ(id1, id2);
  1463. ExternalUniqueIdToInternal(&id2);
  1464. EXPECT_EQ(id1, id2);
  1465. }
  1466. }
  1467. namespace {
  1468. void SetGoodTableProperties(TableProperties* tp) {
  1469. // To ensure the computation only depends on the expected entries, we set
  1470. // the rest randomly
  1471. TEST_SetRandomTableProperties(tp);
  1472. tp->db_id = "7265b6eb-4e42-4aec-86a4-0dc5e73a228d";
  1473. tp->db_session_id = "ABCDEFGHIJ0123456789";
  1474. tp->orig_file_number = 1;
  1475. }
  1476. } // namespace
  1477. TEST_F(TablePropertyTest, UniqueIdHumanStrings) {
  1478. TableProperties tp;
  1479. SetGoodTableProperties(&tp);
  1480. std::string tmp;
  1481. EXPECT_OK(GetExtendedUniqueIdFromTableProperties(tp, &tmp));
  1482. EXPECT_EQ(tmp,
  1483. (std::string{{'\x64', '\x74', '\xdf', '\x65', '\x03', '\x23',
  1484. '\xbd', '\xf0', '\xb4', '\x8e', '\x64', '\xf3',
  1485. '\x03', '\x93', '\x08', '\xca', '\x17', '\x28',
  1486. '\x4b', '\x32', '\xe7', '\xf7', '\x44', '\x4b'}}));
  1487. EXPECT_EQ(UniqueIdToHumanString(tmp),
  1488. "6474DF650323BDF0-B48E64F3039308CA-17284B32E7F7444B");
  1489. EXPECT_OK(GetUniqueIdFromTableProperties(tp, &tmp));
  1490. EXPECT_EQ(UniqueIdToHumanString(tmp), "6474DF650323BDF0-B48E64F3039308CA");
  1491. // including zero padding
  1492. tmp = std::string(24U, '\0');
  1493. tmp[15] = '\x12';
  1494. tmp[23] = '\xAB';
  1495. EXPECT_EQ(UniqueIdToHumanString(tmp),
  1496. "0000000000000000-0000000000000012-00000000000000AB");
  1497. // And shortened
  1498. tmp = std::string(20U, '\0');
  1499. tmp[5] = '\x12';
  1500. tmp[10] = '\xAB';
  1501. tmp[17] = '\xEF';
  1502. EXPECT_EQ(UniqueIdToHumanString(tmp),
  1503. "0000000000120000-0000AB0000000000-00EF0000");
  1504. tmp.resize(16);
  1505. EXPECT_EQ(UniqueIdToHumanString(tmp), "0000000000120000-0000AB0000000000");
  1506. tmp.resize(11);
  1507. EXPECT_EQ(UniqueIdToHumanString(tmp), "0000000000120000-0000AB");
  1508. tmp.resize(6);
  1509. EXPECT_EQ(UniqueIdToHumanString(tmp), "000000000012");
  1510. // Also internal IDs to human string
  1511. UniqueId64x3 euid = {12345, 678, 9};
  1512. EXPECT_EQ(InternalUniqueIdToHumanString(&euid), "{12345,678,9}");
  1513. UniqueId64x2 uid = {1234, 567890};
  1514. EXPECT_EQ(InternalUniqueIdToHumanString(&uid), "{1234,567890}");
  1515. }
  1516. TEST_F(TablePropertyTest, UniqueIdsFailure) {
  1517. TableProperties tp;
  1518. std::string tmp;
  1519. // Missing DB id
  1520. SetGoodTableProperties(&tp);
  1521. tp.db_id = "";
  1522. EXPECT_TRUE(GetUniqueIdFromTableProperties(tp, &tmp).IsNotSupported());
  1523. EXPECT_TRUE(
  1524. GetExtendedUniqueIdFromTableProperties(tp, &tmp).IsNotSupported());
  1525. // Missing session id
  1526. SetGoodTableProperties(&tp);
  1527. tp.db_session_id = "";
  1528. EXPECT_TRUE(GetUniqueIdFromTableProperties(tp, &tmp).IsNotSupported());
  1529. EXPECT_TRUE(
  1530. GetExtendedUniqueIdFromTableProperties(tp, &tmp).IsNotSupported());
  1531. // Missing file number
  1532. SetGoodTableProperties(&tp);
  1533. tp.orig_file_number = 0;
  1534. EXPECT_TRUE(GetUniqueIdFromTableProperties(tp, &tmp).IsNotSupported());
  1535. EXPECT_TRUE(
  1536. GetExtendedUniqueIdFromTableProperties(tp, &tmp).IsNotSupported());
  1537. }
  1538. // This test include all the basic checks except those for index size and block
  1539. // size, which will be conducted in separated unit tests.
  1540. TEST_P(BlockBasedTableTest, BasicBlockBasedTableProperties) {
  1541. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  1542. c.Add("a1", "val1");
  1543. c.Add("b2", "val2");
  1544. c.Add("c3", "val3");
  1545. c.Add("d4", "val4");
  1546. c.Add("e5", "val5");
  1547. c.Add("f6", "val6");
  1548. c.Add("g7", "val7");
  1549. c.Add("h8", "val8");
  1550. c.Add("j9", "val9");
  1551. uint64_t diff_internal_user_bytes = 9 * 8; // 8 is seq size, 9 k-v totally
  1552. std::vector<std::string> keys;
  1553. stl_wrappers::KVMap kvmap;
  1554. Options options;
  1555. options.compression = kNoCompression;
  1556. options.statistics = CreateDBStatistics();
  1557. options.statistics->set_stats_level(StatsLevel::kAll);
  1558. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1559. table_options.block_restart_interval = 1;
  1560. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1561. ImmutableOptions ioptions(options);
  1562. MutableCFOptions moptions(options);
  1563. c.Finish(options, ioptions, moptions, table_options,
  1564. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  1565. ASSERT_EQ(
  1566. options.statistics->getTickerCount(NUMBER_BLOCK_COMPRESSION_REJECTED), 0);
  1567. auto& props = *c.GetTableReader()->GetTableProperties();
  1568. ASSERT_EQ(kvmap.size(), props.num_entries);
  1569. auto raw_key_size = kvmap.size() * 2ul;
  1570. auto raw_value_size = kvmap.size() * 4ul;
  1571. ASSERT_EQ(raw_key_size + diff_internal_user_bytes, props.raw_key_size);
  1572. ASSERT_EQ(raw_value_size, props.raw_value_size);
  1573. ASSERT_EQ(1ul, props.num_data_blocks);
  1574. ASSERT_EQ("", props.filter_policy_name); // no filter policy is used
  1575. // Verify data size.
  1576. BlockBuilder block_builder(1);
  1577. for (const auto& item : kvmap) {
  1578. block_builder.Add(item.first, item.second);
  1579. }
  1580. Slice content = block_builder.Finish();
  1581. ASSERT_EQ(content.size() + BlockBasedTable::kBlockTrailerSize +
  1582. diff_internal_user_bytes,
  1583. props.data_size);
  1584. c.ResetTableReader();
  1585. }
  1586. #ifdef SNAPPY
  1587. uint64_t BlockBasedTableTest::IndexUncompressedHelper(bool compressed) {
  1588. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  1589. constexpr size_t kNumKeys = 10000;
  1590. for (size_t k = 0; k < kNumKeys; ++k) {
  1591. c.Add("key" + std::to_string(k), "val" + std::to_string(k));
  1592. }
  1593. std::vector<std::string> keys;
  1594. stl_wrappers::KVMap kvmap;
  1595. Options options;
  1596. options.compression = kSnappyCompression;
  1597. options.statistics = CreateDBStatistics();
  1598. options.statistics->set_stats_level(StatsLevel::kAll);
  1599. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1600. table_options.block_restart_interval = 1;
  1601. table_options.enable_index_compression = compressed;
  1602. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1603. ImmutableOptions ioptions(options);
  1604. MutableCFOptions moptions(options);
  1605. c.Finish(options, ioptions, moptions, table_options,
  1606. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  1607. c.ResetTableReader();
  1608. return options.statistics->getTickerCount(NUMBER_BLOCK_COMPRESSED);
  1609. }
  1610. TEST_P(BlockBasedTableTest, IndexUncompressed) {
  1611. uint64_t tbl1_compressed_cnt = IndexUncompressedHelper(true);
  1612. uint64_t tbl2_compressed_cnt = IndexUncompressedHelper(false);
  1613. // tbl1_compressed_cnt should include 1 index block
  1614. EXPECT_EQ(tbl2_compressed_cnt + 1, tbl1_compressed_cnt);
  1615. }
  1616. #endif // SNAPPY
  1617. TEST_P(BlockBasedTableTest, BlockBasedTableProperties2) {
  1618. TableConstructor c(&reverse_key_comparator,
  1619. true /* convert_to_internal_key_ */);
  1620. std::vector<std::string> keys;
  1621. stl_wrappers::KVMap kvmap;
  1622. for (CompressionType ct : {kNoCompression, kSnappyCompression}) {
  1623. if (!Snappy_Supported() && ct == kSnappyCompression) {
  1624. continue;
  1625. }
  1626. Options options;
  1627. options.compression = ct;
  1628. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1629. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1630. const ImmutableOptions ioptions(options);
  1631. const MutableCFOptions moptions(options);
  1632. c.Add("blah", std::string(200, 'x')); // something to compress
  1633. c.Finish(options, ioptions, moptions, table_options,
  1634. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  1635. auto& props = *c.GetTableReader()->GetTableProperties();
  1636. // Default comparator
  1637. ASSERT_EQ("leveldb.BytewiseComparator", props.comparator_name);
  1638. // No merge operator
  1639. ASSERT_EQ("nullptr", props.merge_operator_name);
  1640. // No prefix extractor
  1641. ASSERT_EQ("nullptr", props.prefix_extractor_name);
  1642. // No property collectors
  1643. ASSERT_EQ("[]", props.property_collectors_names);
  1644. // No filter policy is used
  1645. ASSERT_EQ("", props.filter_policy_name);
  1646. // Compression type == that set:
  1647. if (FormatVersionUsesCompressionManagerName(table_options.format_version)) {
  1648. ASSERT_EQ(ct == kNoCompression ? ";;" : "BuiltinV2;01;",
  1649. props.compression_name);
  1650. } else {
  1651. ASSERT_EQ(ct == kNoCompression ? "NoCompression" : "Snappy",
  1652. props.compression_name);
  1653. }
  1654. c.ResetTableReader();
  1655. }
  1656. {
  1657. Options options;
  1658. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1659. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1660. options.comparator = &reverse_key_comparator;
  1661. options.merge_operator = MergeOperators::CreateUInt64AddOperator();
  1662. options.prefix_extractor.reset(NewNoopTransform());
  1663. options.table_properties_collector_factories.emplace_back(
  1664. new DummyPropertiesCollectorFactory1());
  1665. options.table_properties_collector_factories.emplace_back(
  1666. new DummyPropertiesCollectorFactory2());
  1667. const ImmutableOptions ioptions(options);
  1668. const MutableCFOptions moptions(options);
  1669. c.Finish(options, ioptions, moptions, table_options,
  1670. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  1671. auto& props = *c.GetTableReader()->GetTableProperties();
  1672. ASSERT_EQ("rocksdb.ReverseBytewiseComparator", props.comparator_name);
  1673. ASSERT_EQ("UInt64AddOperator", props.merge_operator_name);
  1674. ASSERT_EQ("rocksdb.Noop", props.prefix_extractor_name);
  1675. ASSERT_EQ(
  1676. "[DummyPropertiesCollectorFactory1,DummyPropertiesCollectorFactory2]",
  1677. props.property_collectors_names);
  1678. ASSERT_EQ("", props.filter_policy_name); // no filter policy is used
  1679. c.ResetTableReader();
  1680. }
  1681. }
  1682. TEST_P(BlockBasedTableTest, RangeDelBlock) {
  1683. TableConstructor c(BytewiseComparator());
  1684. std::vector<std::string> keys = {"1pika", "2chu"};
  1685. std::vector<std::string> vals = {"p", "c"};
  1686. std::vector<RangeTombstone> expected_tombstones = {
  1687. {"1pika", "2chu", 0},
  1688. {"2chu", "c", 1},
  1689. {"2chu", "c", 0},
  1690. {"c", "p", 0},
  1691. };
  1692. for (int i = 0; i < 2; i++) {
  1693. RangeTombstone t(keys[i], vals[i], i);
  1694. std::pair<InternalKey, Slice> p = t.Serialize();
  1695. c.Add(p.first.Encode().ToString(), p.second);
  1696. }
  1697. std::vector<std::string> sorted_keys;
  1698. stl_wrappers::KVMap kvmap;
  1699. Options options;
  1700. options.compression = kNoCompression;
  1701. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1702. table_options.block_restart_interval = 1;
  1703. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1704. const ImmutableOptions ioptions(options);
  1705. const MutableCFOptions moptions(options);
  1706. std::unique_ptr<InternalKeyComparator> internal_cmp(
  1707. new InternalKeyComparator(options.comparator));
  1708. c.Finish(options, ioptions, moptions, table_options, *internal_cmp,
  1709. &sorted_keys, &kvmap);
  1710. for (int j = 0; j < 2; ++j) {
  1711. std::unique_ptr<InternalIterator> iter(
  1712. c.GetTableReader()->NewRangeTombstoneIterator(ReadOptions()));
  1713. if (j > 0) {
  1714. // For second iteration, delete the table reader object and verify the
  1715. // iterator can still access its metablock's range tombstones.
  1716. c.ResetTableReader();
  1717. }
  1718. ASSERT_FALSE(iter->Valid());
  1719. iter->SeekToFirst();
  1720. ASSERT_TRUE(iter->Valid());
  1721. for (size_t i = 0; i < expected_tombstones.size(); i++) {
  1722. ASSERT_TRUE(iter->Valid());
  1723. ParsedInternalKey parsed_key;
  1724. ASSERT_OK(
  1725. ParseInternalKey(iter->key(), &parsed_key, true /* log_err_key */));
  1726. RangeTombstone t(parsed_key, iter->value());
  1727. const auto& expected_t = expected_tombstones[i];
  1728. ASSERT_EQ(t.start_key_, expected_t.start_key_);
  1729. ASSERT_EQ(t.end_key_, expected_t.end_key_);
  1730. ASSERT_EQ(t.seq_, expected_t.seq_);
  1731. iter->Next();
  1732. }
  1733. ASSERT_TRUE(!iter->Valid());
  1734. }
  1735. }
  1736. TEST_P(BlockBasedTableTest, FilterPolicyNameProperties) {
  1737. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  1738. c.Add("a1", "val1");
  1739. std::vector<std::string> keys;
  1740. stl_wrappers::KVMap kvmap;
  1741. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1742. table_options.filter_policy.reset(NewBloomFilterPolicy(10));
  1743. Options options;
  1744. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1745. const ImmutableOptions ioptions(options);
  1746. const MutableCFOptions moptions(options);
  1747. c.Finish(options, ioptions, moptions, table_options,
  1748. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  1749. auto& props = *c.GetTableReader()->GetTableProperties();
  1750. ASSERT_EQ(table_options.filter_policy->Name(), props.filter_policy_name);
  1751. c.ResetTableReader();
  1752. }
  1753. //
  1754. // BlockBasedTableTest::PrefetchTest
  1755. //
  1756. void AssertKeysInCache(BlockBasedTable* table_reader,
  1757. const std::vector<std::string>& keys_in_cache,
  1758. const std::vector<std::string>& keys_not_in_cache,
  1759. bool convert = false) {
  1760. if (convert) {
  1761. for (const auto& key : keys_in_cache) {
  1762. InternalKey ikey(key, kMaxSequenceNumber, kTypeValue);
  1763. ASSERT_TRUE(table_reader->TEST_KeyInCache(ReadOptions(), ikey.Encode()));
  1764. }
  1765. for (const auto& key : keys_not_in_cache) {
  1766. InternalKey ikey(key, kMaxSequenceNumber, kTypeValue);
  1767. ASSERT_TRUE(!table_reader->TEST_KeyInCache(ReadOptions(), ikey.Encode()));
  1768. }
  1769. } else {
  1770. for (const auto& key : keys_in_cache) {
  1771. ASSERT_TRUE(table_reader->TEST_KeyInCache(ReadOptions(), key));
  1772. }
  1773. for (const auto& key : keys_not_in_cache) {
  1774. ASSERT_TRUE(!table_reader->TEST_KeyInCache(ReadOptions(), key));
  1775. }
  1776. }
  1777. }
  1778. void PrefetchRange(TableConstructor* c, Options* opt,
  1779. BlockBasedTableOptions* table_options, const char* key_begin,
  1780. const char* key_end,
  1781. const std::vector<std::string>& keys_in_cache,
  1782. const std::vector<std::string>& keys_not_in_cache,
  1783. const Status expected_status = Status::OK()) {
  1784. // reset the cache and reopen the table
  1785. table_options->block_cache = NewLRUCache(16 * 1024 * 1024, 4);
  1786. opt->table_factory.reset(NewBlockBasedTableFactory(*table_options));
  1787. const ImmutableOptions ioptions2(*opt);
  1788. const MutableCFOptions moptions(*opt);
  1789. ASSERT_OK(c->Reopen(ioptions2, moptions));
  1790. // prefetch
  1791. auto* table_reader = dynamic_cast<BlockBasedTable*>(c->GetTableReader());
  1792. Status s;
  1793. std::unique_ptr<Slice> begin, end;
  1794. std::unique_ptr<InternalKey> i_begin, i_end;
  1795. if (key_begin != nullptr) {
  1796. if (c->ConvertToInternalKey()) {
  1797. i_begin.reset(new InternalKey(key_begin, kMaxSequenceNumber, kTypeValue));
  1798. begin.reset(new Slice(i_begin->Encode()));
  1799. } else {
  1800. begin.reset(new Slice(key_begin));
  1801. }
  1802. }
  1803. if (key_end != nullptr) {
  1804. if (c->ConvertToInternalKey()) {
  1805. i_end.reset(new InternalKey(key_end, kMaxSequenceNumber, kTypeValue));
  1806. end.reset(new Slice(i_end->Encode()));
  1807. } else {
  1808. end.reset(new Slice(key_end));
  1809. }
  1810. }
  1811. const ReadOptions read_options;
  1812. s = table_reader->Prefetch(read_options, begin.get(), end.get());
  1813. ASSERT_TRUE(s.code() == expected_status.code());
  1814. // assert our expectation in cache warmup
  1815. AssertKeysInCache(table_reader, keys_in_cache, keys_not_in_cache,
  1816. c->ConvertToInternalKey());
  1817. c->ResetTableReader();
  1818. }
  1819. TEST_P(BlockBasedTableTest, PrefetchTest) {
  1820. // The purpose of this test is to test the prefetching operation built into
  1821. // BlockBasedTable.
  1822. Options opt;
  1823. std::unique_ptr<InternalKeyComparator> ikc;
  1824. ikc.reset(new test::PlainInternalKeyComparator(opt.comparator));
  1825. opt.compression = kNoCompression;
  1826. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1827. table_options.block_size = 1024;
  1828. // big enough so we don't ever lose cached values.
  1829. table_options.block_cache = NewLRUCache(16 * 1024 * 1024, 4);
  1830. opt.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1831. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  1832. c.Add("k01", "hello");
  1833. c.Add("k02", "hello2");
  1834. c.Add("k03", std::string(10000, 'x'));
  1835. c.Add("k04", std::string(200000, 'x'));
  1836. c.Add("k05", std::string(300000, 'x'));
  1837. c.Add("k06", "hello3");
  1838. c.Add("k07", std::string(100000, 'x'));
  1839. std::vector<std::string> keys;
  1840. stl_wrappers::KVMap kvmap;
  1841. const ImmutableOptions ioptions(opt);
  1842. const MutableCFOptions moptions(opt);
  1843. c.Finish(opt, ioptions, moptions, table_options, *ikc, &keys, &kvmap);
  1844. c.ResetTableReader();
  1845. // We get the following data spread :
  1846. //
  1847. // Data block Index
  1848. // ========================
  1849. // [ k01 k02 k03 ] k03
  1850. // [ k04 ] k04
  1851. // [ k05 ] k05
  1852. // [ k06 k07 ] k07
  1853. // Simple
  1854. PrefetchRange(&c, &opt, &table_options,
  1855. /*key_begin=*/"k01", /*key_end=*/"k05",
  1856. /*keys_in_cache=*/{"k01", "k02", "k03", "k04", "k05"},
  1857. /*keys_not_in_cache=*/{"k06", "k07"});
  1858. PrefetchRange(&c, &opt, &table_options, "k01", "k01", {"k01", "k02", "k03"},
  1859. {"k04", "k05", "k06", "k07"});
  1860. // odd
  1861. PrefetchRange(&c, &opt, &table_options, "a", "z",
  1862. {"k01", "k02", "k03", "k04", "k05", "k06", "k07"}, {});
  1863. PrefetchRange(&c, &opt, &table_options, "k00", "k00", {"k01", "k02", "k03"},
  1864. {"k04", "k05", "k06", "k07"});
  1865. // Edge cases
  1866. PrefetchRange(&c, &opt, &table_options, "k00", "k06",
  1867. {"k01", "k02", "k03", "k04", "k05", "k06", "k07"}, {});
  1868. PrefetchRange(&c, &opt, &table_options, "k00", "zzz",
  1869. {"k01", "k02", "k03", "k04", "k05", "k06", "k07"}, {});
  1870. // null keys
  1871. PrefetchRange(&c, &opt, &table_options, nullptr, nullptr,
  1872. {"k01", "k02", "k03", "k04", "k05", "k06", "k07"}, {});
  1873. PrefetchRange(&c, &opt, &table_options, "k04", nullptr,
  1874. {"k04", "k05", "k06", "k07"}, {"k01", "k02", "k03"});
  1875. PrefetchRange(&c, &opt, &table_options, nullptr, "k05",
  1876. {"k01", "k02", "k03", "k04", "k05"}, {"k06", "k07"});
  1877. // invalid
  1878. PrefetchRange(&c, &opt, &table_options, "k06", "k00", {}, {},
  1879. Status::InvalidArgument(Slice("k06 "), Slice("k07")));
  1880. c.ResetTableReader();
  1881. }
  1882. TEST_P(BlockBasedTableTest, TotalOrderSeekOnHashIndex) {
  1883. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1884. for (int i = 0; i <= 4; ++i) {
  1885. Options options;
  1886. // Make each key/value an individual block
  1887. table_options.block_size = 64;
  1888. switch (i) {
  1889. case 0:
  1890. // Binary search index
  1891. table_options.index_type = BlockBasedTableOptions::kBinarySearch;
  1892. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  1893. break;
  1894. case 1:
  1895. // Hash search index
  1896. table_options.index_type = BlockBasedTableOptions::kHashSearch;
  1897. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  1898. options.prefix_extractor.reset(NewFixedPrefixTransform(4));
  1899. break;
  1900. case 2:
  1901. // Hash search index with filter policy
  1902. table_options.index_type = BlockBasedTableOptions::kHashSearch;
  1903. table_options.filter_policy.reset(NewBloomFilterPolicy(10));
  1904. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  1905. options.prefix_extractor.reset(NewFixedPrefixTransform(4));
  1906. break;
  1907. case 3:
  1908. // Two-level index
  1909. table_options.index_type = BlockBasedTableOptions::kTwoLevelIndexSearch;
  1910. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  1911. break;
  1912. case 4:
  1913. // Binary search with first key
  1914. table_options.index_type =
  1915. BlockBasedTableOptions::kBinarySearchWithFirstKey;
  1916. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  1917. break;
  1918. }
  1919. TableConstructor c(BytewiseComparator(),
  1920. true /* convert_to_internal_key_ */);
  1921. c.Add("aaaa1", std::string('a', 56));
  1922. c.Add("bbaa1", std::string('a', 56));
  1923. c.Add("cccc1", std::string('a', 56));
  1924. c.Add("bbbb1", std::string('a', 56));
  1925. c.Add("baaa1", std::string('a', 56));
  1926. c.Add("abbb1", std::string('a', 56));
  1927. c.Add("cccc2", std::string('a', 56));
  1928. std::vector<std::string> keys;
  1929. stl_wrappers::KVMap kvmap;
  1930. const ImmutableOptions ioptions(options);
  1931. const MutableCFOptions moptions(options);
  1932. c.Finish(options, ioptions, moptions, table_options,
  1933. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  1934. auto props = c.GetTableReader()->GetTableProperties();
  1935. ASSERT_EQ(7u, props->num_data_blocks);
  1936. auto* reader = c.GetTableReader();
  1937. ReadOptions ro;
  1938. ro.total_order_seek = true;
  1939. std::unique_ptr<InternalIterator> iter(reader->NewIterator(
  1940. ro, moptions.prefix_extractor.get(), /*arena=*/nullptr,
  1941. /*skip_filters=*/false, TableReaderCaller::kUncategorized));
  1942. iter->Seek(InternalKey("b", 0, kTypeValue).Encode());
  1943. ASSERT_OK(iter->status());
  1944. ASSERT_TRUE(iter->Valid());
  1945. ASSERT_EQ("baaa1", ExtractUserKey(iter->key()).ToString());
  1946. iter->Next();
  1947. ASSERT_OK(iter->status());
  1948. ASSERT_TRUE(iter->Valid());
  1949. ASSERT_EQ("bbaa1", ExtractUserKey(iter->key()).ToString());
  1950. iter->Seek(InternalKey("bb", 0, kTypeValue).Encode());
  1951. ASSERT_OK(iter->status());
  1952. ASSERT_TRUE(iter->Valid());
  1953. ASSERT_EQ("bbaa1", ExtractUserKey(iter->key()).ToString());
  1954. iter->Next();
  1955. ASSERT_OK(iter->status());
  1956. ASSERT_TRUE(iter->Valid());
  1957. ASSERT_EQ("bbbb1", ExtractUserKey(iter->key()).ToString());
  1958. iter->Seek(InternalKey("bbb", 0, kTypeValue).Encode());
  1959. ASSERT_OK(iter->status());
  1960. ASSERT_TRUE(iter->Valid());
  1961. ASSERT_EQ("bbbb1", ExtractUserKey(iter->key()).ToString());
  1962. iter->Next();
  1963. ASSERT_OK(iter->status());
  1964. ASSERT_TRUE(iter->Valid());
  1965. ASSERT_EQ("cccc1", ExtractUserKey(iter->key()).ToString());
  1966. }
  1967. }
  1968. TEST_P(BlockBasedTableTest, NoopTransformSeek) {
  1969. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1970. table_options.filter_policy.reset(NewBloomFilterPolicy(10));
  1971. Options options;
  1972. options.comparator = BytewiseComparator();
  1973. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  1974. options.prefix_extractor.reset(NewNoopTransform());
  1975. TableConstructor c(options.comparator);
  1976. // To tickle the PrefixMayMatch bug it is important that the
  1977. // user-key is a single byte so that the index key exactly matches
  1978. // the user-key.
  1979. InternalKey key("a", 1, kTypeValue);
  1980. c.Add(key.Encode().ToString(), "b");
  1981. std::vector<std::string> keys;
  1982. stl_wrappers::KVMap kvmap;
  1983. const ImmutableOptions ioptions(options);
  1984. const MutableCFOptions moptions(options);
  1985. const InternalKeyComparator internal_comparator(options.comparator);
  1986. c.Finish(options, ioptions, moptions, table_options, internal_comparator,
  1987. &keys, &kvmap);
  1988. auto* reader = c.GetTableReader();
  1989. for (int i = 0; i < 2; ++i) {
  1990. ReadOptions ro;
  1991. ro.total_order_seek = (i == 0);
  1992. std::unique_ptr<InternalIterator> iter(reader->NewIterator(
  1993. ro, moptions.prefix_extractor.get(), /*arena=*/nullptr,
  1994. /*skip_filters=*/false, TableReaderCaller::kUncategorized));
  1995. iter->Seek(key.Encode());
  1996. ASSERT_OK(iter->status());
  1997. ASSERT_TRUE(iter->Valid());
  1998. ASSERT_EQ("a", ExtractUserKey(iter->key()).ToString());
  1999. }
  2000. }
  2001. TEST_P(BlockBasedTableTest, SkipPrefixBloomFilter) {
  2002. // if DB is opened with a prefix extractor of a different name,
  2003. // prefix bloom is skipped when read the file
  2004. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2005. table_options.filter_policy.reset(NewBloomFilterPolicy(2));
  2006. table_options.whole_key_filtering = false;
  2007. Options options;
  2008. options.comparator = BytewiseComparator();
  2009. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  2010. options.prefix_extractor.reset(NewFixedPrefixTransform(1));
  2011. TableConstructor c(options.comparator);
  2012. InternalKey key("abcdefghijk", 1, kTypeValue);
  2013. c.Add(key.Encode().ToString(), "test");
  2014. std::vector<std::string> keys;
  2015. stl_wrappers::KVMap kvmap;
  2016. const ImmutableOptions ioptions(options);
  2017. const MutableCFOptions moptions(options);
  2018. const InternalKeyComparator internal_comparator(options.comparator);
  2019. c.Finish(options, ioptions, moptions, table_options, internal_comparator,
  2020. &keys, &kvmap);
  2021. // TODO(Zhongyi): update test to use MutableCFOptions
  2022. options.prefix_extractor.reset(NewFixedPrefixTransform(9));
  2023. const ImmutableOptions new_ioptions(options);
  2024. const MutableCFOptions new_moptions(options);
  2025. ASSERT_OK(c.Reopen(new_ioptions, new_moptions));
  2026. auto reader = c.GetTableReader();
  2027. ReadOptions read_options;
  2028. std::unique_ptr<InternalIterator> db_iter(reader->NewIterator(
  2029. read_options, new_moptions.prefix_extractor.get(), /*arena=*/nullptr,
  2030. /*skip_filters=*/false, TableReaderCaller::kUncategorized));
  2031. // Test point lookup
  2032. // only one kv
  2033. for (auto& kv : kvmap) {
  2034. db_iter->Seek(kv.first);
  2035. ASSERT_TRUE(db_iter->Valid());
  2036. ASSERT_OK(db_iter->status());
  2037. ASSERT_EQ(db_iter->key(), kv.first);
  2038. ASSERT_EQ(db_iter->value(), kv.second);
  2039. }
  2040. }
  2041. TEST_P(BlockBasedTableTest, BadChecksumType) {
  2042. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2043. Options options;
  2044. options.comparator = BytewiseComparator();
  2045. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  2046. TableConstructor c(options.comparator);
  2047. InternalKey key("abc", 1, kTypeValue);
  2048. c.Add(key.Encode().ToString(), "test");
  2049. std::vector<std::string> keys;
  2050. stl_wrappers::KVMap kvmap;
  2051. const ImmutableOptions ioptions(options);
  2052. const MutableCFOptions moptions(options);
  2053. const InternalKeyComparator internal_comparator(options.comparator);
  2054. c.Finish(options, ioptions, moptions, table_options, internal_comparator,
  2055. &keys, &kvmap);
  2056. // Corrupt checksum type (123 is invalid)
  2057. auto& sink = *c.TEST_GetSink();
  2058. size_t len = sink.contents_.size();
  2059. ASSERT_EQ(sink.contents_[len - Footer::kNewVersionsEncodedLength],
  2060. table_options.checksum);
  2061. sink.contents_[len - Footer::kNewVersionsEncodedLength] = char{123};
  2062. // (Re-)Open table file with bad checksum type
  2063. const ImmutableOptions new_ioptions(options);
  2064. const MutableCFOptions new_moptions(options);
  2065. Status s = c.Reopen(new_ioptions, new_moptions);
  2066. ASSERT_NOK(s);
  2067. // "test" is file name
  2068. ASSERT_EQ(s.ToString(),
  2069. "Corruption: Corrupt or unsupported checksum type: 123 in test");
  2070. }
  2071. class BuiltinChecksumTest : public testing::Test,
  2072. public testing::WithParamInterface<ChecksumType> {};
  2073. INSTANTIATE_TEST_CASE_P(SupportedChecksums, BuiltinChecksumTest,
  2074. testing::ValuesIn(GetSupportedChecksums()));
  2075. namespace {
  2076. std::string ChecksumAsString(const std::string& data,
  2077. ChecksumType checksum_type) {
  2078. uint32_t v = ComputeBuiltinChecksum(checksum_type, data.data(), data.size());
  2079. // Verify consistency with other function
  2080. if (data.size() >= 1) {
  2081. EXPECT_EQ(v, ComputeBuiltinChecksumWithLastByte(
  2082. checksum_type, data.data(), data.size() - 1, data.back()));
  2083. }
  2084. // Little endian as in file
  2085. std::array<char, 4> raw_bytes;
  2086. EncodeFixed32(raw_bytes.data(), v);
  2087. return Slice(raw_bytes.data(), raw_bytes.size()).ToString(/*hex*/ true);
  2088. }
  2089. std::string ChecksumAsString(std::string* data, char new_last_byte,
  2090. ChecksumType checksum_type) {
  2091. data->back() = new_last_byte;
  2092. return ChecksumAsString(*data, checksum_type);
  2093. }
  2094. } // namespace
  2095. // Make sure that checksum values don't change in later versions, even if
  2096. // consistent within current version.
  2097. TEST_P(BuiltinChecksumTest, ChecksumSchemas) {
  2098. // Trailing 'x' chars will be replaced by compression type. Specifically,
  2099. // the first byte of a block trailer is compression type, which is part of
  2100. // the checksum input. This test does not deal with storing or parsing
  2101. // checksums from the trailer (next 4 bytes of trailer).
  2102. std::string b0 = "x";
  2103. std::string b1 = "This is a short block!x";
  2104. std::string b2;
  2105. for (int i = 0; i < 100; ++i) {
  2106. b2.append("This is a long block!");
  2107. }
  2108. b2.append("x");
  2109. std::string empty;
  2110. char ct1 = kNoCompression;
  2111. char ct2 = kSnappyCompression;
  2112. char ct3 = kZSTD;
  2113. ChecksumType t = GetParam();
  2114. switch (t) {
  2115. case kNoChecksum:
  2116. EXPECT_EQ(ChecksumAsString(empty, t), "00000000");
  2117. EXPECT_EQ(ChecksumAsString(&b0, ct1, t), "00000000");
  2118. EXPECT_EQ(ChecksumAsString(&b0, ct2, t), "00000000");
  2119. EXPECT_EQ(ChecksumAsString(&b0, ct3, t), "00000000");
  2120. EXPECT_EQ(ChecksumAsString(&b1, ct1, t), "00000000");
  2121. EXPECT_EQ(ChecksumAsString(&b1, ct2, t), "00000000");
  2122. EXPECT_EQ(ChecksumAsString(&b1, ct3, t), "00000000");
  2123. EXPECT_EQ(ChecksumAsString(&b2, ct1, t), "00000000");
  2124. EXPECT_EQ(ChecksumAsString(&b2, ct2, t), "00000000");
  2125. EXPECT_EQ(ChecksumAsString(&b2, ct3, t), "00000000");
  2126. break;
  2127. case kCRC32c:
  2128. EXPECT_EQ(ChecksumAsString(empty, t), "D8EA82A2");
  2129. EXPECT_EQ(ChecksumAsString(&b0, ct1, t), "D28F2549");
  2130. EXPECT_EQ(ChecksumAsString(&b0, ct2, t), "052B2843");
  2131. EXPECT_EQ(ChecksumAsString(&b0, ct3, t), "46F8F711");
  2132. EXPECT_EQ(ChecksumAsString(&b1, ct1, t), "583F0355");
  2133. EXPECT_EQ(ChecksumAsString(&b1, ct2, t), "2F9B0A57");
  2134. EXPECT_EQ(ChecksumAsString(&b1, ct3, t), "ECE7DA1D");
  2135. EXPECT_EQ(ChecksumAsString(&b2, ct1, t), "943EF0AB");
  2136. EXPECT_EQ(ChecksumAsString(&b2, ct2, t), "43A2EDB1");
  2137. EXPECT_EQ(ChecksumAsString(&b2, ct3, t), "00E53D63");
  2138. break;
  2139. case kxxHash:
  2140. EXPECT_EQ(ChecksumAsString(empty, t), "055DCC02");
  2141. EXPECT_EQ(ChecksumAsString(&b0, ct1, t), "3EB065CF");
  2142. EXPECT_EQ(ChecksumAsString(&b0, ct2, t), "31F79238");
  2143. EXPECT_EQ(ChecksumAsString(&b0, ct3, t), "320D2E00");
  2144. EXPECT_EQ(ChecksumAsString(&b1, ct1, t), "4A2E5FB0");
  2145. EXPECT_EQ(ChecksumAsString(&b1, ct2, t), "0BD9F652");
  2146. EXPECT_EQ(ChecksumAsString(&b1, ct3, t), "B4107E50");
  2147. EXPECT_EQ(ChecksumAsString(&b2, ct1, t), "20F4D4BA");
  2148. EXPECT_EQ(ChecksumAsString(&b2, ct2, t), "8F1A1F99");
  2149. EXPECT_EQ(ChecksumAsString(&b2, ct3, t), "A191A338");
  2150. break;
  2151. case kxxHash64:
  2152. EXPECT_EQ(ChecksumAsString(empty, t), "99E9D851");
  2153. EXPECT_EQ(ChecksumAsString(&b0, ct1, t), "682705DB");
  2154. EXPECT_EQ(ChecksumAsString(&b0, ct2, t), "30E7211B");
  2155. EXPECT_EQ(ChecksumAsString(&b0, ct3, t), "B7BB58E8");
  2156. EXPECT_EQ(ChecksumAsString(&b1, ct1, t), "B74655EF");
  2157. EXPECT_EQ(ChecksumAsString(&b1, ct2, t), "B6C8BBBE");
  2158. EXPECT_EQ(ChecksumAsString(&b1, ct3, t), "AED9E3B4");
  2159. EXPECT_EQ(ChecksumAsString(&b2, ct1, t), "0D4999FE");
  2160. EXPECT_EQ(ChecksumAsString(&b2, ct2, t), "F5932423");
  2161. EXPECT_EQ(ChecksumAsString(&b2, ct3, t), "6B31BAB1");
  2162. break;
  2163. case kXXH3:
  2164. EXPECT_EQ(ChecksumAsString(empty, t), "00000000");
  2165. EXPECT_EQ(ChecksumAsString(&b0, ct1, t), "C294D338");
  2166. EXPECT_EQ(ChecksumAsString(&b0, ct2, t), "1B174353");
  2167. EXPECT_EQ(ChecksumAsString(&b0, ct3, t), "2D0E20C8");
  2168. EXPECT_EQ(ChecksumAsString(&b1, ct1, t), "B37FB5E6");
  2169. EXPECT_EQ(ChecksumAsString(&b1, ct2, t), "6AFC258D");
  2170. EXPECT_EQ(ChecksumAsString(&b1, ct3, t), "5CE54616");
  2171. EXPECT_EQ(ChecksumAsString(&b2, ct1, t), "FA2D482E");
  2172. EXPECT_EQ(ChecksumAsString(&b2, ct2, t), "23AED845");
  2173. EXPECT_EQ(ChecksumAsString(&b2, ct3, t), "15B7BBDE");
  2174. break;
  2175. default:
  2176. // Force this test to be updated on new ChecksumTypes
  2177. assert(false);
  2178. break;
  2179. }
  2180. }
  2181. TEST_P(BuiltinChecksumTest, ChecksumZeroInputs) {
  2182. // Verify that no reasonably sized "all zeros" inputs produce "all zeros"
  2183. // output. Otherwise, "wiped" data could appear to be well-formed.
  2184. // Assuming essentially random assignment of output values, the likelihood
  2185. // of encountering checksum == 0 for an input not specifically crafted is
  2186. // 1 in 4 billion.
  2187. if (GetParam() == kNoChecksum) {
  2188. return;
  2189. }
  2190. // "Thorough" case is too slow for continouous testing
  2191. bool thorough = getenv("ROCKSDB_THOROUGH_CHECKSUM_TEST") != nullptr;
  2192. // Verified through 10M
  2193. size_t kMaxZerosLen = thorough ? 10000000 : 20000;
  2194. std::string zeros(kMaxZerosLen, '\0');
  2195. for (size_t len = 0; len < kMaxZerosLen; ++len) {
  2196. if (thorough && (len & 0xffffU) == 0) {
  2197. fprintf(stderr, "t=%u len=%u\n", (unsigned)GetParam(), (unsigned)len);
  2198. }
  2199. uint32_t v = ComputeBuiltinChecksum(GetParam(), zeros.data(), len);
  2200. if (v == 0U) {
  2201. // One exception case:
  2202. if (GetParam() == kXXH3 && len == 0) {
  2203. // This is not a big deal because assuming the block length is known
  2204. // from the block handle, which comes from a checksum-verified block,
  2205. // there is nothing to corrupt in a zero-length block. And when there
  2206. // is a block trailer with compression byte (as in block-based table),
  2207. // zero length checksummed data never arises.
  2208. continue;
  2209. }
  2210. // Only compute this on failure
  2211. SCOPED_TRACE("len=" + std::to_string(len));
  2212. ASSERT_NE(v, 0U);
  2213. }
  2214. }
  2215. }
  2216. void AddInternalKey(TableConstructor* c, const std::string& prefix,
  2217. std::string value = "v", int /*suffix_len*/ = 800) {
  2218. static Random rnd(1023);
  2219. InternalKey k(prefix + rnd.RandomString(800), 0, kTypeValue);
  2220. c->Add(k.Encode().ToString(), value);
  2221. }
  2222. void TableTest::IndexTest(BlockBasedTableOptions table_options) {
  2223. TableConstructor c(BytewiseComparator());
  2224. // keys with prefix length 3, make sure the key/value is big enough to fill
  2225. // one block
  2226. AddInternalKey(&c, "0015");
  2227. AddInternalKey(&c, "0035");
  2228. AddInternalKey(&c, "0054");
  2229. AddInternalKey(&c, "0055");
  2230. AddInternalKey(&c, "0056");
  2231. AddInternalKey(&c, "0057");
  2232. AddInternalKey(&c, "0058");
  2233. AddInternalKey(&c, "0075");
  2234. AddInternalKey(&c, "0076");
  2235. AddInternalKey(&c, "0095");
  2236. std::vector<std::string> keys;
  2237. stl_wrappers::KVMap kvmap;
  2238. Options options;
  2239. options.prefix_extractor.reset(NewFixedPrefixTransform(3));
  2240. table_options.block_size = 1700;
  2241. table_options.block_cache = NewLRUCache(1024, 4);
  2242. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2243. std::unique_ptr<InternalKeyComparator> comparator(
  2244. new InternalKeyComparator(BytewiseComparator()));
  2245. const ImmutableOptions ioptions(options);
  2246. const MutableCFOptions moptions(options);
  2247. c.Finish(options, ioptions, moptions, table_options, *comparator, &keys,
  2248. &kvmap);
  2249. auto reader = c.GetTableReader();
  2250. auto props = reader->GetTableProperties();
  2251. ASSERT_EQ(5u, props->num_data_blocks);
  2252. // TODO(Zhongyi): update test to use MutableCFOptions
  2253. ReadOptions read_options;
  2254. std::unique_ptr<InternalIterator> index_iter(reader->NewIterator(
  2255. read_options, moptions.prefix_extractor.get(), /*arena=*/nullptr,
  2256. /*skip_filters=*/false, TableReaderCaller::kUncategorized));
  2257. // -- Find keys do not exist, but have common prefix.
  2258. std::vector<std::string> prefixes = {"001", "003", "005", "007", "009"};
  2259. std::vector<std::string> lower_bound = {
  2260. keys[0], keys[1], keys[2], keys[7], keys[9],
  2261. };
  2262. // find the lower bound of the prefix
  2263. for (size_t i = 0; i < prefixes.size(); ++i) {
  2264. index_iter->Seek(InternalKey(prefixes[i], 0, kTypeValue).Encode());
  2265. ASSERT_OK(index_iter->status());
  2266. ASSERT_TRUE(index_iter->Valid());
  2267. // seek the first element in the block
  2268. ASSERT_EQ(lower_bound[i], index_iter->key().ToString());
  2269. ASSERT_EQ("v", index_iter->value().ToString());
  2270. }
  2271. // find the upper bound of prefixes
  2272. std::vector<std::string> upper_bound = {
  2273. keys[1],
  2274. keys[2],
  2275. keys[7],
  2276. keys[9],
  2277. };
  2278. // find existing keys
  2279. for (const auto& item : kvmap) {
  2280. auto ukey = ExtractUserKey(item.first).ToString();
  2281. index_iter->Seek(ukey);
  2282. // ASSERT_OK(regular_iter->status());
  2283. ASSERT_OK(index_iter->status());
  2284. // ASSERT_TRUE(regular_iter->Valid());
  2285. ASSERT_TRUE(index_iter->Valid());
  2286. ASSERT_EQ(item.first, index_iter->key().ToString());
  2287. ASSERT_EQ(item.second, index_iter->value().ToString());
  2288. }
  2289. for (size_t i = 0; i < prefixes.size(); ++i) {
  2290. // the key is greater than any existing keys.
  2291. auto key = prefixes[i] + "9";
  2292. index_iter->Seek(InternalKey(key, 0, kTypeValue).Encode());
  2293. ASSERT_TRUE(index_iter->status().ok() || index_iter->status().IsNotFound());
  2294. ASSERT_TRUE(!index_iter->status().IsNotFound() || !index_iter->Valid());
  2295. if (i == prefixes.size() - 1) {
  2296. // last key
  2297. ASSERT_TRUE(!index_iter->Valid());
  2298. } else {
  2299. ASSERT_TRUE(index_iter->Valid());
  2300. // seek the first element in the block
  2301. ASSERT_EQ(upper_bound[i], index_iter->key().ToString());
  2302. ASSERT_EQ("v", index_iter->value().ToString());
  2303. }
  2304. }
  2305. // find keys with prefix that don't match any of the existing prefixes.
  2306. std::vector<std::string> non_exist_prefixes = {"002", "004", "006", "008"};
  2307. for (const auto& prefix : non_exist_prefixes) {
  2308. index_iter->Seek(InternalKey(prefix, 0, kTypeValue).Encode());
  2309. // regular_iter->Seek(prefix);
  2310. ASSERT_OK(index_iter->status());
  2311. // Seek to non-existing prefixes should yield either invalid, or a
  2312. // key with prefix greater than the target.
  2313. if (index_iter->Valid()) {
  2314. Slice ukey = ExtractUserKey(index_iter->key());
  2315. Slice ukey_prefix = options.prefix_extractor->Transform(ukey);
  2316. ASSERT_TRUE(BytewiseComparator()->Compare(prefix, ukey_prefix) < 0);
  2317. }
  2318. }
  2319. for (const auto& prefix : non_exist_prefixes) {
  2320. index_iter->SeekForPrev(InternalKey(prefix, 0, kTypeValue).Encode());
  2321. // regular_iter->Seek(prefix);
  2322. ASSERT_OK(index_iter->status());
  2323. // Seek to non-existing prefixes should yield either invalid, or a
  2324. // key with prefix greater than the target.
  2325. if (index_iter->Valid()) {
  2326. Slice ukey = ExtractUserKey(index_iter->key());
  2327. Slice ukey_prefix = options.prefix_extractor->Transform(ukey);
  2328. ASSERT_TRUE(BytewiseComparator()->Compare(prefix, ukey_prefix) > 0);
  2329. }
  2330. }
  2331. {
  2332. // Test reseek case. It should impact partitioned index more.
  2333. ReadOptions ro;
  2334. ro.total_order_seek = true;
  2335. std::unique_ptr<InternalIterator> index_iter2(reader->NewIterator(
  2336. ro, moptions.prefix_extractor.get(), /*arena=*/nullptr,
  2337. /*skip_filters=*/false, TableReaderCaller::kUncategorized));
  2338. // Things to cover in partitioned index:
  2339. // 1. Both of Seek() and SeekToLast() has optimization to prevent
  2340. // rereek leaf index block if it remains to the same one, and
  2341. // they reuse the same variable.
  2342. // 2. When Next() or Prev() is called, the block moves, so the
  2343. // optimization should kick in only with the current one.
  2344. index_iter2->Seek(InternalKey("0055", 0, kTypeValue).Encode());
  2345. ASSERT_TRUE(index_iter2->Valid());
  2346. ASSERT_EQ("0055", index_iter2->key().ToString().substr(0, 4));
  2347. index_iter2->SeekToLast();
  2348. ASSERT_TRUE(index_iter2->Valid());
  2349. ASSERT_EQ("0095", index_iter2->key().ToString().substr(0, 4));
  2350. index_iter2->Seek(InternalKey("0055", 0, kTypeValue).Encode());
  2351. ASSERT_TRUE(index_iter2->Valid());
  2352. ASSERT_EQ("0055", index_iter2->key().ToString().substr(0, 4));
  2353. index_iter2->SeekToLast();
  2354. ASSERT_TRUE(index_iter2->Valid());
  2355. ASSERT_EQ("0095", index_iter2->key().ToString().substr(0, 4));
  2356. index_iter2->Prev();
  2357. ASSERT_TRUE(index_iter2->Valid());
  2358. index_iter2->Prev();
  2359. ASSERT_TRUE(index_iter2->Valid());
  2360. ASSERT_EQ("0075", index_iter2->key().ToString().substr(0, 4));
  2361. index_iter2->Seek(InternalKey("0095", 0, kTypeValue).Encode());
  2362. ASSERT_TRUE(index_iter2->Valid());
  2363. ASSERT_EQ("0095", index_iter2->key().ToString().substr(0, 4));
  2364. index_iter2->Prev();
  2365. ASSERT_TRUE(index_iter2->Valid());
  2366. index_iter2->Prev();
  2367. ASSERT_TRUE(index_iter2->Valid());
  2368. ASSERT_EQ("0075", index_iter2->key().ToString().substr(0, 4));
  2369. index_iter2->SeekToLast();
  2370. ASSERT_TRUE(index_iter2->Valid());
  2371. ASSERT_EQ("0095", index_iter2->key().ToString().substr(0, 4));
  2372. index_iter2->Seek(InternalKey("0095", 0, kTypeValue).Encode());
  2373. ASSERT_TRUE(index_iter2->Valid());
  2374. ASSERT_EQ("0095", index_iter2->key().ToString().substr(0, 4));
  2375. index_iter2->Prev();
  2376. ASSERT_TRUE(index_iter2->Valid());
  2377. index_iter2->Prev();
  2378. ASSERT_TRUE(index_iter2->Valid());
  2379. ASSERT_EQ("0075", index_iter2->key().ToString().substr(0, 4));
  2380. index_iter2->Seek(InternalKey("0075", 0, kTypeValue).Encode());
  2381. ASSERT_TRUE(index_iter2->Valid());
  2382. ASSERT_EQ("0075", index_iter2->key().ToString().substr(0, 4));
  2383. index_iter2->Next();
  2384. ASSERT_TRUE(index_iter2->Valid());
  2385. index_iter2->Next();
  2386. ASSERT_TRUE(index_iter2->Valid());
  2387. ASSERT_EQ("0095", index_iter2->key().ToString().substr(0, 4));
  2388. index_iter2->SeekToLast();
  2389. ASSERT_TRUE(index_iter2->Valid());
  2390. ASSERT_EQ("0095", index_iter2->key().ToString().substr(0, 4));
  2391. }
  2392. c.ResetTableReader();
  2393. }
  2394. TEST_P(BlockBasedTableTest, BinaryIndexTest) {
  2395. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2396. table_options.index_type = BlockBasedTableOptions::kBinarySearch;
  2397. IndexTest(table_options);
  2398. }
  2399. TEST_P(BlockBasedTableTest, HashIndexTest) {
  2400. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2401. table_options.index_type = BlockBasedTableOptions::kHashSearch;
  2402. IndexTest(table_options);
  2403. }
  2404. TEST_P(BlockBasedTableTest, PartitionIndexTest) {
  2405. const int max_index_keys = 5;
  2406. const int est_max_index_key_value_size = 32;
  2407. const int est_max_index_size = max_index_keys * est_max_index_key_value_size;
  2408. for (int i = 1; i <= est_max_index_size + 1; i++) {
  2409. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2410. table_options.index_type = BlockBasedTableOptions::kTwoLevelIndexSearch;
  2411. table_options.metadata_block_size = i;
  2412. IndexTest(table_options);
  2413. }
  2414. }
  2415. TEST_P(BlockBasedTableTest, IndexSeekOptimizationIncomplete) {
  2416. std::unique_ptr<InternalKeyComparator> comparator(
  2417. new InternalKeyComparator(BytewiseComparator()));
  2418. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2419. Options options;
  2420. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2421. const ImmutableOptions ioptions(options);
  2422. const MutableCFOptions moptions(options);
  2423. TableConstructor c(BytewiseComparator());
  2424. AddInternalKey(&c, "pika");
  2425. std::vector<std::string> keys;
  2426. stl_wrappers::KVMap kvmap;
  2427. c.Finish(options, ioptions, moptions, table_options, *comparator, &keys,
  2428. &kvmap);
  2429. ASSERT_EQ(1, keys.size());
  2430. auto reader = c.GetTableReader();
  2431. ReadOptions ropt;
  2432. ropt.read_tier = ReadTier::kBlockCacheTier;
  2433. std::unique_ptr<InternalIterator> iter(reader->NewIterator(
  2434. ropt, /*prefix_extractor=*/nullptr, /*arena=*/nullptr,
  2435. /*skip_filters=*/false, TableReaderCaller::kUncategorized));
  2436. auto ikey = [](Slice user_key) {
  2437. return InternalKey(user_key, 0, kTypeValue).Encode().ToString();
  2438. };
  2439. iter->Seek(ikey("pika"));
  2440. ASSERT_FALSE(iter->Valid());
  2441. ASSERT_TRUE(iter->status().IsIncomplete());
  2442. // This used to crash at some point.
  2443. iter->Seek(ikey("pika"));
  2444. ASSERT_FALSE(iter->Valid());
  2445. ASSERT_TRUE(iter->status().IsIncomplete());
  2446. }
  2447. TEST_P(BlockBasedTableTest, BinaryIndexWithFirstKey1) {
  2448. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2449. table_options.index_type = BlockBasedTableOptions::kBinarySearchWithFirstKey;
  2450. IndexTest(table_options);
  2451. }
  2452. class CustomFlushBlockPolicy : public FlushBlockPolicyFactory,
  2453. public FlushBlockPolicy {
  2454. public:
  2455. explicit CustomFlushBlockPolicy(std::vector<int> keys_per_block)
  2456. : keys_per_block_(keys_per_block) {}
  2457. const char* Name() const override { return "CustomFlushBlockPolicy"; }
  2458. FlushBlockPolicy* NewFlushBlockPolicy(const BlockBasedTableOptions&,
  2459. const BlockBuilder&) const override {
  2460. return new CustomFlushBlockPolicy(keys_per_block_);
  2461. }
  2462. bool Update(const Slice&, const Slice&) override {
  2463. if (keys_in_current_block_ >= keys_per_block_.at(current_block_idx_)) {
  2464. ++current_block_idx_;
  2465. keys_in_current_block_ = 1;
  2466. return true;
  2467. }
  2468. ++keys_in_current_block_;
  2469. return false;
  2470. }
  2471. std::vector<int> keys_per_block_;
  2472. int current_block_idx_ = 0;
  2473. int keys_in_current_block_ = 0;
  2474. };
  2475. TEST_P(BlockBasedTableTest, BinaryIndexWithFirstKey2) {
  2476. for (int use_first_key = 0; use_first_key < 2; ++use_first_key) {
  2477. SCOPED_TRACE("use_first_key = " + std::to_string(use_first_key));
  2478. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2479. table_options.index_type =
  2480. use_first_key ? BlockBasedTableOptions::kBinarySearchWithFirstKey
  2481. : BlockBasedTableOptions::kBinarySearch;
  2482. table_options.block_cache = NewLRUCache(10000); // fits all blocks
  2483. table_options.index_shortening =
  2484. BlockBasedTableOptions::IndexShorteningMode::kNoShortening;
  2485. table_options.flush_block_policy_factory =
  2486. std::make_shared<CustomFlushBlockPolicy>(std::vector<int>{2, 1, 3, 2});
  2487. Options options;
  2488. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2489. options.statistics = CreateDBStatistics();
  2490. Statistics* stats = options.statistics.get();
  2491. std::unique_ptr<InternalKeyComparator> comparator(
  2492. new InternalKeyComparator(BytewiseComparator()));
  2493. const ImmutableOptions ioptions(options);
  2494. const MutableCFOptions moptions(options);
  2495. TableConstructor c(BytewiseComparator());
  2496. // Block 0.
  2497. AddInternalKey(&c, "aaaa", "v0");
  2498. AddInternalKey(&c, "aaac", "v1");
  2499. // Block 1.
  2500. AddInternalKey(&c, "aaca", "v2");
  2501. // Block 2.
  2502. AddInternalKey(&c, "caaa", "v3");
  2503. AddInternalKey(&c, "caac", "v4");
  2504. AddInternalKey(&c, "caae", "v5");
  2505. // Block 3.
  2506. AddInternalKey(&c, "ccaa", "v6");
  2507. AddInternalKey(&c, "ccac", "v7");
  2508. // Write the file.
  2509. std::vector<std::string> keys;
  2510. stl_wrappers::KVMap kvmap;
  2511. c.Finish(options, ioptions, moptions, table_options, *comparator, &keys,
  2512. &kvmap);
  2513. ASSERT_EQ(8, keys.size());
  2514. auto reader = c.GetTableReader();
  2515. auto props = reader->GetTableProperties();
  2516. ASSERT_EQ(4u, props->num_data_blocks);
  2517. ReadOptions read_options;
  2518. std::unique_ptr<InternalIterator> iter(reader->NewIterator(
  2519. read_options, /*prefix_extractor=*/nullptr, /*arena=*/nullptr,
  2520. /*skip_filters=*/false, TableReaderCaller::kUncategorized,
  2521. /*compaction_readahead_size=*/0, /*allow_unprepared_value=*/true));
  2522. // Shouldn't have read data blocks before iterator is seeked.
  2523. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  2524. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2525. auto ikey = [](Slice user_key) {
  2526. return InternalKey(user_key, 0, kTypeValue).Encode().ToString();
  2527. };
  2528. // Seek to a key between blocks. If index contains first key, we shouldn't
  2529. // read any data blocks until value is requested.
  2530. iter->Seek(ikey("aaba"));
  2531. ASSERT_TRUE(iter->Valid());
  2532. EXPECT_EQ(keys[2], iter->key().ToString());
  2533. EXPECT_EQ(use_first_key ? 0 : 1,
  2534. stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  2535. ASSERT_TRUE(iter->PrepareValue());
  2536. EXPECT_EQ("v2", iter->value().ToString());
  2537. EXPECT_EQ(1, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  2538. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2539. // Seek to the middle of a block. The block should be read right away.
  2540. iter->Seek(ikey("caab"));
  2541. ASSERT_TRUE(iter->Valid());
  2542. EXPECT_EQ(keys[4], iter->key().ToString());
  2543. EXPECT_EQ(2, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  2544. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2545. ASSERT_TRUE(iter->PrepareValue());
  2546. EXPECT_EQ("v4", iter->value().ToString());
  2547. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2548. // Seek to just before the same block and don't access value.
  2549. // The iterator should keep pinning the block contents.
  2550. iter->Seek(ikey("baaa"));
  2551. ASSERT_TRUE(iter->Valid());
  2552. EXPECT_EQ(keys[3], iter->key().ToString());
  2553. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2554. // Seek to the same block again to check that the block is still pinned.
  2555. iter->Seek(ikey("caae"));
  2556. ASSERT_TRUE(iter->Valid());
  2557. EXPECT_EQ(keys[5], iter->key().ToString());
  2558. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2559. ASSERT_TRUE(iter->PrepareValue());
  2560. EXPECT_EQ("v5", iter->value().ToString());
  2561. EXPECT_EQ(2, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  2562. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2563. // Step forward and fall through to the next block. Don't access value.
  2564. iter->Next();
  2565. ASSERT_TRUE(iter->Valid());
  2566. EXPECT_EQ(keys[6], iter->key().ToString());
  2567. EXPECT_EQ(use_first_key ? 2 : 3,
  2568. stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  2569. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2570. // Step forward again. Block should be read.
  2571. iter->Next();
  2572. ASSERT_TRUE(iter->Valid());
  2573. EXPECT_EQ(keys[7], iter->key().ToString());
  2574. EXPECT_EQ(3, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  2575. ASSERT_TRUE(iter->PrepareValue());
  2576. EXPECT_EQ("v7", iter->value().ToString());
  2577. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2578. // Step forward and reach the end.
  2579. iter->Next();
  2580. EXPECT_FALSE(iter->Valid());
  2581. EXPECT_EQ(3, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  2582. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2583. // Seek to a single-key block and step forward without accessing value.
  2584. iter->Seek(ikey("aaca"));
  2585. ASSERT_TRUE(iter->Valid());
  2586. EXPECT_EQ(keys[2], iter->key().ToString());
  2587. EXPECT_EQ(use_first_key ? 0 : 1,
  2588. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2589. iter->Next();
  2590. ASSERT_TRUE(iter->Valid());
  2591. EXPECT_EQ(keys[3], iter->key().ToString());
  2592. EXPECT_EQ(use_first_key ? 1 : 2,
  2593. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2594. ASSERT_TRUE(iter->PrepareValue());
  2595. EXPECT_EQ("v3", iter->value().ToString());
  2596. EXPECT_EQ(2, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2597. EXPECT_EQ(3, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  2598. // Seek between blocks and step back without accessing value.
  2599. iter->Seek(ikey("aaca"));
  2600. ASSERT_TRUE(iter->Valid());
  2601. EXPECT_EQ(keys[2], iter->key().ToString());
  2602. EXPECT_EQ(use_first_key ? 2 : 3,
  2603. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2604. EXPECT_EQ(3, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  2605. iter->Prev();
  2606. ASSERT_TRUE(iter->Valid());
  2607. EXPECT_EQ(keys[1], iter->key().ToString());
  2608. EXPECT_EQ(use_first_key ? 2 : 3,
  2609. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2610. // All blocks are in cache now, there'll be no more misses ever.
  2611. EXPECT_EQ(4, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  2612. ASSERT_TRUE(iter->PrepareValue());
  2613. EXPECT_EQ("v1", iter->value().ToString());
  2614. // Next into the next block again.
  2615. iter->Next();
  2616. ASSERT_TRUE(iter->Valid());
  2617. EXPECT_EQ(keys[2], iter->key().ToString());
  2618. EXPECT_EQ(use_first_key ? 2 : 4,
  2619. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2620. // Seek to first and step back without accessing value.
  2621. iter->SeekToFirst();
  2622. ASSERT_TRUE(iter->Valid());
  2623. EXPECT_EQ(keys[0], iter->key().ToString());
  2624. EXPECT_EQ(use_first_key ? 2 : 5,
  2625. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2626. iter->Prev();
  2627. EXPECT_FALSE(iter->Valid());
  2628. EXPECT_EQ(use_first_key ? 2 : 5,
  2629. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2630. // Do some SeekForPrev() and SeekToLast() just to cover all methods.
  2631. iter->SeekForPrev(ikey("caad"));
  2632. ASSERT_TRUE(iter->Valid());
  2633. EXPECT_EQ(keys[4], iter->key().ToString());
  2634. EXPECT_EQ(use_first_key ? 3 : 6,
  2635. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2636. ASSERT_TRUE(iter->PrepareValue());
  2637. EXPECT_EQ("v4", iter->value().ToString());
  2638. EXPECT_EQ(use_first_key ? 3 : 6,
  2639. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2640. iter->SeekToLast();
  2641. ASSERT_TRUE(iter->Valid());
  2642. EXPECT_EQ(keys[7], iter->key().ToString());
  2643. EXPECT_EQ(use_first_key ? 4 : 7,
  2644. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2645. ASSERT_TRUE(iter->PrepareValue());
  2646. EXPECT_EQ("v7", iter->value().ToString());
  2647. EXPECT_EQ(use_first_key ? 4 : 7,
  2648. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2649. EXPECT_EQ(4, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  2650. c.ResetTableReader();
  2651. }
  2652. }
  2653. TEST_P(BlockBasedTableTest, BinaryIndexWithFirstKeyGlobalSeqno) {
  2654. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2655. table_options.index_type = BlockBasedTableOptions::kBinarySearchWithFirstKey;
  2656. table_options.block_cache = NewLRUCache(10000);
  2657. Options options;
  2658. options.statistics = CreateDBStatistics();
  2659. Statistics* stats = options.statistics.get();
  2660. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2661. std::unique_ptr<InternalKeyComparator> comparator(
  2662. new InternalKeyComparator(BytewiseComparator()));
  2663. const ImmutableOptions ioptions(options);
  2664. const MutableCFOptions moptions(options);
  2665. TableConstructor c(BytewiseComparator(), /* convert_to_internal_key */ false,
  2666. /* level */ -1, /* largest_seqno */ 42);
  2667. c.Add(InternalKey("b", 0, kTypeValue).Encode().ToString(), "x");
  2668. c.Add(InternalKey("c", 0, kTypeValue).Encode().ToString(), "y");
  2669. std::vector<std::string> keys;
  2670. stl_wrappers::KVMap kvmap;
  2671. c.Finish(options, ioptions, moptions, table_options, *comparator, &keys,
  2672. &kvmap);
  2673. ASSERT_EQ(2, keys.size());
  2674. auto reader = c.GetTableReader();
  2675. auto props = reader->GetTableProperties();
  2676. ASSERT_EQ(1u, props->num_data_blocks);
  2677. ReadOptions read_options;
  2678. std::unique_ptr<InternalIterator> iter(reader->NewIterator(
  2679. read_options, /*prefix_extractor=*/nullptr, /*arena=*/nullptr,
  2680. /*skip_filters=*/false, TableReaderCaller::kUncategorized,
  2681. /*compaction_readahead_size=*/0, /*allow_unprepared_value=*/true));
  2682. iter->Seek(InternalKey("a", 0, kTypeValue).Encode().ToString());
  2683. ASSERT_TRUE(iter->Valid());
  2684. EXPECT_EQ(InternalKey("b", 42, kTypeValue).Encode().ToString(),
  2685. iter->key().ToString());
  2686. EXPECT_NE(keys[0], iter->key().ToString());
  2687. // Key should have been served from index, without reading data blocks.
  2688. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  2689. ASSERT_TRUE(iter->PrepareValue());
  2690. EXPECT_EQ("x", iter->value().ToString());
  2691. EXPECT_EQ(1, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  2692. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2693. EXPECT_EQ(InternalKey("b", 42, kTypeValue).Encode().ToString(),
  2694. iter->key().ToString());
  2695. c.ResetTableReader();
  2696. }
  2697. // It's very hard to figure out the index block size of a block accurately.
  2698. // To make sure we get the index size, we just make sure as key number
  2699. // grows, the filter block size also grows.
  2700. TEST_P(BlockBasedTableTest, IndexSizeStat) {
  2701. uint64_t last_index_size = 0;
  2702. // we need to use random keys since the pure human readable texts
  2703. // may be well compressed, resulting insignifcant change of index
  2704. // block size.
  2705. Random rnd(test::RandomSeed());
  2706. std::vector<std::string> keys;
  2707. for (int i = 0; i < 100; ++i) {
  2708. keys.push_back(rnd.RandomString(10000));
  2709. }
  2710. // Each time we load one more key to the table. the table index block
  2711. // size is expected to be larger than last time's.
  2712. for (size_t i = 1; i < keys.size(); ++i) {
  2713. TableConstructor c(BytewiseComparator(),
  2714. true /* convert_to_internal_key_ */);
  2715. for (size_t j = 0; j < i; ++j) {
  2716. c.Add(keys[j], "val");
  2717. }
  2718. std::vector<std::string> ks;
  2719. stl_wrappers::KVMap kvmap;
  2720. Options options;
  2721. options.compression = kNoCompression;
  2722. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2723. table_options.block_restart_interval = 1;
  2724. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2725. const ImmutableOptions ioptions(options);
  2726. const MutableCFOptions moptions(options);
  2727. c.Finish(options, ioptions, moptions, table_options,
  2728. GetPlainInternalComparator(options.comparator), &ks, &kvmap);
  2729. auto index_size = c.GetTableReader()->GetTableProperties()->index_size;
  2730. ASSERT_GT(index_size, last_index_size);
  2731. last_index_size = index_size;
  2732. c.ResetTableReader();
  2733. }
  2734. }
  2735. TEST_P(BlockBasedTableTest, NumBlockStat) {
  2736. Random rnd(test::RandomSeed());
  2737. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  2738. Options options;
  2739. options.compression = kNoCompression;
  2740. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2741. table_options.block_restart_interval = 1;
  2742. table_options.block_size = 1000;
  2743. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2744. for (int i = 0; i < 10; ++i) {
  2745. // the key/val are slightly smaller than block size, so that each block
  2746. // holds roughly one key/value pair.
  2747. c.Add(rnd.RandomString(900), "val");
  2748. }
  2749. std::vector<std::string> ks;
  2750. stl_wrappers::KVMap kvmap;
  2751. const ImmutableOptions ioptions(options);
  2752. const MutableCFOptions moptions(options);
  2753. c.Finish(options, ioptions, moptions, table_options,
  2754. GetPlainInternalComparator(options.comparator), &ks, &kvmap);
  2755. ASSERT_EQ(kvmap.size(),
  2756. c.GetTableReader()->GetTableProperties()->num_data_blocks);
  2757. c.ResetTableReader();
  2758. }
  2759. TEST_P(BlockBasedTableTest, TracingGetTest) {
  2760. TableConstructor c(BytewiseComparator());
  2761. Options options;
  2762. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2763. options.create_if_missing = true;
  2764. table_options.block_cache = NewLRUCache(1024 * 1024, 0);
  2765. table_options.cache_index_and_filter_blocks = true;
  2766. table_options.filter_policy.reset(NewBloomFilterPolicy(10));
  2767. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  2768. SetupTracingTest(&c);
  2769. std::vector<std::string> keys;
  2770. stl_wrappers::KVMap kvmap;
  2771. ImmutableOptions ioptions(options);
  2772. MutableCFOptions moptions(options);
  2773. c.Finish(options, ioptions, moptions, table_options,
  2774. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  2775. InternalKey internal_key(auto_add_key1, 0, kTypeValue);
  2776. std::string encoded_key = internal_key.Encode().ToString();
  2777. for (uint32_t i = 1; i <= 2; i++) {
  2778. PinnableSlice value;
  2779. GetContext get_context(
  2780. options.comparator, nullptr, nullptr, nullptr, GetContext::kNotFound,
  2781. auto_add_key1, &value, nullptr, nullptr, nullptr, true, nullptr,
  2782. nullptr, nullptr, nullptr, nullptr, nullptr, /*tracing_get_id=*/i);
  2783. get_perf_context()->Reset();
  2784. ASSERT_OK(c.GetTableReader()->Get(ReadOptions(), encoded_key, &get_context,
  2785. moptions.prefix_extractor.get()));
  2786. ASSERT_EQ(get_context.State(), GetContext::kFound);
  2787. ASSERT_EQ(value.ToString(), kDummyValue);
  2788. }
  2789. // Verify traces.
  2790. std::vector<BlockCacheTraceRecord> expected_records;
  2791. // The first two records should be prefetching index and filter blocks.
  2792. BlockCacheTraceRecord record;
  2793. record.block_type = TraceType::kBlockTraceIndexBlock;
  2794. record.caller = TableReaderCaller::kPrefetch;
  2795. record.is_cache_hit = false;
  2796. record.no_insert = false;
  2797. expected_records.push_back(record);
  2798. record.block_type = TraceType::kBlockTraceFilterBlock;
  2799. expected_records.push_back(record);
  2800. // Then we should have three records for one index, one filter, and one data
  2801. // block access.
  2802. record.get_id = 1;
  2803. record.block_type = TraceType::kBlockTraceFilterBlock;
  2804. record.caller = TableReaderCaller::kUserGet;
  2805. record.get_from_user_specified_snapshot = false;
  2806. record.referenced_key = encoded_key;
  2807. record.referenced_key_exist_in_block = true;
  2808. record.is_cache_hit = true;
  2809. expected_records.push_back(record);
  2810. record.block_type = TraceType::kBlockTraceIndexBlock;
  2811. expected_records.push_back(record);
  2812. record.is_cache_hit = false;
  2813. record.block_type = TraceType::kBlockTraceDataBlock;
  2814. expected_records.push_back(record);
  2815. // The second get should all observe cache hits.
  2816. record.is_cache_hit = true;
  2817. record.get_id = 2;
  2818. record.block_type = TraceType::kBlockTraceFilterBlock;
  2819. record.caller = TableReaderCaller::kUserGet;
  2820. record.get_from_user_specified_snapshot = false;
  2821. record.referenced_key = encoded_key;
  2822. expected_records.push_back(record);
  2823. record.block_type = TraceType::kBlockTraceIndexBlock;
  2824. expected_records.push_back(record);
  2825. record.block_type = TraceType::kBlockTraceDataBlock;
  2826. expected_records.push_back(record);
  2827. VerifyBlockAccessTrace(&c, expected_records);
  2828. c.ResetTableReader();
  2829. }
  2830. void GenerateKVMap(TableConstructor* c) {
  2831. int num_block = 100;
  2832. Random rnd(101);
  2833. uint32_t key = 0;
  2834. for (int block = 0; block < num_block; block++) {
  2835. for (int i = 0; i < 16; i++) {
  2836. char k[9] = {0};
  2837. // Internal key is constructed directly from this key,
  2838. // and internal key size is required to be >= 8 bytes,
  2839. // so use %08u as the format string.
  2840. snprintf(k, sizeof(k), "%08u", key);
  2841. std::string v = rnd.RandomString(256);
  2842. InternalKey ikey(std::string(k), 0, kTypeValue);
  2843. c->Add(ikey.Encode().ToString(), rnd.RandomString(256));
  2844. key++;
  2845. }
  2846. }
  2847. }
  2848. void WarmUpCache(TableConstructor* c, const MutableCFOptions& moptions,
  2849. const std::vector<std::string>& warm_keys) {
  2850. ReadOptions ro;
  2851. std::unique_ptr<InternalIterator> iter(c->GetTableReader()->NewIterator(
  2852. ro, moptions.prefix_extractor.get(), nullptr, false,
  2853. TableReaderCaller::kUncategorized));
  2854. size_t i = 0;
  2855. while (i < warm_keys.size()) {
  2856. InternalKey ikey(warm_keys[i], 0, kTypeValue);
  2857. iter->Seek(ikey.Encode().ToString());
  2858. ASSERT_OK(iter->status());
  2859. ASSERT_TRUE(iter->Valid());
  2860. i++;
  2861. }
  2862. }
  2863. TEST_P(BlockBasedTableTest, BlockCacheLookupSeqScans) {
  2864. Options options;
  2865. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2866. options.create_if_missing = true;
  2867. options.compression = kNoCompression;
  2868. options.statistics = CreateDBStatistics();
  2869. table_options.index_type =
  2870. BlockBasedTableOptions::IndexType::kTwoLevelIndexSearch;
  2871. table_options.block_cache = NewLRUCache(1024 * 1024, 0);
  2872. table_options.cache_index_and_filter_blocks = true;
  2873. table_options.filter_policy.reset(NewBloomFilterPolicy(10, true));
  2874. table_options.block_align = true;
  2875. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  2876. ASSERT_OK(options.table_factory->ValidateOptions(
  2877. DBOptions(options), ColumnFamilyOptions(options)));
  2878. TableConstructor c(BytewiseComparator());
  2879. GenerateKVMap(&c);
  2880. std::vector<std::string> keys;
  2881. stl_wrappers::KVMap kvmap;
  2882. ImmutableOptions ioptions(options);
  2883. MutableCFOptions moptions(options);
  2884. const InternalKeyComparator internal_comparator(options.comparator);
  2885. c.Finish(options, ioptions, moptions, table_options, internal_comparator,
  2886. &keys, &kvmap);
  2887. BlockBasedTable* bbt = static_cast<BlockBasedTable*>(c.GetTableReader());
  2888. BlockHandle block_handle;
  2889. ReadOptions read_options;
  2890. read_options.auto_readahead_size = true;
  2891. Slice ub = Slice("00000805");
  2892. Slice* ub_ptr = &ub;
  2893. read_options.iterate_upper_bound = ub_ptr;
  2894. read_options.readahead_size = 16384;
  2895. // Test various functionalities -
  2896. // 5 blocks prefetched - Current + 4 additional (readahead_size).
  2897. {
  2898. // Check the behavior when it's -
  2899. // Miss(200), Hit(210), Hit(225), Hit(240), Hit(255).
  2900. // It should only prefetch current block (200).
  2901. {
  2902. std::vector<std::string> warm_keys{"00000210", "00000225", "00000240",
  2903. "00000255"};
  2904. WarmUpCache(&c, moptions, warm_keys);
  2905. ASSERT_OK(options.statistics->Reset());
  2906. std::unique_ptr<InternalIterator> iter(c.GetTableReader()->NewIterator(
  2907. read_options, moptions.prefix_extractor.get(), /*arena=*/nullptr,
  2908. /*skip_filters=*/false, TableReaderCaller::kUncategorized));
  2909. // Seek key -
  2910. InternalKey ikey("00000200", 0, kTypeValue);
  2911. auto kv_iter = kvmap.find(ikey.Encode().ToString());
  2912. iter->Seek(kv_iter->first);
  2913. ASSERT_OK(iter->status());
  2914. ASSERT_TRUE(iter->Valid());
  2915. ASSERT_EQ(iter->key(), kv_iter->first);
  2916. ASSERT_EQ(iter->value().ToString(), kv_iter->second);
  2917. FilePrefetchBuffer* prefetch_buffer =
  2918. (static_cast<BlockBasedTableIterator*>(iter.get()))
  2919. ->prefetch_buffer();
  2920. std::vector<std::tuple<uint64_t, size_t, bool>> buffer_info(1);
  2921. prefetch_buffer->TEST_GetBufferOffsetandSize(buffer_info);
  2922. bbt->TEST_GetDataBlockHandle(read_options, kv_iter->first, block_handle);
  2923. // It won't prefetch the data of cache hit.
  2924. // One block data.
  2925. ASSERT_EQ(std::get<1>(buffer_info[0]), 4096);
  2926. ASSERT_EQ(std::get<0>(buffer_info[0]), block_handle.offset());
  2927. ASSERT_EQ(options.statistics->getAndResetTickerCount(READAHEAD_TRIMMED),
  2928. 1);
  2929. }
  2930. {
  2931. // Check the behavior when it's -
  2932. // First Prefetch - Miss(315), Miss(330), Miss(345), Hit(360), Hit(375),
  2933. // Second Prefetch - Miss(390), Miss(405) ...
  2934. // First prefetch should only prefetch from 315 to 345.
  2935. std::vector<std::string> warm_keys{"00000360", "00000375"};
  2936. WarmUpCache(&c, moptions, warm_keys);
  2937. std::unique_ptr<InternalIterator> iter(c.GetTableReader()->NewIterator(
  2938. read_options, moptions.prefix_extractor.get(), nullptr, false,
  2939. TableReaderCaller::kUncategorized));
  2940. // Seek key -
  2941. InternalKey ikey("00000315", 0, kTypeValue);
  2942. auto kv_iter = kvmap.find(ikey.Encode().ToString());
  2943. iter->Seek(kv_iter->first);
  2944. ASSERT_OK(iter->status());
  2945. ASSERT_TRUE(iter->Valid());
  2946. ASSERT_EQ(iter->key(), kv_iter->first);
  2947. ASSERT_EQ(iter->value().ToString(), kv_iter->second);
  2948. FilePrefetchBuffer* prefetch_buffer =
  2949. (static_cast<BlockBasedTableIterator*>(iter.get()))
  2950. ->prefetch_buffer();
  2951. std::vector<std::tuple<uint64_t, size_t, bool>> buffer_info(1);
  2952. prefetch_buffer->TEST_GetBufferOffsetandSize(buffer_info);
  2953. bbt->TEST_GetDataBlockHandle(read_options, kv_iter->first, block_handle);
  2954. // It won't prefetch the data of cache hit.
  2955. // 3 blocks data.
  2956. ASSERT_EQ(std::get<1>(buffer_info[0]), 12288);
  2957. ASSERT_EQ(std::get<0>(buffer_info[0]), block_handle.offset());
  2958. for (; kv_iter != kvmap.end() && iter->Valid(); kv_iter++) {
  2959. ASSERT_EQ(iter->key(), kv_iter->first);
  2960. ASSERT_EQ(iter->value().ToString(), kv_iter->second);
  2961. iter->Next();
  2962. ASSERT_OK(iter->status());
  2963. if (iter->user_key().ToString() == "00000400") {
  2964. break;
  2965. }
  2966. }
  2967. // Second Prefetch.
  2968. prefetch_buffer->TEST_GetBufferOffsetandSize(buffer_info);
  2969. bbt->TEST_GetDataBlockHandle(read_options, kv_iter->first, block_handle);
  2970. ASSERT_EQ(std::get<1>(buffer_info[0]), 20480);
  2971. ASSERT_EQ(std::get<0>(buffer_info[0]), block_handle.offset());
  2972. ASSERT_EQ(options.statistics->getAndResetTickerCount(READAHEAD_TRIMMED),
  2973. 1);
  2974. }
  2975. }
  2976. c.ResetTableReader();
  2977. }
  2978. TEST_P(BlockBasedTableTest, BlockCacheLookupAsyncScansSeek) {
  2979. Options options;
  2980. TableConstructor c(BytewiseComparator());
  2981. std::unique_ptr<Env> env(
  2982. new CompositeEnvWrapper(c.env_, FileSystem::Default()));
  2983. options.env = env.get();
  2984. options.compression = kNoCompression;
  2985. options.statistics = CreateDBStatistics();
  2986. c.env_ = env.get();
  2987. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2988. options.create_if_missing = true;
  2989. table_options.index_type =
  2990. BlockBasedTableOptions::IndexType::kTwoLevelIndexSearch;
  2991. table_options.block_cache = NewLRUCache(1024 * 1024, 0);
  2992. table_options.cache_index_and_filter_blocks = true;
  2993. table_options.filter_policy.reset(NewBloomFilterPolicy(10, true));
  2994. table_options.block_align = true;
  2995. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  2996. ASSERT_OK(options.table_factory->ValidateOptions(
  2997. DBOptions(options), ColumnFamilyOptions(options)));
  2998. GenerateKVMap(&c);
  2999. std::vector<std::string> keys;
  3000. stl_wrappers::KVMap kvmap;
  3001. ImmutableOptions ioptions(options);
  3002. MutableCFOptions moptions(options);
  3003. const InternalKeyComparator internal_comparator(options.comparator);
  3004. c.Finish(options, ioptions, moptions, table_options, internal_comparator,
  3005. &keys, &kvmap);
  3006. BlockBasedTable* bbt = static_cast<BlockBasedTable*>(c.GetTableReader());
  3007. BlockHandle block_handle;
  3008. ReadOptions read_options;
  3009. read_options.auto_readahead_size = true;
  3010. Slice ub = Slice("00000805");
  3011. Slice* ub_ptr = &ub;
  3012. read_options.iterate_upper_bound = ub_ptr;
  3013. read_options.readahead_size = 16384;
  3014. read_options.async_io = true;
  3015. // Test Various functionalities -
  3016. // 3 blocks prefetched - Current + 2 additional (readahead_size/2).
  3017. {
  3018. // Check the behavior when it's -
  3019. // 1st Prefetch - Miss(200), Hit(210), Hit(225),
  3020. // 2nd Prefetch - Hit(240), Hit(255)
  3021. // First Prefetch will be for 200 offset.
  3022. // Second prefetch will be 0.
  3023. {
  3024. std::vector<std::string> warm_keys{"00000210", "00000225", "00000240",
  3025. "00000255"};
  3026. WarmUpCache(&c, moptions, warm_keys);
  3027. ASSERT_OK(options.statistics->Reset());
  3028. std::unique_ptr<InternalIterator> iter(c.GetTableReader()->NewIterator(
  3029. read_options, moptions.prefix_extractor.get(), nullptr, false,
  3030. TableReaderCaller::kUncategorized));
  3031. // Seek key -
  3032. InternalKey ikey("00000200", 0, kTypeValue);
  3033. auto kv_iter = kvmap.find(ikey.Encode().ToString());
  3034. iter->Seek(kv_iter->first);
  3035. ASSERT_TRUE(iter->status().IsTryAgain());
  3036. iter->Seek(kv_iter->first);
  3037. ASSERT_OK(iter->status());
  3038. ASSERT_TRUE(iter->Valid());
  3039. ASSERT_EQ(iter->key(), kv_iter->first);
  3040. ASSERT_EQ(iter->value().ToString(), kv_iter->second);
  3041. FilePrefetchBuffer* prefetch_buffer =
  3042. (static_cast<BlockBasedTableIterator*>(iter.get()))
  3043. ->prefetch_buffer();
  3044. std::vector<std::tuple<uint64_t, size_t, bool>> buffer_info(2);
  3045. prefetch_buffer->TEST_GetBufferOffsetandSize(buffer_info);
  3046. bbt->TEST_GetDataBlockHandle(read_options, kv_iter->first, block_handle);
  3047. ASSERT_EQ(std::get<0>(buffer_info[0]), block_handle.offset());
  3048. ASSERT_EQ(std::get<1>(buffer_info[0]), 4096);
  3049. ASSERT_EQ(std::get<1>(buffer_info[1]), 0);
  3050. ASSERT_EQ(options.statistics->getAndResetTickerCount(READAHEAD_TRIMMED),
  3051. 2);
  3052. }
  3053. {
  3054. // Check the behavior when it's -
  3055. // First Prefetch - Miss(315), Miss(330), Hit(345),
  3056. // Second Prefetch - Miss(360), Miss(375), ...
  3057. // First prefetch should only prefetch from 315 to 330.
  3058. // Second prefetch should start from 360.
  3059. std::vector<std::string> warm_keys{"00000345"};
  3060. WarmUpCache(&c, moptions, warm_keys);
  3061. std::unique_ptr<InternalIterator> iter(c.GetTableReader()->NewIterator(
  3062. read_options, moptions.prefix_extractor.get(), nullptr, false,
  3063. TableReaderCaller::kUncategorized));
  3064. // Seek key -
  3065. InternalKey ikey("00000315", 0, kTypeValue);
  3066. auto kv_iter = kvmap.find(ikey.Encode().ToString());
  3067. iter->Seek(kv_iter->first);
  3068. ASSERT_TRUE(iter->status().IsTryAgain());
  3069. iter->Seek(kv_iter->first);
  3070. ASSERT_OK(iter->status());
  3071. ASSERT_TRUE(iter->Valid());
  3072. ASSERT_EQ(iter->key(), kv_iter->first);
  3073. ASSERT_EQ(iter->value().ToString(), kv_iter->second);
  3074. FilePrefetchBuffer* prefetch_buffer =
  3075. (static_cast<BlockBasedTableIterator*>(iter.get()))
  3076. ->prefetch_buffer();
  3077. std::vector<std::tuple<uint64_t, size_t, bool>> buffer_info(2);
  3078. prefetch_buffer->TEST_GetBufferOffsetandSize(buffer_info);
  3079. {
  3080. // 1st Buffer Verification.
  3081. bbt->TEST_GetDataBlockHandle(read_options, kv_iter->first,
  3082. block_handle);
  3083. ASSERT_EQ(std::get<0>(buffer_info[0]), block_handle.offset());
  3084. ASSERT_EQ(std::get<1>(buffer_info[0]), 8192);
  3085. // 2nd Buffer Verification.
  3086. InternalKey ikey_tmp("00000360", 0, kTypeValue);
  3087. bbt->TEST_GetDataBlockHandle(read_options, ikey_tmp.Encode().ToString(),
  3088. block_handle);
  3089. ASSERT_EQ(std::get<0>(buffer_info[1]), block_handle.offset());
  3090. ASSERT_EQ(std::get<1>(buffer_info[1]), 8192);
  3091. ASSERT_EQ(options.statistics->getAndResetTickerCount(READAHEAD_TRIMMED),
  3092. 1);
  3093. }
  3094. }
  3095. {
  3096. // Check the behavior when it's -
  3097. // First Prefetch - Miss(495), Miss(510), Hit(525), prefetch len- 8192
  3098. // Second Prefetch async - Miss(540), Miss(555), - 8192
  3099. // Third Prefetch Async - Hit(570), Miss(585), - 4096
  3100. // 4th Prefetch Async - Hit(600), Miss(615), - 4096
  3101. // 5th Prefetch Async - Miss(630), Miss(645) - 8192
  3102. std::vector<std::string> warm_keys{"00000525", "00000570", "00000600"};
  3103. WarmUpCache(&c, moptions, warm_keys);
  3104. std::unique_ptr<InternalIterator> iter(c.GetTableReader()->NewIterator(
  3105. read_options, moptions.prefix_extractor.get(), /*arena=*/nullptr,
  3106. /*skip_filters=*/false, TableReaderCaller::kUncategorized));
  3107. // Seek key -
  3108. InternalKey ikey("00000495", 0, kTypeValue);
  3109. auto kv_iter = kvmap.find(ikey.Encode().ToString());
  3110. // First and Second Prefetch.
  3111. iter->Seek(kv_iter->first);
  3112. ASSERT_TRUE(iter->status().IsTryAgain());
  3113. iter->Seek(kv_iter->first);
  3114. ASSERT_OK(iter->status());
  3115. ASSERT_TRUE(iter->Valid());
  3116. ASSERT_EQ(iter->key(), kv_iter->first);
  3117. ASSERT_EQ(iter->value().ToString(), kv_iter->second);
  3118. FilePrefetchBuffer* prefetch_buffer =
  3119. (static_cast<BlockBasedTableIterator*>(iter.get()))
  3120. ->prefetch_buffer();
  3121. {
  3122. std::vector<std::tuple<uint64_t, size_t, bool>> buffer_info(2);
  3123. prefetch_buffer->TEST_GetBufferOffsetandSize(buffer_info);
  3124. // 1st Buffer Verification.
  3125. bbt->TEST_GetDataBlockHandle(read_options, kv_iter->first,
  3126. block_handle);
  3127. ASSERT_EQ(std::get<0>(buffer_info[0]), block_handle.offset());
  3128. ASSERT_EQ(std::get<1>(buffer_info[0]), 8192);
  3129. // 2nd Buffer Verification.
  3130. InternalKey ikey_tmp("00000540", 0, kTypeValue);
  3131. bbt->TEST_GetDataBlockHandle(read_options, ikey_tmp.Encode().ToString(),
  3132. block_handle);
  3133. ASSERT_EQ(std::get<0>(buffer_info[1]), block_handle.offset());
  3134. ASSERT_EQ(std::get<1>(buffer_info[1]), 8192);
  3135. ASSERT_EQ(options.statistics->getAndResetTickerCount(READAHEAD_TRIMMED),
  3136. 1);
  3137. }
  3138. // Third prefetch ReadAsync (buffers will swap).
  3139. for (; kv_iter != kvmap.end() && iter->Valid(); kv_iter++) {
  3140. ASSERT_EQ(iter->key(), kv_iter->first);
  3141. ASSERT_EQ(iter->value().ToString(), kv_iter->second);
  3142. if (iter->user_key() == "00000540") {
  3143. break;
  3144. }
  3145. iter->Next();
  3146. ASSERT_OK(iter->status());
  3147. }
  3148. {
  3149. std::vector<std::tuple<uint64_t, size_t, bool>> buffer_info(2);
  3150. prefetch_buffer->TEST_GetBufferOffsetandSize(buffer_info);
  3151. // 1st Buffer Verification.
  3152. bbt->TEST_GetDataBlockHandle(read_options, kv_iter->first,
  3153. block_handle);
  3154. ASSERT_EQ(std::get<0>(buffer_info[0]), block_handle.offset());
  3155. ASSERT_EQ(std::get<1>(buffer_info[0]), 8192);
  3156. // 2nd Buffer Verification.
  3157. InternalKey ikey_tmp("00000585", 0, kTypeValue);
  3158. bbt->TEST_GetDataBlockHandle(read_options, ikey_tmp.Encode().ToString(),
  3159. block_handle);
  3160. ASSERT_EQ(std::get<0>(buffer_info[1]), block_handle.offset());
  3161. ASSERT_EQ(std::get<1>(buffer_info[1]), 4096);
  3162. ASSERT_EQ(options.statistics->getAndResetTickerCount(READAHEAD_TRIMMED),
  3163. 1);
  3164. }
  3165. // 4th Prefetch ReadAsync (buffers will swap).
  3166. for (; kv_iter != kvmap.end() && iter->Valid(); kv_iter++) {
  3167. ASSERT_EQ(iter->key(), kv_iter->first);
  3168. ASSERT_EQ(iter->value().ToString(), kv_iter->second);
  3169. if (iter->user_key() == "00000585") {
  3170. break;
  3171. }
  3172. iter->Next();
  3173. ASSERT_OK(iter->status());
  3174. }
  3175. {
  3176. std::vector<std::tuple<uint64_t, size_t, bool>> buffer_info(2);
  3177. prefetch_buffer->TEST_GetBufferOffsetandSize(buffer_info);
  3178. // 1st Buffer Verification.
  3179. bbt->TEST_GetDataBlockHandle(read_options, kv_iter->first,
  3180. block_handle);
  3181. ASSERT_EQ(std::get<0>(buffer_info[0]), block_handle.offset());
  3182. ASSERT_EQ(std::get<1>(buffer_info[0]), 4096);
  3183. // 2nd Buffer Verification.
  3184. InternalKey ikey_tmp("00000615", 0, kTypeValue);
  3185. bbt->TEST_GetDataBlockHandle(read_options, ikey_tmp.Encode().ToString(),
  3186. block_handle);
  3187. ASSERT_EQ(std::get<0>(buffer_info[1]), block_handle.offset());
  3188. ASSERT_EQ(std::get<1>(buffer_info[1]), 4096);
  3189. ASSERT_EQ(options.statistics->getAndResetTickerCount(READAHEAD_TRIMMED),
  3190. 1);
  3191. }
  3192. // 5th Prefetch ReadAsync.
  3193. for (; kv_iter != kvmap.end() && iter->Valid(); kv_iter++) {
  3194. ASSERT_EQ(iter->key(), kv_iter->first);
  3195. ASSERT_EQ(iter->value().ToString(), kv_iter->second);
  3196. if (iter->user_key() == "00000615") {
  3197. break;
  3198. }
  3199. iter->Next();
  3200. ASSERT_OK(iter->status());
  3201. }
  3202. {
  3203. std::vector<std::tuple<uint64_t, size_t, bool>> buffer_info(2);
  3204. prefetch_buffer->TEST_GetBufferOffsetandSize(buffer_info);
  3205. // 1st Buffer Verification.
  3206. bbt->TEST_GetDataBlockHandle(read_options, kv_iter->first,
  3207. block_handle);
  3208. ASSERT_EQ(std::get<0>(buffer_info[0]), block_handle.offset());
  3209. ASSERT_EQ(std::get<1>(buffer_info[0]), 4096);
  3210. // 2nd Buffer Verification.
  3211. InternalKey ikey_tmp("00000630", 0, kTypeValue);
  3212. bbt->TEST_GetDataBlockHandle(read_options, ikey_tmp.Encode().ToString(),
  3213. block_handle);
  3214. ASSERT_EQ(std::get<0>(buffer_info[1]), block_handle.offset());
  3215. ASSERT_EQ(std::get<1>(buffer_info[1]), 8192);
  3216. ASSERT_EQ(options.statistics->getAndResetTickerCount(READAHEAD_TRIMMED),
  3217. 0);
  3218. }
  3219. }
  3220. }
  3221. c.ResetTableReader();
  3222. }
  3223. struct HitMissCountingCache : public CacheWrapper {
  3224. using CacheWrapper::CacheWrapper;
  3225. const char* Name() const override { return "HitMissCountingCache"; }
  3226. uint64_t hit_count_ = 0;
  3227. uint64_t miss_count_ = 0;
  3228. void Reset() {
  3229. hit_count_ = 0;
  3230. miss_count_ = 0;
  3231. }
  3232. Handle* Lookup(const Slice& key, const CacheItemHelper* helper,
  3233. CreateContext* create_context,
  3234. Priority priority = Priority::LOW,
  3235. Statistics* stats = nullptr) override {
  3236. // ASSUMES no blocking async lookups
  3237. Handle* h = target_->Lookup(key, helper, create_context, priority, stats);
  3238. if (h) {
  3239. hit_count_++;
  3240. } else {
  3241. miss_count_++;
  3242. }
  3243. return h;
  3244. }
  3245. void StartAsyncLookup(AsyncLookupHandle& async_handle) override {
  3246. target_->StartAsyncLookup(async_handle);
  3247. // If not pending, caller might not call WaitAll, so have to account here.
  3248. if (!async_handle.IsPending()) {
  3249. if (async_handle.Result()) {
  3250. hit_count_++;
  3251. } else {
  3252. miss_count_++;
  3253. }
  3254. }
  3255. }
  3256. void WaitAll(AsyncLookupHandle* async_handles, size_t count) override {
  3257. // If !pending, then we already accounted for it in StartAsyncLookup.
  3258. // Assume the pending status does not change asynchronously (since
  3259. // StartAsyncLookup) and remember which still need accounting.
  3260. std::vector<AsyncLookupHandle*> needs_accounting;
  3261. for (size_t i = 0; i < count; ++i) {
  3262. if (async_handles[i].IsPending()) {
  3263. needs_accounting.push_back(async_handles + i);
  3264. }
  3265. }
  3266. target_->WaitAll(async_handles, count);
  3267. for (auto ah : needs_accounting) {
  3268. if (ah->Result()) {
  3269. hit_count_++;
  3270. } else {
  3271. miss_count_++;
  3272. }
  3273. }
  3274. }
  3275. void VerifyExpectedHitMissCounts(
  3276. const std::vector<BlockCacheTraceRecord>& expected_records) {
  3277. uint64_t expected_hits = 0;
  3278. uint64_t expected_misses = 0;
  3279. for (const auto& r : expected_records) {
  3280. if (r.is_cache_hit) {
  3281. expected_hits++;
  3282. } else {
  3283. expected_misses++;
  3284. }
  3285. }
  3286. EXPECT_EQ(expected_hits, hit_count_);
  3287. EXPECT_EQ(expected_misses, miss_count_);
  3288. Reset();
  3289. }
  3290. };
  3291. TEST_P(BlockBasedTableTest, TracingMultiGetTest) {
  3292. TableConstructor c(BytewiseComparator());
  3293. Options options;
  3294. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  3295. options.create_if_missing = true;
  3296. auto cache =
  3297. std::make_shared<HitMissCountingCache>(NewLRUCache(1024 * 1024, 0));
  3298. table_options.block_cache = cache;
  3299. table_options.cache_index_and_filter_blocks = true;
  3300. table_options.filter_policy.reset(NewBloomFilterPolicy(10));
  3301. // Put auto_add_key1 and auto_add_key2 in the same data block
  3302. table_options.block_size = kDummyValue.size() * 2 + 100;
  3303. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  3304. SetupTracingTest(&c);
  3305. std::vector<std::string> keys;
  3306. stl_wrappers::KVMap kvmap;
  3307. ImmutableOptions ioptions(options);
  3308. MutableCFOptions moptions(options);
  3309. c.Finish(options, ioptions, moptions, table_options,
  3310. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  3311. std::vector<BlockCacheTraceRecord> expected_records;
  3312. for (bool first_pass : {true, false}) {
  3313. uint64_t get_id_offset = first_pass ? 2 : 5;
  3314. ReadOptions ro;
  3315. std::array<Slice, 2> ukeys{{auto_add_key1, auto_add_key2}};
  3316. std::array<PinnableSlice, 2> values;
  3317. std::vector<GetContext> get_contexts;
  3318. get_contexts.emplace_back(
  3319. options.comparator, nullptr, nullptr, nullptr, GetContext::kNotFound,
  3320. ukeys[0], values.data(), nullptr, nullptr, nullptr, true, nullptr,
  3321. nullptr, nullptr, nullptr, nullptr, nullptr, get_id_offset);
  3322. get_contexts.emplace_back(
  3323. options.comparator, nullptr, nullptr, nullptr, GetContext::kNotFound,
  3324. ukeys[1], &values[1], nullptr, nullptr, nullptr, true, nullptr, nullptr,
  3325. nullptr, nullptr, nullptr, nullptr, get_id_offset + 1);
  3326. std::array<std::string, 2> encoded_keys;
  3327. encoded_keys[0] = InternalKey(ukeys[0], 0, kTypeValue).Encode().ToString();
  3328. encoded_keys[1] = InternalKey(ukeys[1], 0, kTypeValue).Encode().ToString();
  3329. std::array<Status, 2> statuses;
  3330. autovector<KeyContext, MultiGetContext::MAX_BATCH_SIZE> key_context;
  3331. key_context.emplace_back(/*ColumnFamilyHandle omitted*/ nullptr, ukeys[0],
  3332. values.data(),
  3333. /*PinnableWideColumns omitted*/ nullptr,
  3334. /*timestamp omitted*/ nullptr, statuses.data());
  3335. key_context[0].ukey_without_ts = ukeys[0];
  3336. key_context[0].ikey = encoded_keys[0];
  3337. key_context[0].get_context = get_contexts.data();
  3338. key_context.emplace_back(/*ColumnFamilyHandle omitted*/ nullptr, ukeys[1],
  3339. &values[1],
  3340. /*PinnableWideColumns omitted*/ nullptr,
  3341. /*timestamp omitted*/ nullptr, &statuses[1]);
  3342. key_context[1].ukey_without_ts = ukeys[1];
  3343. key_context[1].ikey = encoded_keys[1];
  3344. key_context[1].get_context = &get_contexts[1];
  3345. autovector<KeyContext*, MultiGetContext::MAX_BATCH_SIZE> sorted_keys;
  3346. sorted_keys.push_back(&key_context[0]);
  3347. sorted_keys.push_back(&key_context[1]);
  3348. MultiGetContext m_context(
  3349. &sorted_keys, 0, sorted_keys.size(), /*SequenceNumber*/ 42, ro,
  3350. options.env->GetFileSystem().get(), options.statistics.get());
  3351. MultiGetRange range = m_context.GetMultiGetRange();
  3352. get_perf_context()->Reset();
  3353. c.GetTableReader()->MultiGet(ro, &range, /*prefix_extractor*/ nullptr);
  3354. // Verify read op result
  3355. for (uint32_t i = 0; i <= 1; i++) {
  3356. ASSERT_OK(statuses[i]);
  3357. ASSERT_EQ(get_contexts[i].State(), GetContext::kFound);
  3358. ASSERT_EQ(values[i].ToString(), kDummyValue);
  3359. }
  3360. // Verify traces.
  3361. BlockCacheTraceRecord record;
  3362. if (first_pass) {
  3363. // The first two records should be prefetching index and filter blocks.
  3364. record.get_id = 0;
  3365. record.block_type = TraceType::kBlockTraceIndexBlock;
  3366. record.caller = TableReaderCaller::kPrefetch;
  3367. record.is_cache_hit = false;
  3368. record.no_insert = false;
  3369. expected_records.push_back(record);
  3370. record.block_type = TraceType::kBlockTraceFilterBlock;
  3371. expected_records.push_back(record);
  3372. }
  3373. // Then we should have three records for one index, one filter, and one
  3374. // data block access. (The two keys share a data block.)
  3375. record.get_id = get_id_offset;
  3376. record.block_type = TraceType::kBlockTraceFilterBlock;
  3377. record.caller = TableReaderCaller::kUserMultiGet;
  3378. record.get_from_user_specified_snapshot = false;
  3379. record.referenced_key = encoded_keys[0];
  3380. record.referenced_key_exist_in_block = true;
  3381. record.is_cache_hit = true;
  3382. expected_records.push_back(record);
  3383. record.block_type = TraceType::kBlockTraceIndexBlock;
  3384. expected_records.push_back(record);
  3385. record.is_cache_hit = !first_pass;
  3386. record.block_type = TraceType::kBlockTraceDataBlock;
  3387. expected_records.push_back(record);
  3388. }
  3389. VerifyBlockAccessTrace(&c, expected_records);
  3390. cache->VerifyExpectedHitMissCounts(expected_records);
  3391. c.ResetTableReader();
  3392. }
  3393. TEST_P(BlockBasedTableTest, TracingApproximateOffsetOfTest) {
  3394. TableConstructor c(BytewiseComparator());
  3395. Options options;
  3396. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  3397. options.create_if_missing = true;
  3398. table_options.block_cache = NewLRUCache(1024 * 1024, 0);
  3399. table_options.cache_index_and_filter_blocks = true;
  3400. table_options.filter_policy.reset(NewBloomFilterPolicy(10, true));
  3401. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  3402. SetupTracingTest(&c);
  3403. std::vector<std::string> keys;
  3404. stl_wrappers::KVMap kvmap;
  3405. ImmutableOptions ioptions(options);
  3406. MutableCFOptions moptions(options);
  3407. c.Finish(options, ioptions, moptions, table_options,
  3408. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  3409. const ReadOptions read_options;
  3410. for (uint32_t i = 1; i <= 2; i++) {
  3411. InternalKey internal_key(auto_add_key1, 0, kTypeValue);
  3412. std::string encoded_key = internal_key.Encode().ToString();
  3413. c.GetTableReader()->ApproximateOffsetOf(
  3414. read_options, encoded_key, TableReaderCaller::kUserApproximateSize);
  3415. }
  3416. // Verify traces.
  3417. std::vector<BlockCacheTraceRecord> expected_records;
  3418. // The first two records should be prefetching index and filter blocks.
  3419. BlockCacheTraceRecord record;
  3420. record.block_type = TraceType::kBlockTraceIndexBlock;
  3421. record.caller = TableReaderCaller::kPrefetch;
  3422. record.is_cache_hit = false;
  3423. record.no_insert = false;
  3424. expected_records.push_back(record);
  3425. record.block_type = TraceType::kBlockTraceFilterBlock;
  3426. expected_records.push_back(record);
  3427. // Then we should have two records for only index blocks.
  3428. record.block_type = TraceType::kBlockTraceIndexBlock;
  3429. record.caller = TableReaderCaller::kUserApproximateSize;
  3430. record.is_cache_hit = true;
  3431. expected_records.push_back(record);
  3432. expected_records.push_back(record);
  3433. VerifyBlockAccessTrace(&c, expected_records);
  3434. c.ResetTableReader();
  3435. }
  3436. TEST_P(BlockBasedTableTest, TracingIterator) {
  3437. TableConstructor c(BytewiseComparator());
  3438. Options options;
  3439. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  3440. options.create_if_missing = true;
  3441. table_options.block_cache = NewLRUCache(1024 * 1024, 0);
  3442. table_options.cache_index_and_filter_blocks = true;
  3443. table_options.filter_policy.reset(NewBloomFilterPolicy(10, true));
  3444. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  3445. SetupTracingTest(&c);
  3446. std::vector<std::string> keys;
  3447. stl_wrappers::KVMap kvmap;
  3448. ImmutableOptions ioptions(options);
  3449. MutableCFOptions moptions(options);
  3450. c.Finish(options, ioptions, moptions, table_options,
  3451. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  3452. for (uint32_t i = 1; i <= 2; i++) {
  3453. ReadOptions read_options;
  3454. std::unique_ptr<InternalIterator> iter(c.GetTableReader()->NewIterator(
  3455. read_options, moptions.prefix_extractor.get(), /*arena=*/nullptr,
  3456. /*skip_filters=*/false, TableReaderCaller::kUserIterator));
  3457. iter->SeekToFirst();
  3458. while (iter->Valid()) {
  3459. iter->key();
  3460. iter->value();
  3461. iter->Next();
  3462. }
  3463. ASSERT_OK(iter->status());
  3464. iter.reset();
  3465. }
  3466. // Verify traces.
  3467. std::vector<BlockCacheTraceRecord> expected_records;
  3468. // The first two records should be prefetching index and filter blocks.
  3469. BlockCacheTraceRecord record;
  3470. record.block_type = TraceType::kBlockTraceIndexBlock;
  3471. record.caller = TableReaderCaller::kPrefetch;
  3472. record.is_cache_hit = false;
  3473. record.no_insert = false;
  3474. expected_records.push_back(record);
  3475. record.block_type = TraceType::kBlockTraceFilterBlock;
  3476. expected_records.push_back(record);
  3477. // Then we should have three records for index and two data block access.
  3478. record.block_type = TraceType::kBlockTraceIndexBlock;
  3479. record.caller = TableReaderCaller::kUserIterator;
  3480. record.is_cache_hit = true;
  3481. expected_records.push_back(record);
  3482. record.block_type = TraceType::kBlockTraceDataBlock;
  3483. record.is_cache_hit = false;
  3484. expected_records.push_back(record);
  3485. expected_records.push_back(record);
  3486. // When we iterate this file for the second time, we should observe all
  3487. // cache hits.
  3488. record.block_type = TraceType::kBlockTraceIndexBlock;
  3489. record.is_cache_hit = true;
  3490. expected_records.push_back(record);
  3491. record.block_type = TraceType::kBlockTraceDataBlock;
  3492. expected_records.push_back(record);
  3493. expected_records.push_back(record);
  3494. VerifyBlockAccessTrace(&c, expected_records);
  3495. c.ResetTableReader();
  3496. }
  3497. // A simple tool that takes the snapshot of block cache statistics.
  3498. class BlockCachePropertiesSnapshot {
  3499. public:
  3500. explicit BlockCachePropertiesSnapshot(Statistics* statistics) {
  3501. block_cache_miss = statistics->getTickerCount(BLOCK_CACHE_MISS);
  3502. block_cache_hit = statistics->getTickerCount(BLOCK_CACHE_HIT);
  3503. index_block_cache_miss = statistics->getTickerCount(BLOCK_CACHE_INDEX_MISS);
  3504. index_block_cache_hit = statistics->getTickerCount(BLOCK_CACHE_INDEX_HIT);
  3505. data_block_cache_miss = statistics->getTickerCount(BLOCK_CACHE_DATA_MISS);
  3506. data_block_cache_hit = statistics->getTickerCount(BLOCK_CACHE_DATA_HIT);
  3507. filter_block_cache_miss =
  3508. statistics->getTickerCount(BLOCK_CACHE_FILTER_MISS);
  3509. filter_block_cache_hit = statistics->getTickerCount(BLOCK_CACHE_FILTER_HIT);
  3510. block_cache_bytes_read = statistics->getTickerCount(BLOCK_CACHE_BYTES_READ);
  3511. block_cache_bytes_write =
  3512. statistics->getTickerCount(BLOCK_CACHE_BYTES_WRITE);
  3513. }
  3514. void AssertIndexBlockStat(int64_t expected_index_block_cache_miss,
  3515. int64_t expected_index_block_cache_hit) {
  3516. ASSERT_EQ(expected_index_block_cache_miss, index_block_cache_miss);
  3517. ASSERT_EQ(expected_index_block_cache_hit, index_block_cache_hit);
  3518. }
  3519. void AssertFilterBlockStat(int64_t expected_filter_block_cache_miss,
  3520. int64_t expected_filter_block_cache_hit) {
  3521. ASSERT_EQ(expected_filter_block_cache_miss, filter_block_cache_miss);
  3522. ASSERT_EQ(expected_filter_block_cache_hit, filter_block_cache_hit);
  3523. }
  3524. // Check if the fetched props matches the expected ones.
  3525. // TODO(kailiu) Use this only when you disabled filter policy!
  3526. void AssertEqual(int64_t expected_index_block_cache_miss,
  3527. int64_t expected_index_block_cache_hit,
  3528. int64_t expected_data_block_cache_miss,
  3529. int64_t expected_data_block_cache_hit) const {
  3530. ASSERT_EQ(expected_index_block_cache_miss, index_block_cache_miss);
  3531. ASSERT_EQ(expected_index_block_cache_hit, index_block_cache_hit);
  3532. ASSERT_EQ(expected_data_block_cache_miss, data_block_cache_miss);
  3533. ASSERT_EQ(expected_data_block_cache_hit, data_block_cache_hit);
  3534. ASSERT_EQ(expected_index_block_cache_miss + expected_data_block_cache_miss,
  3535. block_cache_miss);
  3536. ASSERT_EQ(expected_index_block_cache_hit + expected_data_block_cache_hit,
  3537. block_cache_hit);
  3538. }
  3539. int64_t GetCacheBytesRead() { return block_cache_bytes_read; }
  3540. int64_t GetCacheBytesWrite() { return block_cache_bytes_write; }
  3541. private:
  3542. int64_t block_cache_miss = 0;
  3543. int64_t block_cache_hit = 0;
  3544. int64_t index_block_cache_miss = 0;
  3545. int64_t index_block_cache_hit = 0;
  3546. int64_t data_block_cache_miss = 0;
  3547. int64_t data_block_cache_hit = 0;
  3548. int64_t filter_block_cache_miss = 0;
  3549. int64_t filter_block_cache_hit = 0;
  3550. int64_t block_cache_bytes_read = 0;
  3551. int64_t block_cache_bytes_write = 0;
  3552. };
  3553. // Make sure, by default, index/filter blocks were pre-loaded (meaning we
  3554. // won't use block cache to store them).
  3555. TEST_P(BlockBasedTableTest, BlockCacheDisabledTest) {
  3556. Options options;
  3557. options.create_if_missing = true;
  3558. options.statistics = CreateDBStatistics();
  3559. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  3560. table_options.block_cache = NewLRUCache(1024, 4);
  3561. table_options.filter_policy.reset(NewBloomFilterPolicy(10));
  3562. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  3563. std::vector<std::string> keys;
  3564. stl_wrappers::KVMap kvmap;
  3565. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  3566. c.Add("key", "value");
  3567. const ImmutableOptions ioptions(options);
  3568. const MutableCFOptions moptions(options);
  3569. c.Finish(options, ioptions, moptions, table_options,
  3570. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  3571. // preloading filter/index blocks is enabled.
  3572. auto reader = dynamic_cast<BlockBasedTable*>(c.GetTableReader());
  3573. ASSERT_FALSE(reader->TEST_FilterBlockInCache());
  3574. ASSERT_FALSE(reader->TEST_IndexBlockInCache());
  3575. {
  3576. // nothing happens in the beginning
  3577. BlockCachePropertiesSnapshot props(options.statistics.get());
  3578. props.AssertIndexBlockStat(0, 0);
  3579. props.AssertFilterBlockStat(0, 0);
  3580. }
  3581. {
  3582. GetContext get_context(options.comparator, nullptr, nullptr, nullptr,
  3583. GetContext::kNotFound, Slice(), nullptr, nullptr,
  3584. nullptr, nullptr, true, nullptr, nullptr);
  3585. // a hack that just to trigger BlockBasedTable::GetFilter.
  3586. ASSERT_OK(reader->Get(ReadOptions(), "non-exist-key", &get_context,
  3587. moptions.prefix_extractor.get()));
  3588. BlockCachePropertiesSnapshot props(options.statistics.get());
  3589. props.AssertIndexBlockStat(0, 0);
  3590. props.AssertFilterBlockStat(0, 0);
  3591. }
  3592. }
  3593. // Due to the difficulities of the intersaction between statistics, this test
  3594. // only tests the case when "index block is put to block cache"
  3595. TEST_P(BlockBasedTableTest, FilterBlockInBlockCache) {
  3596. // -- Table construction
  3597. Options options;
  3598. options.create_if_missing = true;
  3599. options.statistics = CreateDBStatistics();
  3600. // Enable the cache for index/filter blocks
  3601. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  3602. LRUCacheOptions co;
  3603. co.capacity = 2048;
  3604. co.num_shard_bits = 2;
  3605. co.metadata_charge_policy = kDontChargeCacheMetadata;
  3606. table_options.block_cache = NewLRUCache(co);
  3607. table_options.cache_index_and_filter_blocks = true;
  3608. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  3609. std::vector<std::string> keys;
  3610. stl_wrappers::KVMap kvmap;
  3611. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  3612. c.Add("key", "value");
  3613. const ImmutableOptions ioptions(options);
  3614. const MutableCFOptions moptions(options);
  3615. c.Finish(options, ioptions, moptions, table_options,
  3616. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  3617. // preloading filter/index blocks is prohibited.
  3618. auto* reader = dynamic_cast<BlockBasedTable*>(c.GetTableReader());
  3619. ASSERT_FALSE(reader->TEST_FilterBlockInCache());
  3620. ASSERT_TRUE(reader->TEST_IndexBlockInCache());
  3621. // -- PART 1: Open with regular block cache.
  3622. // Since block_cache is disabled, no cache activities will be involved.
  3623. std::unique_ptr<InternalIterator> iter;
  3624. int64_t last_cache_bytes_read = 0;
  3625. // At first, no block will be accessed.
  3626. {
  3627. BlockCachePropertiesSnapshot props(options.statistics.get());
  3628. // index will be added to block cache.
  3629. props.AssertEqual(1, // index block miss
  3630. 0, 0, 0);
  3631. ASSERT_EQ(props.GetCacheBytesRead(), 0);
  3632. ASSERT_EQ(props.GetCacheBytesWrite(),
  3633. static_cast<int64_t>(table_options.block_cache->GetUsage()));
  3634. last_cache_bytes_read = props.GetCacheBytesRead();
  3635. }
  3636. // Only index block will be accessed
  3637. {
  3638. iter.reset(c.NewIterator(moptions.prefix_extractor.get()));
  3639. BlockCachePropertiesSnapshot props(options.statistics.get());
  3640. // NOTE: to help better highlight the "detla" of each ticker, I use
  3641. // <last_value> + <added_value> to indicate the increment of changed
  3642. // value; other numbers remain the same.
  3643. props.AssertEqual(1, 0 + 1, // index block hit
  3644. 0, 0);
  3645. // Cache hit, bytes read from cache should increase
  3646. ASSERT_GT(props.GetCacheBytesRead(), last_cache_bytes_read);
  3647. ASSERT_EQ(props.GetCacheBytesWrite(),
  3648. static_cast<int64_t>(table_options.block_cache->GetUsage()));
  3649. last_cache_bytes_read = props.GetCacheBytesRead();
  3650. }
  3651. // Only data block will be accessed
  3652. {
  3653. iter->SeekToFirst();
  3654. ASSERT_OK(iter->status());
  3655. BlockCachePropertiesSnapshot props(options.statistics.get());
  3656. props.AssertEqual(1, 1, 0 + 1, // data block miss
  3657. 0);
  3658. // Cache miss, Bytes read from cache should not change
  3659. ASSERT_EQ(props.GetCacheBytesRead(), last_cache_bytes_read);
  3660. ASSERT_EQ(props.GetCacheBytesWrite(),
  3661. static_cast<int64_t>(table_options.block_cache->GetUsage()));
  3662. last_cache_bytes_read = props.GetCacheBytesRead();
  3663. }
  3664. // Data block will be in cache
  3665. {
  3666. iter.reset(c.NewIterator(moptions.prefix_extractor.get()));
  3667. iter->SeekToFirst();
  3668. ASSERT_OK(iter->status());
  3669. BlockCachePropertiesSnapshot props(options.statistics.get());
  3670. props.AssertEqual(1, 1 + 1, /* index block hit */
  3671. 1, 0 + 1 /* data block hit */);
  3672. // Cache hit, bytes read from cache should increase
  3673. ASSERT_GT(props.GetCacheBytesRead(), last_cache_bytes_read);
  3674. ASSERT_EQ(props.GetCacheBytesWrite(),
  3675. static_cast<int64_t>(table_options.block_cache->GetUsage()));
  3676. }
  3677. // release the iterator so that the block cache can reset correctly.
  3678. iter.reset();
  3679. c.ResetTableReader();
  3680. // -- PART 2: Open with very small block cache
  3681. // In this test, no block will ever get hit since the block cache is
  3682. // too small to fit even one entry.
  3683. table_options.block_cache = NewLRUCache(1, 4);
  3684. options.statistics = CreateDBStatistics();
  3685. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  3686. const ImmutableOptions ioptions2(options);
  3687. const MutableCFOptions moptions2(options);
  3688. ASSERT_OK(c.Reopen(ioptions2, moptions2));
  3689. {
  3690. BlockCachePropertiesSnapshot props(options.statistics.get());
  3691. props.AssertEqual(1, // index block miss
  3692. 0, 0, 0);
  3693. // Cache miss, Bytes read from cache should not change
  3694. ASSERT_EQ(props.GetCacheBytesRead(), 0);
  3695. }
  3696. {
  3697. // Both index and data block get accessed.
  3698. // It first cache index block then data block. But since the cache size
  3699. // is only 1, index block will be purged after data block is inserted.
  3700. iter.reset(c.NewIterator(moptions2.prefix_extractor.get()));
  3701. BlockCachePropertiesSnapshot props(options.statistics.get());
  3702. props.AssertEqual(1 + 1, // index block miss
  3703. 0, 0, // data block miss
  3704. 0);
  3705. // Cache hit, bytes read from cache should increase
  3706. ASSERT_EQ(props.GetCacheBytesRead(), 0);
  3707. }
  3708. {
  3709. // SeekToFirst() accesses data block. With similar reason, we expect data
  3710. // block's cache miss.
  3711. iter->SeekToFirst();
  3712. ASSERT_OK(iter->status());
  3713. BlockCachePropertiesSnapshot props(options.statistics.get());
  3714. props.AssertEqual(2, 0, 0 + 1, // data block miss
  3715. 0);
  3716. // Cache miss, Bytes read from cache should not change
  3717. ASSERT_EQ(props.GetCacheBytesRead(), 0);
  3718. }
  3719. iter.reset();
  3720. c.ResetTableReader();
  3721. // -- PART 3: Open table with bloom filter enabled but not in SST file
  3722. table_options.block_cache = NewLRUCache(4096, 4);
  3723. table_options.cache_index_and_filter_blocks = false;
  3724. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  3725. TableConstructor c3(BytewiseComparator());
  3726. std::string user_key = "k01";
  3727. InternalKey internal_key(user_key, 0, kTypeValue);
  3728. c3.Add(internal_key.Encode().ToString(), "hello");
  3729. ImmutableOptions ioptions3(options);
  3730. MutableCFOptions moptions3(options);
  3731. // Generate table without filter policy
  3732. c3.Finish(options, ioptions3, moptions3, table_options,
  3733. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  3734. c3.ResetTableReader();
  3735. // Open table with filter policy
  3736. table_options.filter_policy.reset(NewBloomFilterPolicy(1));
  3737. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  3738. options.statistics = CreateDBStatistics();
  3739. ImmutableOptions ioptions4(options);
  3740. MutableCFOptions moptions4(options);
  3741. ASSERT_OK(c3.Reopen(ioptions4, moptions4));
  3742. reader = dynamic_cast<BlockBasedTable*>(c3.GetTableReader());
  3743. ASSERT_FALSE(reader->TEST_FilterBlockInCache());
  3744. PinnableSlice value;
  3745. GetContext get_context(options.comparator, nullptr, nullptr, nullptr,
  3746. GetContext::kNotFound, user_key, &value, nullptr,
  3747. nullptr, nullptr, true, nullptr, nullptr);
  3748. ASSERT_OK(reader->Get(ReadOptions(), internal_key.Encode(), &get_context,
  3749. moptions4.prefix_extractor.get()));
  3750. ASSERT_STREQ(value.data(), "hello");
  3751. BlockCachePropertiesSnapshot props(options.statistics.get());
  3752. props.AssertFilterBlockStat(0, 0);
  3753. c3.ResetTableReader();
  3754. }
  3755. void ValidateBlockSizeDeviation(int value, int expected) {
  3756. BlockBasedTableOptions table_options;
  3757. table_options.block_size_deviation = value;
  3758. BlockBasedTableFactory* factory = new BlockBasedTableFactory(table_options);
  3759. const BlockBasedTableOptions* normalized_table_options =
  3760. factory->GetOptions<BlockBasedTableOptions>();
  3761. ASSERT_EQ(normalized_table_options->block_size_deviation, expected);
  3762. delete factory;
  3763. }
  3764. void ValidateBlockRestartInterval(int value, int expected) {
  3765. BlockBasedTableOptions table_options;
  3766. table_options.block_restart_interval = value;
  3767. BlockBasedTableFactory* factory = new BlockBasedTableFactory(table_options);
  3768. const BlockBasedTableOptions* normalized_table_options =
  3769. factory->GetOptions<BlockBasedTableOptions>();
  3770. ASSERT_EQ(normalized_table_options->block_restart_interval, expected);
  3771. delete factory;
  3772. }
  3773. TEST_P(BlockBasedTableTest, InvalidOptions) {
  3774. // invalid values for block_size_deviation (<0 or >100) are silently set to
  3775. // 0
  3776. ValidateBlockSizeDeviation(-10, 0);
  3777. ValidateBlockSizeDeviation(-1, 0);
  3778. ValidateBlockSizeDeviation(0, 0);
  3779. ValidateBlockSizeDeviation(1, 1);
  3780. ValidateBlockSizeDeviation(99, 99);
  3781. ValidateBlockSizeDeviation(100, 100);
  3782. ValidateBlockSizeDeviation(101, 0);
  3783. ValidateBlockSizeDeviation(1000, 0);
  3784. // invalid values for block_restart_interval (<1) are silently set to 1
  3785. ValidateBlockRestartInterval(-10, 1);
  3786. ValidateBlockRestartInterval(-1, 1);
  3787. ValidateBlockRestartInterval(0, 1);
  3788. ValidateBlockRestartInterval(1, 1);
  3789. ValidateBlockRestartInterval(2, 2);
  3790. ValidateBlockRestartInterval(1000, 1000);
  3791. }
  3792. TEST_P(BlockBasedTableTest, BlockReadCountTest) {
  3793. // bloom_filter_type = 1 -- full filter using use_block_based_builder=false
  3794. // bloom_filter_type = 2 -- full filter using use_block_based_builder=true
  3795. // because of API change to hide block-based filter
  3796. for (int bloom_filter_type = 1; bloom_filter_type <= 2; ++bloom_filter_type) {
  3797. for (int index_and_filter_in_cache = 0; index_and_filter_in_cache < 2;
  3798. ++index_and_filter_in_cache) {
  3799. Options options;
  3800. options.create_if_missing = true;
  3801. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  3802. table_options.block_cache = NewLRUCache(1, 0);
  3803. table_options.cache_index_and_filter_blocks = index_and_filter_in_cache;
  3804. table_options.filter_policy.reset(
  3805. NewBloomFilterPolicy(10, bloom_filter_type == 2));
  3806. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  3807. std::vector<std::string> keys;
  3808. stl_wrappers::KVMap kvmap;
  3809. TableConstructor c(BytewiseComparator());
  3810. std::string user_key = "k04";
  3811. InternalKey internal_key(user_key, 0, kTypeValue);
  3812. std::string encoded_key = internal_key.Encode().ToString();
  3813. c.Add(encoded_key, "hello");
  3814. ImmutableOptions ioptions(options);
  3815. MutableCFOptions moptions(options);
  3816. // Generate table with filter policy
  3817. c.Finish(options, ioptions, moptions, table_options,
  3818. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  3819. auto reader = c.GetTableReader();
  3820. PinnableSlice value;
  3821. {
  3822. GetContext get_context(options.comparator, nullptr, nullptr, nullptr,
  3823. GetContext::kNotFound, user_key, &value, nullptr,
  3824. nullptr, nullptr, true, nullptr, nullptr);
  3825. get_perf_context()->Reset();
  3826. ASSERT_OK(reader->Get(ReadOptions(), encoded_key, &get_context,
  3827. moptions.prefix_extractor.get()));
  3828. if (index_and_filter_in_cache) {
  3829. // data, index and filter block
  3830. ASSERT_EQ(get_perf_context()->block_read_count, 3);
  3831. ASSERT_EQ(get_perf_context()->index_block_read_count, 1);
  3832. ASSERT_EQ(get_perf_context()->filter_block_read_count, 1);
  3833. } else {
  3834. // just the data block
  3835. ASSERT_EQ(get_perf_context()->block_read_count, 1);
  3836. }
  3837. ASSERT_EQ(get_context.State(), GetContext::kFound);
  3838. ASSERT_STREQ(value.data(), "hello");
  3839. }
  3840. // Get non-existing key
  3841. user_key = "does-not-exist";
  3842. internal_key = InternalKey(user_key, 0, kTypeValue);
  3843. encoded_key = internal_key.Encode().ToString();
  3844. value.Reset();
  3845. {
  3846. GetContext get_context(options.comparator, nullptr, nullptr, nullptr,
  3847. GetContext::kNotFound, user_key, &value, nullptr,
  3848. nullptr, nullptr, true, nullptr, nullptr);
  3849. get_perf_context()->Reset();
  3850. ASSERT_OK(reader->Get(ReadOptions(), encoded_key, &get_context,
  3851. moptions.prefix_extractor.get()));
  3852. ASSERT_EQ(get_context.State(), GetContext::kNotFound);
  3853. }
  3854. if (index_and_filter_in_cache) {
  3855. if (bloom_filter_type == 0) {
  3856. // with block-based, we read index and then the filter
  3857. ASSERT_EQ(get_perf_context()->block_read_count, 2);
  3858. ASSERT_EQ(get_perf_context()->index_block_read_count, 1);
  3859. ASSERT_EQ(get_perf_context()->filter_block_read_count, 1);
  3860. } else {
  3861. // with full-filter, we read filter first and then we stop
  3862. ASSERT_EQ(get_perf_context()->block_read_count, 1);
  3863. ASSERT_EQ(get_perf_context()->filter_block_read_count, 1);
  3864. }
  3865. } else {
  3866. // filter is already in memory and it figures out that the key doesn't
  3867. // exist
  3868. ASSERT_EQ(get_perf_context()->block_read_count, 0);
  3869. }
  3870. }
  3871. }
  3872. }
  3873. TEST_P(BlockBasedTableTest, BlockCacheLeak) {
  3874. // Check that when we reopen a table we don't lose access to blocks already
  3875. // in the cache. This test checks whether the Table actually makes use of
  3876. // the unique ID from the file.
  3877. Options opt;
  3878. std::unique_ptr<InternalKeyComparator> ikc;
  3879. ikc.reset(new test::PlainInternalKeyComparator(opt.comparator));
  3880. opt.compression = kNoCompression;
  3881. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  3882. table_options.block_size = 1024;
  3883. // big enough so we don't ever lose cached values.
  3884. table_options.block_cache = NewLRUCache(16 * 1024 * 1024, 4);
  3885. opt.table_factory.reset(NewBlockBasedTableFactory(table_options));
  3886. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  3887. c.Add("k01", "hello");
  3888. c.Add("k02", "hello2");
  3889. c.Add("k03", std::string(10000, 'x'));
  3890. c.Add("k04", std::string(200000, 'x'));
  3891. c.Add("k05", std::string(300000, 'x'));
  3892. c.Add("k06", "hello3");
  3893. c.Add("k07", std::string(100000, 'x'));
  3894. std::vector<std::string> keys;
  3895. stl_wrappers::KVMap kvmap;
  3896. const ImmutableOptions ioptions(opt);
  3897. const MutableCFOptions moptions(opt);
  3898. c.Finish(opt, ioptions, moptions, table_options, *ikc, &keys, &kvmap);
  3899. std::unique_ptr<InternalIterator> iter(
  3900. c.NewIterator(moptions.prefix_extractor.get()));
  3901. iter->SeekToFirst();
  3902. while (iter->Valid()) {
  3903. iter->key();
  3904. iter->value();
  3905. iter->Next();
  3906. }
  3907. ASSERT_OK(iter->status());
  3908. iter.reset();
  3909. const ImmutableOptions ioptions1(opt);
  3910. const MutableCFOptions moptions1(opt);
  3911. ASSERT_OK(c.Reopen(ioptions1, moptions1));
  3912. auto table_reader = dynamic_cast<BlockBasedTable*>(c.GetTableReader());
  3913. for (const std::string& key : keys) {
  3914. InternalKey ikey(key, kMaxSequenceNumber, kTypeValue);
  3915. ASSERT_TRUE(table_reader->TEST_KeyInCache(ReadOptions(), ikey.Encode()));
  3916. }
  3917. c.ResetTableReader();
  3918. // rerun with different block cache
  3919. table_options.block_cache = NewLRUCache(16 * 1024 * 1024, 4);
  3920. opt.table_factory.reset(NewBlockBasedTableFactory(table_options));
  3921. const ImmutableOptions ioptions2(opt);
  3922. const MutableCFOptions moptions2(opt);
  3923. ASSERT_OK(c.Reopen(ioptions2, moptions2));
  3924. table_reader = dynamic_cast<BlockBasedTable*>(c.GetTableReader());
  3925. for (const std::string& key : keys) {
  3926. InternalKey ikey(key, kMaxSequenceNumber, kTypeValue);
  3927. ASSERT_TRUE(!table_reader->TEST_KeyInCache(ReadOptions(), ikey.Encode()));
  3928. }
  3929. c.ResetTableReader();
  3930. }
  3931. TEST_P(BlockBasedTableTest, MemoryAllocator) {
  3932. auto default_memory_allocator = std::make_shared<DefaultMemoryAllocator>();
  3933. auto custom_memory_allocator =
  3934. std::make_shared<CountedMemoryAllocator>(default_memory_allocator);
  3935. {
  3936. Options opt;
  3937. std::unique_ptr<InternalKeyComparator> ikc;
  3938. ikc.reset(new test::PlainInternalKeyComparator(opt.comparator));
  3939. opt.compression = kNoCompression;
  3940. BlockBasedTableOptions table_options;
  3941. table_options.block_size = 1024;
  3942. LRUCacheOptions lruOptions;
  3943. lruOptions.memory_allocator = custom_memory_allocator;
  3944. lruOptions.capacity = 16 * 1024 * 1024;
  3945. lruOptions.num_shard_bits = 4;
  3946. table_options.block_cache = NewLRUCache(std::move(lruOptions));
  3947. opt.table_factory.reset(NewBlockBasedTableFactory(table_options));
  3948. TableConstructor c(BytewiseComparator(),
  3949. true /* convert_to_internal_key_ */);
  3950. c.Add("k01", "hello");
  3951. c.Add("k02", "hello2");
  3952. c.Add("k03", std::string(10000, 'x'));
  3953. c.Add("k04", std::string(200000, 'x'));
  3954. c.Add("k05", std::string(300000, 'x'));
  3955. c.Add("k06", "hello3");
  3956. c.Add("k07", std::string(100000, 'x'));
  3957. std::vector<std::string> keys;
  3958. stl_wrappers::KVMap kvmap;
  3959. const ImmutableOptions ioptions(opt);
  3960. const MutableCFOptions moptions(opt);
  3961. c.Finish(opt, ioptions, moptions, table_options, *ikc, &keys, &kvmap);
  3962. std::unique_ptr<InternalIterator> iter(
  3963. c.NewIterator(moptions.prefix_extractor.get()));
  3964. iter->SeekToFirst();
  3965. while (iter->Valid()) {
  3966. iter->key();
  3967. iter->value();
  3968. iter->Next();
  3969. }
  3970. ASSERT_OK(iter->status());
  3971. }
  3972. // out of scope, block cache should have been deleted, all allocations
  3973. // deallocated
  3974. EXPECT_EQ(custom_memory_allocator->GetNumAllocations(),
  3975. custom_memory_allocator->GetNumDeallocations());
  3976. // make sure that allocations actually happened through the cache allocator
  3977. EXPECT_GT(custom_memory_allocator->GetNumAllocations(), 0);
  3978. }
  3979. // Test the file checksum of block based table
  3980. TEST_P(BlockBasedTableTest, NoFileChecksum) {
  3981. Options options;
  3982. ImmutableOptions ioptions(options);
  3983. MutableCFOptions moptions(options);
  3984. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  3985. std::unique_ptr<InternalKeyComparator> comparator(
  3986. new InternalKeyComparator(BytewiseComparator()));
  3987. int level = 0;
  3988. InternalTblPropCollFactories internal_tbl_prop_coll_factories;
  3989. std::string column_family_name;
  3990. FileChecksumTestHelper f(true);
  3991. f.CreateWritableFile();
  3992. std::unique_ptr<TableBuilder> builder;
  3993. const ReadOptions read_options;
  3994. const WriteOptions write_options;
  3995. builder.reset(moptions.table_factory->NewTableBuilder(
  3996. TableBuilderOptions(ioptions, moptions, read_options, write_options,
  3997. *comparator, &internal_tbl_prop_coll_factories,
  3998. options.compression, options.compression_opts,
  3999. kUnknownColumnFamily, column_family_name, level,
  4000. kUnknownNewestKeyTime),
  4001. f.GetFileWriter()));
  4002. ASSERT_OK(f.ResetTableBuilder(std::move(builder)));
  4003. f.AddKVtoKVMap(1000);
  4004. ASSERT_OK(f.WriteKVAndFlushTable());
  4005. ASSERT_STREQ(f.GetFileChecksumFuncName(), kUnknownFileChecksumFuncName);
  4006. ASSERT_STREQ(f.GetFileChecksum().c_str(), kUnknownFileChecksum);
  4007. }
  4008. TEST_P(BlockBasedTableTest, Crc32cFileChecksum) {
  4009. FileChecksumGenCrc32cFactory* file_checksum_gen_factory =
  4010. new FileChecksumGenCrc32cFactory();
  4011. Options options;
  4012. options.file_checksum_gen_factory.reset(file_checksum_gen_factory);
  4013. ImmutableOptions ioptions(options);
  4014. MutableCFOptions moptions(options);
  4015. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  4016. std::unique_ptr<InternalKeyComparator> comparator(
  4017. new InternalKeyComparator(BytewiseComparator()));
  4018. int level = 0;
  4019. InternalTblPropCollFactories internal_tbl_prop_coll_factories;
  4020. std::string column_family_name;
  4021. FileChecksumGenContext gen_context;
  4022. gen_context.file_name = "db/tmp";
  4023. std::unique_ptr<FileChecksumGenerator> checksum_crc32c_gen1 =
  4024. options.file_checksum_gen_factory->CreateFileChecksumGenerator(
  4025. gen_context);
  4026. FileChecksumTestHelper f(true);
  4027. f.CreateWritableFile();
  4028. f.SetFileChecksumGenerator(checksum_crc32c_gen1.release());
  4029. std::unique_ptr<TableBuilder> builder;
  4030. const ReadOptions read_options;
  4031. const WriteOptions write_options;
  4032. builder.reset(moptions.table_factory->NewTableBuilder(
  4033. TableBuilderOptions(ioptions, moptions, read_options, write_options,
  4034. *comparator, &internal_tbl_prop_coll_factories,
  4035. options.compression, options.compression_opts,
  4036. kUnknownColumnFamily, column_family_name, level,
  4037. kUnknownNewestKeyTime),
  4038. f.GetFileWriter()));
  4039. ASSERT_OK(f.ResetTableBuilder(std::move(builder)));
  4040. f.AddKVtoKVMap(1000);
  4041. ASSERT_OK(f.WriteKVAndFlushTable());
  4042. ASSERT_STREQ(f.GetFileChecksumFuncName(), "FileChecksumCrc32c");
  4043. std::unique_ptr<FileChecksumGenerator> checksum_crc32c_gen2 =
  4044. options.file_checksum_gen_factory->CreateFileChecksumGenerator(
  4045. gen_context);
  4046. std::string checksum;
  4047. ASSERT_OK(f.CalculateFileChecksum(checksum_crc32c_gen2.get(), &checksum));
  4048. ASSERT_STREQ(f.GetFileChecksum().c_str(), checksum.c_str());
  4049. // Unit test the generator itself for schema stability
  4050. std::unique_ptr<FileChecksumGenerator> checksum_crc32c_gen3 =
  4051. options.file_checksum_gen_factory->CreateFileChecksumGenerator(
  4052. gen_context);
  4053. const char data[] = "here is some data";
  4054. checksum_crc32c_gen3->Update(data, sizeof(data));
  4055. checksum_crc32c_gen3->Finalize();
  4056. checksum = checksum_crc32c_gen3->GetChecksum();
  4057. ASSERT_STREQ(checksum.c_str(), "\345\245\277\110");
  4058. }
  4059. TEST_F(PlainTableTest, BasicPlainTableProperties) {
  4060. PlainTableOptions plain_table_options;
  4061. plain_table_options.user_key_len = 8;
  4062. plain_table_options.bloom_bits_per_key = 8;
  4063. plain_table_options.hash_table_ratio = 0;
  4064. PlainTableFactory factory(plain_table_options);
  4065. std::unique_ptr<FSWritableFile> sink(new test::StringSink());
  4066. std::unique_ptr<WritableFileWriter> file_writer(new WritableFileWriter(
  4067. std::move(sink), "" /* don't care */, FileOptions()));
  4068. Options options;
  4069. const ImmutableOptions ioptions(options);
  4070. const MutableCFOptions moptions(options);
  4071. InternalKeyComparator ikc(options.comparator);
  4072. InternalTblPropCollFactories internal_tbl_prop_coll_factories;
  4073. std::string column_family_name;
  4074. int unknown_level = -1;
  4075. const ReadOptions read_options;
  4076. const WriteOptions write_options;
  4077. std::unique_ptr<TableBuilder> builder(factory.NewTableBuilder(
  4078. TableBuilderOptions(ioptions, moptions, read_options, write_options, ikc,
  4079. &internal_tbl_prop_coll_factories, kNoCompression,
  4080. CompressionOptions(), kUnknownColumnFamily,
  4081. column_family_name, unknown_level,
  4082. kUnknownNewestKeyTime),
  4083. file_writer.get()));
  4084. for (char c = 'a'; c <= 'z'; ++c) {
  4085. std::string key(8, c);
  4086. key.append("\1 "); // PlainTable expects internal key structure
  4087. std::string value(28, c + 42);
  4088. builder->Add(key, value);
  4089. }
  4090. ASSERT_OK(builder->Finish());
  4091. ASSERT_OK(file_writer->Flush(IOOptions()));
  4092. test::StringSink* ss =
  4093. static_cast<test::StringSink*>(file_writer->writable_file());
  4094. std::unique_ptr<FSRandomAccessFile> source(
  4095. new test::StringSource(ss->contents(), 72242, true));
  4096. std::unique_ptr<RandomAccessFileReader> file_reader(
  4097. new RandomAccessFileReader(std::move(source), "test"));
  4098. std::unique_ptr<TableProperties> props;
  4099. auto s = ReadTableProperties(file_reader.get(), ss->contents().size(),
  4100. kPlainTableMagicNumber, ioptions, read_options,
  4101. &props);
  4102. ASSERT_OK(s);
  4103. ASSERT_EQ(0ul, props->index_size);
  4104. ASSERT_EQ(0ul, props->filter_size);
  4105. ASSERT_EQ(16ul * 26, props->raw_key_size);
  4106. ASSERT_EQ(28ul * 26, props->raw_value_size);
  4107. ASSERT_EQ(26ul, props->num_entries);
  4108. ASSERT_EQ(1ul, props->num_data_blocks);
  4109. }
  4110. TEST_F(PlainTableTest, NoFileChecksum) {
  4111. PlainTableOptions plain_table_options;
  4112. plain_table_options.user_key_len = 20;
  4113. plain_table_options.bloom_bits_per_key = 8;
  4114. plain_table_options.hash_table_ratio = 0;
  4115. PlainTableFactory factory(plain_table_options);
  4116. Options options;
  4117. const ImmutableOptions ioptions(options);
  4118. const MutableCFOptions moptions(options);
  4119. InternalKeyComparator ikc(options.comparator);
  4120. InternalTblPropCollFactories internal_tbl_prop_coll_factories;
  4121. std::string column_family_name;
  4122. int unknown_level = -1;
  4123. FileChecksumTestHelper f(true);
  4124. f.CreateWritableFile();
  4125. const ReadOptions read_options;
  4126. const WriteOptions write_options;
  4127. std::unique_ptr<TableBuilder> builder(factory.NewTableBuilder(
  4128. TableBuilderOptions(ioptions, moptions, read_options, write_options, ikc,
  4129. &internal_tbl_prop_coll_factories, kNoCompression,
  4130. CompressionOptions(), kUnknownColumnFamily,
  4131. column_family_name, unknown_level,
  4132. kUnknownNewestKeyTime),
  4133. f.GetFileWriter()));
  4134. ASSERT_OK(f.ResetTableBuilder(std::move(builder)));
  4135. f.AddKVtoKVMap(1000);
  4136. ASSERT_OK(f.WriteKVAndFlushTable());
  4137. ASSERT_STREQ(f.GetFileChecksumFuncName(), kUnknownFileChecksumFuncName);
  4138. EXPECT_EQ(f.GetFileChecksum(), kUnknownFileChecksum);
  4139. }
  4140. TEST_F(PlainTableTest, Crc32cFileChecksum) {
  4141. PlainTableOptions plain_table_options;
  4142. plain_table_options.user_key_len = 20;
  4143. plain_table_options.bloom_bits_per_key = 8;
  4144. plain_table_options.hash_table_ratio = 0;
  4145. PlainTableFactory factory(plain_table_options);
  4146. FileChecksumGenCrc32cFactory* file_checksum_gen_factory =
  4147. new FileChecksumGenCrc32cFactory();
  4148. Options options;
  4149. options.file_checksum_gen_factory.reset(file_checksum_gen_factory);
  4150. const ImmutableOptions ioptions(options);
  4151. const MutableCFOptions moptions(options);
  4152. InternalKeyComparator ikc(options.comparator);
  4153. InternalTblPropCollFactories internal_tbl_prop_coll_factories;
  4154. std::string column_family_name;
  4155. int unknown_level = -1;
  4156. FileChecksumGenContext gen_context;
  4157. gen_context.file_name = "db/tmp";
  4158. std::unique_ptr<FileChecksumGenerator> checksum_crc32c_gen1 =
  4159. options.file_checksum_gen_factory->CreateFileChecksumGenerator(
  4160. gen_context);
  4161. FileChecksumTestHelper f(true);
  4162. f.CreateWritableFile();
  4163. f.SetFileChecksumGenerator(checksum_crc32c_gen1.release());
  4164. const ReadOptions read_options;
  4165. const WriteOptions write_options;
  4166. std::unique_ptr<TableBuilder> builder(factory.NewTableBuilder(
  4167. TableBuilderOptions(ioptions, moptions, read_options, write_options, ikc,
  4168. &internal_tbl_prop_coll_factories, kNoCompression,
  4169. CompressionOptions(), kUnknownColumnFamily,
  4170. column_family_name, unknown_level,
  4171. kUnknownNewestKeyTime),
  4172. f.GetFileWriter()));
  4173. ASSERT_OK(f.ResetTableBuilder(std::move(builder)));
  4174. f.AddKVtoKVMap(1000);
  4175. ASSERT_OK(f.WriteKVAndFlushTable());
  4176. ASSERT_STREQ(f.GetFileChecksumFuncName(), "FileChecksumCrc32c");
  4177. std::unique_ptr<FileChecksumGenerator> checksum_crc32c_gen2 =
  4178. options.file_checksum_gen_factory->CreateFileChecksumGenerator(
  4179. gen_context);
  4180. std::string checksum;
  4181. ASSERT_OK(f.CalculateFileChecksum(checksum_crc32c_gen2.get(), &checksum));
  4182. EXPECT_STREQ(f.GetFileChecksum().c_str(), checksum.c_str());
  4183. }
  4184. TEST_F(GeneralTableTest, ApproximateOffsetOfPlain) {
  4185. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  4186. c.Add("k01", "hello");
  4187. c.Add("k02", "hello2");
  4188. c.Add("k03", std::string(10000, 'x'));
  4189. c.Add("k04", std::string(200000, 'x'));
  4190. c.Add("k05", std::string(300000, 'x'));
  4191. c.Add("k06", "hello3");
  4192. c.Add("k07", std::string(100000, 'x'));
  4193. std::vector<std::string> keys;
  4194. stl_wrappers::KVMap kvmap;
  4195. Options options;
  4196. options.db_host_id = "";
  4197. test::PlainInternalKeyComparator internal_comparator(options.comparator);
  4198. options.compression = kNoCompression;
  4199. BlockBasedTableOptions table_options;
  4200. table_options.block_size = 1024;
  4201. const ImmutableOptions ioptions(options);
  4202. const MutableCFOptions moptions(options);
  4203. c.Finish(options, ioptions, moptions, table_options, internal_comparator,
  4204. &keys, &kvmap);
  4205. ASSERT_TRUE(Between(c.ApproximateOffsetOf("abc"), 0, 0));
  4206. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k01"), 0, 0));
  4207. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k01a"), 0, 0));
  4208. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k02"), 0, 0));
  4209. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k03"), 0, 0));
  4210. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k04"), 10000, 11000));
  4211. // k04 and k05 will be in two consecutive blocks, the index is
  4212. // an arbitrary slice between k04 and k05, either before or after k04a
  4213. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k04a"), 10000, 211000));
  4214. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k05"), 210000, 211000));
  4215. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k06"), 510000, 512000));
  4216. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k07"), 510000, 512000));
  4217. ASSERT_TRUE(Between(c.ApproximateOffsetOf("xyz"), 610000, 612000));
  4218. c.ResetTableReader();
  4219. }
  4220. static void DoCompressionTest(CompressionType comp) {
  4221. SCOPED_TRACE("CompressionType = " + CompressionTypeToString(comp));
  4222. Random rnd(301);
  4223. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  4224. std::string tmp;
  4225. c.Add("k01", "hello");
  4226. c.Add("k02", test::CompressibleString(&rnd, 0.25, 10000, &tmp));
  4227. c.Add("k03", "hello3");
  4228. c.Add("k04", test::CompressibleString(&rnd, 0.25, 10000, &tmp));
  4229. std::vector<std::string> keys;
  4230. stl_wrappers::KVMap kvmap;
  4231. Options options;
  4232. test::PlainInternalKeyComparator ikc(options.comparator);
  4233. options.compression = comp;
  4234. options.db_host_id = "";
  4235. BlockBasedTableOptions table_options;
  4236. table_options.block_size = 1024;
  4237. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  4238. const ImmutableOptions ioptions(options);
  4239. const MutableCFOptions moptions(options);
  4240. c.Finish(options, ioptions, moptions, table_options, ikc, &keys, &kvmap);
  4241. size_t file_size = c.TEST_GetSink()->contents().size();
  4242. EXPECT_EQ(c.ApproximateOffsetOf("abc"), 0);
  4243. EXPECT_EQ(c.ApproximateOffsetOf("k01"), 0);
  4244. EXPECT_EQ(c.ApproximateOffsetOf("k02"), 0);
  4245. EXPECT_NEAR2(c.ApproximateOffsetOf("k03"), file_size / 2, file_size / 10);
  4246. EXPECT_NEAR2(c.ApproximateOffsetOf("k04"), file_size / 2, file_size / 10);
  4247. EXPECT_NEAR2(c.ApproximateOffsetOf("xyz"), file_size, file_size / 10);
  4248. size_t data_blocks_size = c.GetTableReader()->GetTableProperties()->data_size;
  4249. // Near expected compressed size ~= (0.25 + 0.25) * 10000
  4250. EXPECT_NEAR2(data_blocks_size, 5000, 1500);
  4251. c.ResetTableReader();
  4252. }
  4253. TEST_F(GeneralTableTest, ApproximateOffsetOfCompressed) {
  4254. std::vector<CompressionType> compression_state;
  4255. if (!Snappy_Supported()) {
  4256. fprintf(stderr, "skipping snappy compression tests\n");
  4257. } else {
  4258. compression_state.push_back(kSnappyCompression);
  4259. }
  4260. if (!Zlib_Supported()) {
  4261. fprintf(stderr, "skipping zlib compression tests\n");
  4262. } else {
  4263. compression_state.push_back(kZlibCompression);
  4264. }
  4265. // TODO(kailiu) DoCompressionTest() doesn't work with BZip2.
  4266. /*
  4267. if (!BZip2_Supported()) {
  4268. fprintf(stderr, "skipping bzip2 compression tests\n");
  4269. } else {
  4270. compression_state.push_back(kBZip2Compression);
  4271. }
  4272. */
  4273. if (!LZ4_Supported()) {
  4274. fprintf(stderr, "skipping lz4 and lz4hc compression tests\n");
  4275. } else {
  4276. compression_state.push_back(kLZ4Compression);
  4277. compression_state.push_back(kLZ4HCCompression);
  4278. }
  4279. if (!XPRESS_Supported()) {
  4280. fprintf(stderr, "skipping xpress and xpress compression tests\n");
  4281. } else {
  4282. compression_state.push_back(kXpressCompression);
  4283. }
  4284. for (auto state : compression_state) {
  4285. DoCompressionTest(state);
  4286. }
  4287. }
  4288. TEST_F(GeneralTableTest, ApproximateKeyAnchors) {
  4289. Random rnd(301);
  4290. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  4291. std::string tmp;
  4292. for (int i = 1000; i < 9000; i++) {
  4293. c.Add(std::to_string(i), rnd.RandomString(2000));
  4294. }
  4295. std::vector<std::string> keys;
  4296. stl_wrappers::KVMap kvmap;
  4297. Options options;
  4298. InternalKeyComparator ikc(options.comparator);
  4299. options.compression = kNoCompression;
  4300. BlockBasedTableOptions table_options;
  4301. table_options.block_size = 4096;
  4302. const ImmutableOptions ioptions(options);
  4303. const MutableCFOptions moptions(options);
  4304. c.Finish(options, ioptions, moptions, table_options, ikc, &keys, &kvmap);
  4305. std::vector<TableReader::Anchor> anchors;
  4306. ASSERT_OK(c.GetTableReader()->ApproximateKeyAnchors(ReadOptions(), anchors));
  4307. // The target is 128 anchors. But in reality it can be slightly more or
  4308. // fewer.
  4309. ASSERT_GT(anchors.size(), 120);
  4310. ASSERT_LT(anchors.size(), 140);
  4311. // We have around 8000 keys. With 128 anchors, in average 62.5 keys per
  4312. // anchor. Here we take a rough range and estimate the distance between
  4313. // anchors is between 50 and 100.
  4314. // Total data size is about 18,000,000, so each anchor range is about
  4315. // 140,625. We also take a rough range.
  4316. int prev_num = 1000;
  4317. // Non-last anchor
  4318. for (size_t i = 0; i + 1 < anchors.size(); i++) {
  4319. auto& anchor = anchors[i];
  4320. ASSERT_GT(anchor.range_size, 100000);
  4321. ASSERT_LT(anchor.range_size, 200000);
  4322. // Key might be shortened, so fill 0 in the end if it is the case.
  4323. std::string key_cpy = anchor.user_key;
  4324. key_cpy.append(4 - key_cpy.size(), '0');
  4325. int num = std::stoi(key_cpy);
  4326. ASSERT_GT(num - prev_num, 50);
  4327. ASSERT_LT(num - prev_num, 100);
  4328. prev_num = num;
  4329. }
  4330. ASSERT_EQ("8999", anchors.back().user_key);
  4331. ASSERT_LT(anchors.back().range_size, 200000);
  4332. c.ResetTableReader();
  4333. }
  4334. #if !defined(ROCKSDB_VALGRIND_RUN) || defined(ROCKSDB_FULL_VALGRIND_RUN)
  4335. TEST_P(ParameterizedHarnessTest, RandomizedHarnessTest) {
  4336. Random rnd(test::RandomSeed() + 5);
  4337. for (int num_entries = 0; num_entries < 2000;
  4338. num_entries += (num_entries < 50 ? 1 : 200)) {
  4339. for (int e = 0; e < num_entries; e++) {
  4340. Add(test::RandomKey(&rnd, rnd.Skewed(4)),
  4341. rnd.RandomString(rnd.Skewed(5)));
  4342. }
  4343. Test(&rnd);
  4344. }
  4345. }
  4346. TEST_F(DBHarnessTest, RandomizedLongDB) {
  4347. Random rnd(test::RandomSeed());
  4348. int num_entries = 100000;
  4349. for (int e = 0; e < num_entries; e++) {
  4350. std::string v;
  4351. Add(test::RandomKey(&rnd, rnd.Skewed(4)), rnd.RandomString(rnd.Skewed(5)));
  4352. }
  4353. Test(&rnd);
  4354. // We must have created enough data to force merging
  4355. int files = 0;
  4356. for (int level = 0; level < db()->NumberLevels(); level++) {
  4357. std::string value;
  4358. char name[100];
  4359. snprintf(name, sizeof(name), "rocksdb.num-files-at-level%d", level);
  4360. ASSERT_TRUE(db()->GetProperty(name, &value));
  4361. files += atoi(value.c_str());
  4362. }
  4363. ASSERT_GT(files, 0);
  4364. }
  4365. #endif // !defined(ROCKSDB_VALGRIND_RUN) || defined(ROCKSDB_FULL_VALGRIND_RUN)
  4366. class MemTableTest : public testing::Test {
  4367. public:
  4368. MemTableTest() {
  4369. InternalKeyComparator cmp(BytewiseComparator());
  4370. auto table_factory = std::make_shared<SkipListFactory>();
  4371. options_.memtable_factory = table_factory;
  4372. ImmutableOptions ioptions(options_);
  4373. wb_ = new WriteBufferManager(options_.db_write_buffer_size);
  4374. memtable_ = new MemTable(cmp, ioptions, MutableCFOptions(options_), wb_,
  4375. kMaxSequenceNumber, 0 /* column_family_id */);
  4376. memtable_->Ref();
  4377. }
  4378. ~MemTableTest() {
  4379. delete memtable_->Unref();
  4380. delete wb_;
  4381. }
  4382. MemTable* GetMemTable() { return memtable_; }
  4383. private:
  4384. MemTable* memtable_;
  4385. Options options_;
  4386. WriteBufferManager* wb_;
  4387. };
  4388. TEST_F(MemTableTest, Simple) {
  4389. WriteBatch batch;
  4390. WriteBatchInternal::SetSequence(&batch, 100);
  4391. ASSERT_OK(batch.Put(std::string("k1"), std::string("v1")));
  4392. ASSERT_OK(batch.Put(std::string("k2"), std::string("v2")));
  4393. ASSERT_OK(batch.Put(std::string("k3"), std::string("v3")));
  4394. ASSERT_OK(batch.Put(std::string("largekey"), std::string("vlarge")));
  4395. ASSERT_OK(batch.DeleteRange(std::string("chi"), std::string("xigua")));
  4396. ASSERT_OK(batch.DeleteRange(std::string("begin"), std::string("end")));
  4397. ColumnFamilyMemTablesDefault cf_mems_default(GetMemTable());
  4398. ASSERT_TRUE(
  4399. WriteBatchInternal::InsertInto(&batch, &cf_mems_default, nullptr, nullptr)
  4400. .ok());
  4401. for (int i = 0; i < 2; ++i) {
  4402. Arena arena;
  4403. ScopedArenaPtr<InternalIterator> arena_iter_guard;
  4404. std::unique_ptr<InternalIterator> iter_guard;
  4405. InternalIterator* iter;
  4406. if (i == 0) {
  4407. iter = GetMemTable()->NewIterator(ReadOptions(),
  4408. /*seqno_to_time_mapping=*/nullptr,
  4409. &arena, /*prefix_extractor=*/nullptr,
  4410. /*for_flush=*/false);
  4411. arena_iter_guard.reset(iter);
  4412. } else {
  4413. iter = GetMemTable()->NewRangeTombstoneIterator(
  4414. ReadOptions(), kMaxSequenceNumber /* read_seq */,
  4415. false /* immutable_memtable */);
  4416. iter_guard.reset(iter);
  4417. }
  4418. if (iter == nullptr) {
  4419. continue;
  4420. }
  4421. iter->SeekToFirst();
  4422. while (iter->Valid()) {
  4423. fprintf(stderr, "key: '%s' -> '%s'\n", iter->key().ToString().c_str(),
  4424. iter->value().ToString().c_str());
  4425. iter->Next();
  4426. }
  4427. }
  4428. }
  4429. // Test the empty key
  4430. TEST_P(ParameterizedHarnessTest, SimpleEmptyKey) {
  4431. Random rnd(test::RandomSeed() + 1);
  4432. Add("", "v");
  4433. Test(&rnd);
  4434. }
  4435. TEST_P(ParameterizedHarnessTest, SimpleSingle) {
  4436. Random rnd(test::RandomSeed() + 2);
  4437. Add("abc", "v");
  4438. Test(&rnd);
  4439. }
  4440. TEST_P(ParameterizedHarnessTest, SimpleMulti) {
  4441. Random rnd(test::RandomSeed() + 3);
  4442. Add("abc", "v");
  4443. Add("abcd", "v");
  4444. Add("ac", "v2");
  4445. Test(&rnd);
  4446. }
  4447. TEST_P(ParameterizedHarnessTest, SimpleSpecialKey) {
  4448. Random rnd(test::RandomSeed() + 4);
  4449. Add("\xff\xff", "v3");
  4450. Test(&rnd);
  4451. }
  4452. TEST(TableTest, FooterTests) {
  4453. Random* r = Random::GetTLSInstance();
  4454. uint64_t data_size = (uint64_t{1} << r->Uniform(40)) + r->Uniform(100);
  4455. uint64_t index_size = r->Uniform(1000000000);
  4456. uint64_t metaindex_size = r->Uniform(1000000);
  4457. // 5 == block trailer size
  4458. BlockHandle index(data_size + 5, index_size);
  4459. BlockHandle meta_index(data_size + index_size + 2 * 5, metaindex_size);
  4460. uint64_t footer_offset = data_size + metaindex_size + index_size + 3 * 5;
  4461. uint32_t base_context_checksum = 123456789;
  4462. {
  4463. // legacy block based
  4464. FooterBuilder footer;
  4465. ASSERT_OK(footer.Build(kBlockBasedTableMagicNumber, /* format_version */ 0,
  4466. footer_offset, kCRC32c, meta_index, index));
  4467. Footer decoded_footer;
  4468. ASSERT_OK(decoded_footer.DecodeFrom(footer.GetSlice(), footer_offset));
  4469. ASSERT_EQ(decoded_footer.table_magic_number(), kBlockBasedTableMagicNumber);
  4470. ASSERT_EQ(decoded_footer.checksum_type(), kCRC32c);
  4471. ASSERT_EQ(decoded_footer.metaindex_handle().offset(), meta_index.offset());
  4472. ASSERT_EQ(decoded_footer.metaindex_handle().size(), meta_index.size());
  4473. ASSERT_EQ(decoded_footer.index_handle().offset(), index.offset());
  4474. ASSERT_EQ(decoded_footer.index_handle().size(), index.size());
  4475. ASSERT_EQ(decoded_footer.format_version(), 0U);
  4476. ASSERT_EQ(decoded_footer.base_context_checksum(), 0U);
  4477. ASSERT_EQ(decoded_footer.GetBlockTrailerSize(), 5U);
  4478. // Ensure serialized with legacy magic
  4479. ASSERT_EQ(
  4480. DecodeFixed64(footer.GetSlice().data() + footer.GetSlice().size() - 8),
  4481. kLegacyBlockBasedTableMagicNumber);
  4482. }
  4483. // block based, various checksums, various versions
  4484. for (auto t : GetSupportedChecksums()) {
  4485. for (uint32_t fv = 1; IsSupportedFormatVersion(fv); ++fv) {
  4486. uint32_t maybe_bcc =
  4487. FormatVersionUsesContextChecksum(fv) ? base_context_checksum : 0U;
  4488. FooterBuilder footer;
  4489. ASSERT_OK(footer.Build(kBlockBasedTableMagicNumber, fv, footer_offset, t,
  4490. meta_index, index, maybe_bcc));
  4491. Footer decoded_footer;
  4492. ASSERT_OK(decoded_footer.DecodeFrom(footer.GetSlice(), footer_offset));
  4493. ASSERT_EQ(decoded_footer.table_magic_number(),
  4494. kBlockBasedTableMagicNumber);
  4495. ASSERT_EQ(decoded_footer.checksum_type(), t);
  4496. ASSERT_EQ(decoded_footer.metaindex_handle().offset(),
  4497. meta_index.offset());
  4498. ASSERT_EQ(decoded_footer.metaindex_handle().size(), meta_index.size());
  4499. if (FormatVersionUsesIndexHandleInFooter(fv)) {
  4500. ASSERT_EQ(decoded_footer.index_handle().offset(), index.offset());
  4501. ASSERT_EQ(decoded_footer.index_handle().size(), index.size());
  4502. }
  4503. ASSERT_EQ(decoded_footer.format_version(), fv);
  4504. ASSERT_EQ(decoded_footer.GetBlockTrailerSize(), 5U);
  4505. if (FormatVersionUsesContextChecksum(fv)) {
  4506. ASSERT_EQ(decoded_footer.base_context_checksum(),
  4507. base_context_checksum);
  4508. // Bad offset should fail footer checksum
  4509. decoded_footer = Footer();
  4510. ASSERT_NOK(
  4511. decoded_footer.DecodeFrom(footer.GetSlice(), footer_offset - 1));
  4512. } else {
  4513. ASSERT_EQ(decoded_footer.base_context_checksum(), 0U);
  4514. }
  4515. // Too big metaindex size should also fail encoding only in new footer
  4516. uint64_t big_metaindex_size = 0x100000007U;
  4517. uint64_t big_footer_offset =
  4518. data_size + big_metaindex_size + index_size + 3 * 5;
  4519. BlockHandle big_metaindex =
  4520. BlockHandle(data_size + index_size + 2 * 5, big_metaindex_size);
  4521. ASSERT_NE(footer
  4522. .Build(kBlockBasedTableMagicNumber, fv, big_footer_offset,
  4523. t, big_metaindex, index, maybe_bcc)
  4524. .ok(),
  4525. FormatVersionUsesContextChecksum(fv));
  4526. }
  4527. }
  4528. {
  4529. // legacy plain table
  4530. FooterBuilder footer;
  4531. ASSERT_OK(footer.Build(kPlainTableMagicNumber, /* format_version */ 0,
  4532. footer_offset, kNoChecksum, meta_index));
  4533. Footer decoded_footer;
  4534. ASSERT_OK(decoded_footer.DecodeFrom(footer.GetSlice(), footer_offset));
  4535. ASSERT_EQ(decoded_footer.table_magic_number(), kPlainTableMagicNumber);
  4536. ASSERT_EQ(decoded_footer.checksum_type(), kCRC32c);
  4537. ASSERT_EQ(decoded_footer.metaindex_handle().offset(), meta_index.offset());
  4538. ASSERT_EQ(decoded_footer.metaindex_handle().size(), meta_index.size());
  4539. ASSERT_EQ(decoded_footer.index_handle().offset(), 0U);
  4540. ASSERT_EQ(decoded_footer.index_handle().size(), 0U);
  4541. ASSERT_EQ(decoded_footer.format_version(), 0U);
  4542. ASSERT_EQ(decoded_footer.GetBlockTrailerSize(), 0U);
  4543. // Ensure serialized with legacy magic
  4544. ASSERT_EQ(
  4545. DecodeFixed64(footer.GetSlice().data() + footer.GetSlice().size() - 8),
  4546. kLegacyPlainTableMagicNumber);
  4547. }
  4548. {
  4549. // xxhash plain table (not currently used)
  4550. FooterBuilder footer;
  4551. ASSERT_OK(footer.Build(kPlainTableMagicNumber, /* format_version */ 1,
  4552. footer_offset, kxxHash, meta_index));
  4553. Footer decoded_footer;
  4554. ASSERT_OK(decoded_footer.DecodeFrom(footer.GetSlice(), footer_offset));
  4555. ASSERT_EQ(decoded_footer.table_magic_number(), kPlainTableMagicNumber);
  4556. ASSERT_EQ(decoded_footer.checksum_type(), kxxHash);
  4557. ASSERT_EQ(decoded_footer.metaindex_handle().offset(), meta_index.offset());
  4558. ASSERT_EQ(decoded_footer.metaindex_handle().size(), meta_index.size());
  4559. ASSERT_EQ(decoded_footer.index_handle().offset(), 0U);
  4560. ASSERT_EQ(decoded_footer.index_handle().size(), 0U);
  4561. ASSERT_EQ(decoded_footer.format_version(), 1U);
  4562. ASSERT_EQ(decoded_footer.GetBlockTrailerSize(), 0U);
  4563. }
  4564. }
  4565. class IndexBlockRestartIntervalTest
  4566. : public TableTest,
  4567. public ::testing::WithParamInterface<std::pair<int, bool>> {
  4568. public:
  4569. static std::vector<std::pair<int, bool>> GetRestartValues() {
  4570. return {{-1, false}, {0, false}, {1, false}, {8, false},
  4571. {16, false}, {32, false}, {-1, true}, {0, true},
  4572. {1, true}, {8, true}, {16, true}, {32, true}};
  4573. }
  4574. };
  4575. INSTANTIATE_TEST_CASE_P(
  4576. IndexBlockRestartIntervalTest, IndexBlockRestartIntervalTest,
  4577. ::testing::ValuesIn(IndexBlockRestartIntervalTest::GetRestartValues()));
  4578. TEST_P(IndexBlockRestartIntervalTest, IndexBlockRestartInterval) {
  4579. const int kKeysInTable = 10000;
  4580. const int kKeySize = 100;
  4581. const int kValSize = 500;
  4582. const int index_block_restart_interval = std::get<0>(GetParam());
  4583. const bool value_delta_encoding = std::get<1>(GetParam());
  4584. Options options;
  4585. BlockBasedTableOptions table_options;
  4586. table_options.block_size = 64; // small block size to get big index block
  4587. table_options.index_block_restart_interval = index_block_restart_interval;
  4588. if (value_delta_encoding) {
  4589. table_options.format_version = 4;
  4590. } else {
  4591. table_options.format_version = 3;
  4592. }
  4593. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  4594. TableConstructor c(BytewiseComparator());
  4595. static Random rnd(301);
  4596. for (int i = 0; i < kKeysInTable; i++) {
  4597. InternalKey k(rnd.RandomString(kKeySize), 0, kTypeValue);
  4598. c.Add(k.Encode().ToString(), rnd.RandomString(kValSize));
  4599. }
  4600. std::vector<std::string> keys;
  4601. stl_wrappers::KVMap kvmap;
  4602. std::unique_ptr<InternalKeyComparator> comparator(
  4603. new InternalKeyComparator(BytewiseComparator()));
  4604. const ImmutableOptions ioptions(options);
  4605. const MutableCFOptions moptions(options);
  4606. c.Finish(options, ioptions, moptions, table_options, *comparator, &keys,
  4607. &kvmap);
  4608. auto reader = c.GetTableReader();
  4609. ReadOptions read_options;
  4610. std::unique_ptr<InternalIterator> db_iter(reader->NewIterator(
  4611. read_options, moptions.prefix_extractor.get(), /*arena=*/nullptr,
  4612. /*skip_filters=*/false, TableReaderCaller::kUncategorized));
  4613. // Test point lookup
  4614. for (auto& kv : kvmap) {
  4615. db_iter->Seek(kv.first);
  4616. ASSERT_TRUE(db_iter->Valid());
  4617. ASSERT_OK(db_iter->status());
  4618. ASSERT_EQ(db_iter->key(), kv.first);
  4619. ASSERT_EQ(db_iter->value(), kv.second);
  4620. }
  4621. // Test iterating
  4622. auto kv_iter = kvmap.begin();
  4623. for (db_iter->SeekToFirst(); db_iter->Valid(); db_iter->Next()) {
  4624. ASSERT_EQ(db_iter->key(), kv_iter->first);
  4625. ASSERT_EQ(db_iter->value(), kv_iter->second);
  4626. kv_iter++;
  4627. }
  4628. ASSERT_EQ(kv_iter, kvmap.end());
  4629. c.ResetTableReader();
  4630. }
  4631. class PrefixTest : public testing::Test {
  4632. public:
  4633. PrefixTest() : testing::Test() {}
  4634. ~PrefixTest() override = default;
  4635. };
  4636. namespace {
  4637. // A simple PrefixExtractor that only works for test PrefixAndWholeKeyTest
  4638. class TestPrefixExtractor : public ROCKSDB_NAMESPACE::SliceTransform {
  4639. public:
  4640. ~TestPrefixExtractor() override = default;
  4641. ;
  4642. const char* Name() const override { return "TestPrefixExtractor"; }
  4643. ROCKSDB_NAMESPACE::Slice Transform(
  4644. const ROCKSDB_NAMESPACE::Slice& src) const override {
  4645. assert(IsValid(src));
  4646. return ROCKSDB_NAMESPACE::Slice(src.data(), 3);
  4647. }
  4648. bool InDomain(const ROCKSDB_NAMESPACE::Slice& src) const override {
  4649. return IsValid(src);
  4650. }
  4651. bool InRange(const ROCKSDB_NAMESPACE::Slice& /*dst*/) const override {
  4652. return true;
  4653. }
  4654. bool IsValid(const ROCKSDB_NAMESPACE::Slice& src) const {
  4655. if (src.size() != 4) {
  4656. return false;
  4657. }
  4658. if (src[0] != '[') {
  4659. return false;
  4660. }
  4661. if (src[1] < '0' || src[1] > '9') {
  4662. return false;
  4663. }
  4664. if (src[2] != ']') {
  4665. return false;
  4666. }
  4667. if (src[3] < '0' || src[3] > '9') {
  4668. return false;
  4669. }
  4670. return true;
  4671. }
  4672. };
  4673. } // namespace
  4674. TEST_F(PrefixTest, PrefixAndWholeKeyTest) {
  4675. ROCKSDB_NAMESPACE::Options options;
  4676. options.compaction_style = ROCKSDB_NAMESPACE::kCompactionStyleUniversal;
  4677. options.num_levels = 20;
  4678. options.create_if_missing = true;
  4679. options.optimize_filters_for_hits = false;
  4680. options.target_file_size_base = 268435456;
  4681. options.prefix_extractor = std::make_shared<TestPrefixExtractor>();
  4682. ROCKSDB_NAMESPACE::BlockBasedTableOptions bbto;
  4683. bbto.filter_policy.reset(ROCKSDB_NAMESPACE::NewBloomFilterPolicy(10));
  4684. bbto.block_size = 262144;
  4685. bbto.whole_key_filtering = true;
  4686. const std::string kDBPath = test::PerThreadDBPath("table_prefix_test");
  4687. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  4688. ASSERT_OK(DestroyDB(kDBPath, options));
  4689. ROCKSDB_NAMESPACE::DB* db;
  4690. ASSERT_OK(ROCKSDB_NAMESPACE::DB::Open(options, kDBPath, &db));
  4691. // Create a bunch of keys with 10 filters.
  4692. for (int i = 0; i < 10; i++) {
  4693. std::string prefix = "[" + std::to_string(i) + "]";
  4694. for (int j = 0; j < 10; j++) {
  4695. std::string key = prefix + std::to_string(j);
  4696. ASSERT_OK(db->Put(ROCKSDB_NAMESPACE::WriteOptions(), key, "1"));
  4697. }
  4698. }
  4699. // Trigger compaction.
  4700. ASSERT_OK(db->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  4701. delete db;
  4702. // In the second round, turn whole_key_filtering off and expect
  4703. // rocksdb still works.
  4704. }
  4705. /*
  4706. * Disable TableWithGlobalSeqno since RocksDB does not store global_seqno in
  4707. * the SST file any more. Instead, RocksDB deduces global_seqno from the
  4708. * MANIFEST while reading from an SST. Therefore, it's not possible to test the
  4709. * functionality of global_seqno in a single, isolated unit test without the
  4710. * involvement of Version, VersionSet, etc.
  4711. */
  4712. TEST_P(BlockBasedTableTest, DISABLED_TableWithGlobalSeqno) {
  4713. BlockBasedTableOptions bbto = GetBlockBasedTableOptions();
  4714. test::StringSink* sink = new test::StringSink();
  4715. std::unique_ptr<FSWritableFile> holder(sink);
  4716. std::unique_ptr<WritableFileWriter> file_writer(new WritableFileWriter(
  4717. std::move(holder), "" /* don't care */, FileOptions()));
  4718. Options options;
  4719. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  4720. const ImmutableOptions ioptions(options);
  4721. const MutableCFOptions moptions(options);
  4722. InternalKeyComparator ikc(options.comparator);
  4723. InternalTblPropCollFactories internal_tbl_prop_coll_factories;
  4724. internal_tbl_prop_coll_factories.emplace_back(
  4725. new SstFileWriterPropertiesCollectorFactory(2 /* version */,
  4726. 0 /* global_seqno*/));
  4727. std::string column_family_name;
  4728. const ReadOptions read_options;
  4729. const WriteOptions write_options;
  4730. std::unique_ptr<TableBuilder> builder(options.table_factory->NewTableBuilder(
  4731. TableBuilderOptions(ioptions, moptions, read_options, write_options, ikc,
  4732. &internal_tbl_prop_coll_factories, kNoCompression,
  4733. CompressionOptions(), kUnknownColumnFamily,
  4734. column_family_name, -1, kUnknownNewestKeyTime),
  4735. file_writer.get()));
  4736. for (char c = 'a'; c <= 'z'; ++c) {
  4737. std::string key(8, c);
  4738. std::string value = key;
  4739. InternalKey ik(key, 0, kTypeValue);
  4740. builder->Add(ik.Encode(), value);
  4741. }
  4742. ASSERT_OK(builder->Finish());
  4743. ASSERT_OK(file_writer->Flush(IOOptions()));
  4744. test::RandomRWStringSink ss_rw(sink);
  4745. uint32_t version;
  4746. uint64_t global_seqno;
  4747. uint64_t global_seqno_offset;
  4748. // Helper function to get version, global_seqno, global_seqno_offset
  4749. std::function<void()> GetVersionAndGlobalSeqno = [&]() {
  4750. std::unique_ptr<FSRandomAccessFile> source(
  4751. new test::StringSource(ss_rw.contents(), 73342, true));
  4752. std::unique_ptr<RandomAccessFileReader> file_reader(
  4753. new RandomAccessFileReader(std::move(source), ""));
  4754. std::unique_ptr<TableProperties> props;
  4755. ASSERT_OK(ReadTableProperties(file_reader.get(), ss_rw.contents().size(),
  4756. kBlockBasedTableMagicNumber, ioptions,
  4757. read_options, &props));
  4758. UserCollectedProperties user_props = props->user_collected_properties;
  4759. version = DecodeFixed32(
  4760. user_props[ExternalSstFilePropertyNames::kVersion].c_str());
  4761. global_seqno = DecodeFixed64(
  4762. user_props[ExternalSstFilePropertyNames::kGlobalSeqno].c_str());
  4763. global_seqno_offset = props->external_sst_file_global_seqno_offset;
  4764. };
  4765. // Helper function to update the value of the global seqno in the file
  4766. std::function<void(uint64_t)> SetGlobalSeqno = [&](uint64_t val) {
  4767. std::string new_global_seqno;
  4768. PutFixed64(&new_global_seqno, val);
  4769. ASSERT_OK(ss_rw.Write(global_seqno_offset, new_global_seqno, IOOptions(),
  4770. nullptr));
  4771. };
  4772. // Helper function to get the contents of the table InternalIterator
  4773. std::unique_ptr<TableReader> table_reader;
  4774. std::function<InternalIterator*()> GetTableInternalIter = [&]() {
  4775. std::unique_ptr<FSRandomAccessFile> source(
  4776. new test::StringSource(ss_rw.contents(), 73342, true));
  4777. std::unique_ptr<RandomAccessFileReader> file_reader(
  4778. new RandomAccessFileReader(std::move(source), ""));
  4779. options.table_factory->NewTableReader(
  4780. TableReaderOptions(ioptions, moptions.prefix_extractor,
  4781. moptions.compression_manager.get(), EnvOptions(),
  4782. ikc, 0 /* block_protection_bytes_per_key */),
  4783. std::move(file_reader), ss_rw.contents().size(), &table_reader);
  4784. return table_reader->NewIterator(
  4785. read_options, moptions.prefix_extractor.get(), /*arena=*/nullptr,
  4786. /*skip_filters=*/false, TableReaderCaller::kUncategorized);
  4787. };
  4788. GetVersionAndGlobalSeqno();
  4789. ASSERT_EQ(2u, version);
  4790. ASSERT_EQ(0u, global_seqno);
  4791. InternalIterator* iter = GetTableInternalIter();
  4792. char current_c = 'a';
  4793. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  4794. ParsedInternalKey pik;
  4795. ASSERT_OK(ParseInternalKey(iter->key(), &pik, true /* log_err_key */));
  4796. ASSERT_EQ(pik.type, ValueType::kTypeValue);
  4797. ASSERT_EQ(pik.sequence, 0);
  4798. ASSERT_EQ(pik.user_key, iter->value());
  4799. ASSERT_EQ(pik.user_key.ToString(), std::string(8, current_c));
  4800. current_c++;
  4801. }
  4802. ASSERT_EQ(current_c, 'z' + 1);
  4803. delete iter;
  4804. // Update global sequence number to 10
  4805. SetGlobalSeqno(10);
  4806. GetVersionAndGlobalSeqno();
  4807. ASSERT_EQ(2u, version);
  4808. ASSERT_EQ(10u, global_seqno);
  4809. iter = GetTableInternalIter();
  4810. current_c = 'a';
  4811. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  4812. ParsedInternalKey pik;
  4813. ASSERT_OK(ParseInternalKey(iter->key(), &pik, true /* log_err_key */));
  4814. ASSERT_EQ(pik.type, ValueType::kTypeValue);
  4815. ASSERT_EQ(pik.sequence, 10);
  4816. ASSERT_EQ(pik.user_key, iter->value());
  4817. ASSERT_EQ(pik.user_key.ToString(), std::string(8, current_c));
  4818. current_c++;
  4819. }
  4820. ASSERT_EQ(current_c, 'z' + 1);
  4821. // Verify Seek
  4822. for (char c = 'a'; c <= 'z'; c++) {
  4823. std::string k = std::string(8, c);
  4824. InternalKey ik(k, 10, kValueTypeForSeek);
  4825. iter->Seek(ik.Encode());
  4826. ASSERT_TRUE(iter->Valid());
  4827. ParsedInternalKey pik;
  4828. ASSERT_OK(ParseInternalKey(iter->key(), &pik, true /* log_err_key */));
  4829. ASSERT_EQ(pik.type, ValueType::kTypeValue);
  4830. ASSERT_EQ(pik.sequence, 10);
  4831. ASSERT_EQ(pik.user_key.ToString(), k);
  4832. ASSERT_EQ(iter->value().ToString(), k);
  4833. }
  4834. delete iter;
  4835. // Update global sequence number to 3
  4836. SetGlobalSeqno(3);
  4837. GetVersionAndGlobalSeqno();
  4838. ASSERT_EQ(2u, version);
  4839. ASSERT_EQ(3u, global_seqno);
  4840. iter = GetTableInternalIter();
  4841. current_c = 'a';
  4842. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  4843. ParsedInternalKey pik;
  4844. ASSERT_OK(ParseInternalKey(iter->key(), &pik, true /* log_err_key */));
  4845. ASSERT_EQ(pik.type, ValueType::kTypeValue);
  4846. ASSERT_EQ(pik.sequence, 3);
  4847. ASSERT_EQ(pik.user_key, iter->value());
  4848. ASSERT_EQ(pik.user_key.ToString(), std::string(8, current_c));
  4849. current_c++;
  4850. }
  4851. ASSERT_EQ(current_c, 'z' + 1);
  4852. // Verify Seek
  4853. for (char c = 'a'; c <= 'z'; c++) {
  4854. std::string k = std::string(8, c);
  4855. // seqno=4 is less than 3 so we still should get our key
  4856. InternalKey ik(k, 4, kValueTypeForSeek);
  4857. iter->Seek(ik.Encode());
  4858. ASSERT_TRUE(iter->Valid());
  4859. ParsedInternalKey pik;
  4860. ASSERT_OK(ParseInternalKey(iter->key(), &pik, true /* log_err_key */));
  4861. ASSERT_EQ(pik.type, ValueType::kTypeValue);
  4862. ASSERT_EQ(pik.sequence, 3);
  4863. ASSERT_EQ(pik.user_key.ToString(), k);
  4864. ASSERT_EQ(iter->value().ToString(), k);
  4865. }
  4866. delete iter;
  4867. }
  4868. TEST_P(BlockBasedTableTest, BlockAlignTest) {
  4869. BlockBasedTableOptions bbto = GetBlockBasedTableOptions();
  4870. bbto.block_align = true;
  4871. test::StringSink* sink = new test::StringSink();
  4872. std::unique_ptr<FSWritableFile> holder(sink);
  4873. std::unique_ptr<WritableFileWriter> file_writer(new WritableFileWriter(
  4874. std::move(holder), "" /* don't care */, FileOptions()));
  4875. Options options;
  4876. options.compression = kNoCompression;
  4877. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  4878. ASSERT_OK(options.table_factory->ValidateOptions(
  4879. DBOptions(options), ColumnFamilyOptions(options)));
  4880. const ImmutableOptions ioptions(options);
  4881. const MutableCFOptions moptions(options);
  4882. InternalKeyComparator ikc(options.comparator);
  4883. InternalTblPropCollFactories internal_tbl_prop_coll_factories;
  4884. std::string column_family_name;
  4885. const ReadOptions read_options;
  4886. const WriteOptions write_options;
  4887. std::unique_ptr<TableBuilder> builder(options.table_factory->NewTableBuilder(
  4888. TableBuilderOptions(ioptions, moptions, read_options, write_options, ikc,
  4889. &internal_tbl_prop_coll_factories, kNoCompression,
  4890. CompressionOptions(), kUnknownColumnFamily,
  4891. column_family_name, -1, kUnknownNewestKeyTime),
  4892. file_writer.get()));
  4893. for (int i = 1; i <= 10000; ++i) {
  4894. std::ostringstream ostr;
  4895. ostr << std::setfill('0') << std::setw(5) << i;
  4896. std::string key = ostr.str();
  4897. std::string value = "val";
  4898. InternalKey ik(key, 0, kTypeValue);
  4899. builder->Add(ik.Encode(), value);
  4900. }
  4901. ASSERT_OK(builder->Finish());
  4902. ASSERT_OK(file_writer->Flush(IOOptions()));
  4903. std::unique_ptr<FSRandomAccessFile> source(
  4904. new test::StringSource(sink->contents(), 73342, false));
  4905. std::unique_ptr<RandomAccessFileReader> file_reader(
  4906. new RandomAccessFileReader(std::move(source), "test"));
  4907. // Helper function to get version, global_seqno, global_seqno_offset
  4908. std::function<void()> VerifyBlockAlignment = [&]() {
  4909. std::unique_ptr<TableProperties> props;
  4910. ASSERT_OK(ReadTableProperties(file_reader.get(), sink->contents().size(),
  4911. kBlockBasedTableMagicNumber, ioptions,
  4912. read_options, &props));
  4913. uint64_t data_block_size = props->data_size / props->num_data_blocks;
  4914. ASSERT_EQ(data_block_size, 4096);
  4915. ASSERT_EQ(props->data_size, data_block_size * props->num_data_blocks);
  4916. };
  4917. VerifyBlockAlignment();
  4918. // The below block of code verifies that we can read back the keys. Set
  4919. // block_align to false when creating the reader to ensure we can flip between
  4920. // the two modes without any issues
  4921. std::unique_ptr<TableReader> table_reader;
  4922. bbto.block_align = false;
  4923. Options options2;
  4924. options2.compression = kNoCompression;
  4925. options2.table_factory.reset(NewBlockBasedTableFactory(bbto));
  4926. ASSERT_OK(options2.table_factory->ValidateOptions(
  4927. DBOptions(options2), ColumnFamilyOptions(options2)));
  4928. ImmutableOptions ioptions2(options2);
  4929. const MutableCFOptions moptions2(options2);
  4930. ASSERT_OK(moptions.table_factory->NewTableReader(
  4931. TableReaderOptions(ioptions2, moptions2.prefix_extractor,
  4932. moptions2.compression_manager.get(), EnvOptions(),
  4933. GetPlainInternalComparator(options2.comparator),
  4934. 0 /* block_protection_bytes_per_key */),
  4935. std::move(file_reader), sink->contents().size(), &table_reader));
  4936. std::unique_ptr<InternalIterator> db_iter(table_reader->NewIterator(
  4937. read_options, moptions2.prefix_extractor.get(), /*arena=*/nullptr,
  4938. /*skip_filters=*/false, TableReaderCaller::kUncategorized));
  4939. int expected_key = 1;
  4940. for (db_iter->SeekToFirst(); db_iter->Valid(); db_iter->Next()) {
  4941. std::ostringstream ostr;
  4942. ostr << std::setfill('0') << std::setw(5) << expected_key++;
  4943. std::string key = ostr.str();
  4944. std::string value = "val";
  4945. ASSERT_OK(db_iter->status());
  4946. ASSERT_EQ(ExtractUserKey(db_iter->key()).ToString(), key);
  4947. ASSERT_EQ(db_iter->value().ToString(), value);
  4948. }
  4949. expected_key--;
  4950. ASSERT_EQ(expected_key, 10000);
  4951. table_reader.reset();
  4952. }
  4953. TEST_P(BlockBasedTableTest, FixBlockAlignMismatchedFileChecksums) {
  4954. Options options;
  4955. options.create_if_missing = true;
  4956. options.compression = kNoCompression;
  4957. options.file_checksum_gen_factory = GetFileChecksumGenCrc32cFactory();
  4958. BlockBasedTableOptions bbto;
  4959. bbto.block_align = true;
  4960. bbto.block_size = 1024;
  4961. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  4962. ASSERT_OK(options.table_factory->ValidateOptions(
  4963. DBOptions(options), ColumnFamilyOptions(options)));
  4964. const std::string kDBPath =
  4965. test::PerThreadDBPath("block_align_padded_bytes_verify_file_checksums");
  4966. ASSERT_OK(DestroyDB(kDBPath, options));
  4967. DB* db;
  4968. ASSERT_OK(DB::Open(options, kDBPath, &db));
  4969. ASSERT_OK(db->Put(WriteOptions(), "k1", "v1"));
  4970. ASSERT_OK(db->Flush(FlushOptions()));
  4971. // Before the fix, VerifyFileChecksums() will fail as padded bytes from
  4972. // aligning blocks are used to generate the checksum to compare against the
  4973. // one not generated by padded bytes
  4974. ASSERT_OK(db->VerifyFileChecksums(ReadOptions()));
  4975. delete db;
  4976. }
  4977. class NoBufferAlignmenttWritableFile : public FSWritableFileOwnerWrapper {
  4978. public:
  4979. explicit NoBufferAlignmenttWritableFile(
  4980. std::unique_ptr<FSWritableFile>&& file)
  4981. : FSWritableFileOwnerWrapper(std::move(file)) {}
  4982. size_t GetRequiredBufferAlignment() const override { return 1; }
  4983. };
  4984. class NoBufferAlignmenttWritableFileFileSystem : public FileSystemWrapper {
  4985. public:
  4986. explicit NoBufferAlignmenttWritableFileFileSystem(
  4987. const std::shared_ptr<FileSystem>& base)
  4988. : FileSystemWrapper(base) {}
  4989. static const char* kClassName() {
  4990. return "NoBufferAlignmenttWritableFileFileSystem";
  4991. }
  4992. const char* Name() const override { return kClassName(); }
  4993. IOStatus NewWritableFile(const std::string& fname,
  4994. const FileOptions& file_opts,
  4995. std::unique_ptr<FSWritableFile>* result,
  4996. IODebugContext* dbg) override {
  4997. IOStatus s = target()->NewWritableFile(fname, file_opts, result, dbg);
  4998. EXPECT_OK(s);
  4999. result->reset(new NoBufferAlignmenttWritableFile(std::move(*result)));
  5000. return s;
  5001. }
  5002. };
  5003. TEST_P(BlockBasedTableTest,
  5004. FixBlockAlignFlushDuringPadMismatchedFileChecksums) {
  5005. Options options;
  5006. options.create_if_missing = true;
  5007. options.compression = kNoCompression;
  5008. options.file_checksum_gen_factory = GetFileChecksumGenCrc32cFactory();
  5009. // To force flush during pad by enforcing a small buffer size
  5010. options.writable_file_max_buffer_size = 1;
  5011. // To help enforce a small buffer size by removing buffer alignment
  5012. Env* raw_env = Env::Default();
  5013. std::shared_ptr<NoBufferAlignmenttWritableFileFileSystem> fs =
  5014. std::make_shared<NoBufferAlignmenttWritableFileFileSystem>(
  5015. raw_env->GetFileSystem());
  5016. std::unique_ptr<Env> env(new CompositeEnvWrapper(raw_env, fs));
  5017. options.env = env.get();
  5018. BlockBasedTableOptions bbto;
  5019. bbto.block_align = true;
  5020. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  5021. const std::string kDBPath = test::PerThreadDBPath(
  5022. "block_align_flush_during_flush_verify_file_checksums");
  5023. ASSERT_OK(DestroyDB(kDBPath, options));
  5024. DB* db;
  5025. ASSERT_OK(DB::Open(options, kDBPath, &db));
  5026. ASSERT_OK(db->Put(WriteOptions(), "k1", "k2"));
  5027. ASSERT_OK(db->Flush(FlushOptions()));
  5028. // Before the fix, VerifyFileChecksums() will fail as incorrect padded bytes
  5029. // were used to generate checksum upon file creation
  5030. ASSERT_OK(db->VerifyFileChecksums(ReadOptions()));
  5031. delete db;
  5032. }
  5033. TEST_P(BlockBasedTableTest, PropertiesBlockRestartPointTest) {
  5034. BlockBasedTableOptions bbto = GetBlockBasedTableOptions();
  5035. bbto.block_align = true;
  5036. test::StringSink* sink = new test::StringSink();
  5037. std::unique_ptr<FSWritableFile> holder(sink);
  5038. std::unique_ptr<WritableFileWriter> file_writer(new WritableFileWriter(
  5039. std::move(holder), "" /* don't care */, FileOptions()));
  5040. Options options;
  5041. options.compression = kNoCompression;
  5042. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  5043. ASSERT_OK(options.table_factory->ValidateOptions(
  5044. DBOptions(options), ColumnFamilyOptions(options)));
  5045. const ImmutableOptions ioptions(options);
  5046. const MutableCFOptions moptions(options);
  5047. InternalKeyComparator ikc(options.comparator);
  5048. InternalTblPropCollFactories internal_tbl_prop_coll_factories;
  5049. std::string column_family_name;
  5050. const ReadOptions read_options;
  5051. const WriteOptions write_options;
  5052. std::unique_ptr<TableBuilder> builder(options.table_factory->NewTableBuilder(
  5053. TableBuilderOptions(ioptions, moptions, read_options, write_options, ikc,
  5054. &internal_tbl_prop_coll_factories, kNoCompression,
  5055. CompressionOptions(), kUnknownColumnFamily,
  5056. column_family_name, -1, kUnknownNewestKeyTime),
  5057. file_writer.get()));
  5058. for (int i = 1; i <= 10000; ++i) {
  5059. std::ostringstream ostr;
  5060. ostr << std::setfill('0') << std::setw(5) << i;
  5061. std::string key = ostr.str();
  5062. std::string value = "val";
  5063. InternalKey ik(key, 0, kTypeValue);
  5064. builder->Add(ik.Encode(), value);
  5065. }
  5066. ASSERT_OK(builder->Finish());
  5067. ASSERT_OK(file_writer->Flush(IOOptions()));
  5068. std::unique_ptr<FSRandomAccessFile> source(
  5069. new test::StringSource(sink->contents(), 73342, true));
  5070. std::unique_ptr<RandomAccessFileReader> file_reader(
  5071. new RandomAccessFileReader(std::move(source), "test"));
  5072. {
  5073. RandomAccessFileReader* file = file_reader.get();
  5074. uint64_t file_size = sink->contents().size();
  5075. Footer footer;
  5076. ASSERT_OK(ReadFooterFromFile(IOOptions(), file, *FileSystem::Default(),
  5077. nullptr /* prefetch_buffer */, file_size,
  5078. &footer, kBlockBasedTableMagicNumber));
  5079. auto BlockFetchHelper = [&](const BlockHandle& handle, BlockType block_type,
  5080. BlockContents* contents) {
  5081. ReadOptions read_options_for_helper;
  5082. read_options_for_helper.verify_checksums = false;
  5083. PersistentCacheOptions cache_options;
  5084. auto mgr = GetBuiltinCompressionManager(
  5085. GetCompressFormatForVersion(footer.format_version()));
  5086. BlockFetcher block_fetcher(file, nullptr /* prefetch_buffer */, footer,
  5087. read_options_for_helper, handle, contents,
  5088. ioptions, false /* decompress */,
  5089. false /*maybe_compressed*/, block_type,
  5090. mgr->GetDecompressor().get(), cache_options);
  5091. ASSERT_OK(block_fetcher.ReadBlockContents());
  5092. };
  5093. // -- Read metaindex block
  5094. auto metaindex_handle = footer.metaindex_handle();
  5095. BlockContents metaindex_contents;
  5096. BlockFetchHelper(metaindex_handle, BlockType::kMetaIndex,
  5097. &metaindex_contents);
  5098. Block metaindex_block(std::move(metaindex_contents));
  5099. std::unique_ptr<InternalIterator> meta_iter(metaindex_block.NewDataIterator(
  5100. BytewiseComparator(), kDisableGlobalSequenceNumber));
  5101. // -- Read properties block
  5102. BlockHandle properties_handle;
  5103. ASSERT_OK(FindOptionalMetaBlock(meta_iter.get(), kPropertiesBlockName,
  5104. &properties_handle));
  5105. ASSERT_FALSE(properties_handle.IsNull());
  5106. BlockContents properties_contents;
  5107. BlockFetchHelper(properties_handle, BlockType::kProperties,
  5108. &properties_contents);
  5109. Block properties_block(std::move(properties_contents));
  5110. ASSERT_EQ(properties_block.NumRestarts(), 1u);
  5111. }
  5112. }
  5113. TEST_P(BlockBasedTableTest, CompressionRatioThreshold) {
  5114. for (CompressionType type : GetSupportedCompressions()) {
  5115. if (type == kNoCompression) {
  5116. continue;
  5117. }
  5118. if (type == kBZip2Compression) {
  5119. // Weird behavior in this test
  5120. continue;
  5121. }
  5122. SCOPED_TRACE("Compression type: " + std::to_string(type));
  5123. Options options;
  5124. options.compression = type;
  5125. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  5126. int len = 10000;
  5127. Random rnd(301);
  5128. std::vector<std::string> keys;
  5129. stl_wrappers::KVMap kvmap;
  5130. // Test the max_compressed_bytes_per_kb option
  5131. for (int threshold : {0, 1, 100, 400, 600, 900, 1024}) {
  5132. SCOPED_TRACE("threshold=" + std::to_string(threshold));
  5133. options.compression_opts.max_compressed_bytes_per_kb = threshold;
  5134. ImmutableOptions ioptions(options);
  5135. MutableCFOptions moptions(options);
  5136. for (double compressible_to : {0.25, 0.75}) {
  5137. SCOPED_TRACE("compressible_to=" + std::to_string(compressible_to));
  5138. TableConstructor c(BytewiseComparator(),
  5139. true /* convert_to_internal_key_ */);
  5140. std::string buf;
  5141. c.Add("x", test::CompressibleString(&rnd, compressible_to, len, &buf));
  5142. // write an SST file
  5143. c.Finish(options, ioptions, moptions, table_options,
  5144. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  5145. size_t table_file_size = c.TEST_GetSink()->contents().size();
  5146. size_t approx_sst_overhead = 1000;
  5147. if (compressible_to < threshold / 1024.0) {
  5148. // Should be compressed (substantial variance depending on algorithm)
  5149. EXPECT_NEAR2(len * compressible_to + approx_sst_overhead,
  5150. table_file_size, len / 8);
  5151. } else {
  5152. // Should not be compressed
  5153. EXPECT_NEAR2(len + approx_sst_overhead, table_file_size, len / 10);
  5154. }
  5155. }
  5156. }
  5157. }
  5158. }
  5159. TEST_P(BlockBasedTableTest, PropertiesMetaBlockLast) {
  5160. // The properties meta-block should come at the end since we always need to
  5161. // read it when opening a file, unlike index/filter/other meta-blocks, which
  5162. // are sometimes read depending on the user's configuration. This ordering
  5163. // allows us to do a small readahead on the end of the file to read properties
  5164. // and meta-index blocks with one I/O.
  5165. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  5166. c.Add("a1", "val1");
  5167. c.Add("b2", "val2");
  5168. c.Add("c3", "val3");
  5169. c.Add("d4", "val4");
  5170. c.Add("e5", "val5");
  5171. c.Add("f6", "val6");
  5172. c.Add("g7", "val7");
  5173. c.Add("h8", "val8");
  5174. c.Add("j9", "val9");
  5175. // write an SST file
  5176. Options options;
  5177. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  5178. table_options.filter_policy.reset(NewBloomFilterPolicy(
  5179. 8 /* bits_per_key */, false /* use_block_based_filter */));
  5180. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  5181. ImmutableOptions ioptions(options);
  5182. MutableCFOptions moptions(options);
  5183. std::vector<std::string> keys;
  5184. stl_wrappers::KVMap kvmap;
  5185. c.Finish(options, ioptions, moptions, table_options,
  5186. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  5187. // get file reader
  5188. test::StringSink* table_sink = c.TEST_GetSink();
  5189. std::unique_ptr<FSRandomAccessFile> source(new test::StringSource(
  5190. table_sink->contents(), 0 /* unique_id */, false /* allow_mmap_reads */));
  5191. std::unique_ptr<RandomAccessFileReader> table_reader(
  5192. new RandomAccessFileReader(std::move(source), "test"));
  5193. size_t table_size = table_sink->contents().size();
  5194. // read footer
  5195. Footer footer;
  5196. IOOptions opts;
  5197. ASSERT_OK(ReadFooterFromFile(opts, table_reader.get(), *FileSystem::Default(),
  5198. nullptr /* prefetch_buffer */, table_size,
  5199. &footer, kBlockBasedTableMagicNumber));
  5200. // read metaindex
  5201. auto metaindex_handle = footer.metaindex_handle();
  5202. BlockContents metaindex_contents;
  5203. PersistentCacheOptions pcache_opts;
  5204. auto mgr = GetBuiltinCompressionManager(
  5205. GetCompressFormatForVersion(footer.format_version()));
  5206. BlockFetcher block_fetcher(
  5207. table_reader.get(), nullptr /* prefetch_buffer */, footer, ReadOptions(),
  5208. metaindex_handle, &metaindex_contents, ioptions, false /* decompress */,
  5209. false /*maybe_compressed*/, BlockType::kMetaIndex,
  5210. mgr->GetDecompressor().get(), pcache_opts, nullptr /*memory_allocator*/);
  5211. ASSERT_OK(block_fetcher.ReadBlockContents());
  5212. Block metaindex_block(std::move(metaindex_contents));
  5213. // verify properties block comes last
  5214. std::unique_ptr<InternalIterator> metaindex_iter{
  5215. metaindex_block.NewMetaIterator()};
  5216. uint64_t max_offset = 0;
  5217. std::string key_at_max_offset;
  5218. for (metaindex_iter->SeekToFirst(); metaindex_iter->Valid();
  5219. metaindex_iter->Next()) {
  5220. BlockHandle handle;
  5221. Slice value = metaindex_iter->value();
  5222. ASSERT_OK(handle.DecodeFrom(&value));
  5223. if (handle.offset() > max_offset) {
  5224. max_offset = handle.offset();
  5225. key_at_max_offset = metaindex_iter->key().ToString();
  5226. }
  5227. }
  5228. ASSERT_EQ(kPropertiesBlockName, key_at_max_offset);
  5229. if (FormatVersionUsesIndexHandleInFooter(footer.format_version())) {
  5230. // If index handle is stored in footer rather than metaindex block,
  5231. // need separate logic to verify it comes before properties block.
  5232. ASSERT_GT(max_offset, footer.index_handle().offset());
  5233. } else {
  5234. ASSERT_TRUE(footer.index_handle().IsNull());
  5235. }
  5236. c.ResetTableReader();
  5237. }
  5238. TEST_P(BlockBasedTableTest, SeekMetaBlocks) {
  5239. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  5240. c.Add("foo_a1", "val1");
  5241. c.Add("foo_b2", "val2");
  5242. c.Add("foo_c3", "val3");
  5243. c.Add("foo_d4", "val4");
  5244. c.Add("foo_e5", "val5");
  5245. c.Add("foo_f6", "val6");
  5246. c.Add("foo_g7", "val7");
  5247. c.Add("foo_h8", "val8");
  5248. c.Add("foo_j9", "val9");
  5249. // write an SST file
  5250. Options options;
  5251. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  5252. table_options.index_type = BlockBasedTableOptions::kHashSearch;
  5253. table_options.filter_policy.reset(NewBloomFilterPolicy(
  5254. 8 /* bits_per_key */, false /* use_block_based_filter */));
  5255. options.prefix_extractor.reset(NewFixedPrefixTransform(4));
  5256. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  5257. ImmutableOptions ioptions(options);
  5258. MutableCFOptions moptions(options);
  5259. std::vector<std::string> keys;
  5260. stl_wrappers::KVMap kvmap;
  5261. c.Finish(options, ioptions, moptions, table_options,
  5262. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  5263. // get file reader
  5264. test::StringSink* table_sink = c.TEST_GetSink();
  5265. std::unique_ptr<FSRandomAccessFile> source(new test::StringSource(
  5266. table_sink->contents(), 0 /* unique_id */, false /* allow_mmap_reads */));
  5267. std::unique_ptr<RandomAccessFileReader> table_reader(
  5268. new RandomAccessFileReader(std::move(source), "test"));
  5269. size_t table_size = table_sink->contents().size();
  5270. // read footer
  5271. Footer footer;
  5272. IOOptions opts;
  5273. ASSERT_OK(ReadFooterFromFile(opts, table_reader.get(), *FileSystem::Default(),
  5274. nullptr /* prefetch_buffer */, table_size,
  5275. &footer, kBlockBasedTableMagicNumber));
  5276. // read metaindex
  5277. auto metaindex_handle = footer.metaindex_handle();
  5278. BlockContents metaindex_contents;
  5279. PersistentCacheOptions pcache_opts;
  5280. auto mgr = GetBuiltinCompressionManager(
  5281. GetCompressFormatForVersion(footer.format_version()));
  5282. BlockFetcher block_fetcher(
  5283. table_reader.get(), nullptr /* prefetch_buffer */, footer, ReadOptions(),
  5284. metaindex_handle, &metaindex_contents, ioptions, false /* decompress */,
  5285. false /*maybe_compressed*/, BlockType::kMetaIndex,
  5286. mgr->GetDecompressor().get(), pcache_opts, nullptr /*memory_allocator*/);
  5287. ASSERT_OK(block_fetcher.ReadBlockContents());
  5288. Block metaindex_block(std::move(metaindex_contents));
  5289. // verify properties block comes last
  5290. std::unique_ptr<MetaBlockIter> metaindex_iter(
  5291. metaindex_block.NewMetaIterator());
  5292. bool has_hash_prefixes = false;
  5293. bool has_hash_metadata = false;
  5294. for (metaindex_iter->SeekToFirst(); metaindex_iter->Valid();
  5295. metaindex_iter->Next()) {
  5296. if (metaindex_iter->key().ToString() == kHashIndexPrefixesBlock) {
  5297. has_hash_prefixes = true;
  5298. } else if (metaindex_iter->key().ToString() ==
  5299. kHashIndexPrefixesMetadataBlock) {
  5300. has_hash_metadata = true;
  5301. }
  5302. }
  5303. if (has_hash_metadata) {
  5304. metaindex_iter->Seek(kHashIndexPrefixesMetadataBlock);
  5305. ASSERT_TRUE(metaindex_iter->Valid());
  5306. ASSERT_EQ(kHashIndexPrefixesMetadataBlock,
  5307. metaindex_iter->key().ToString());
  5308. }
  5309. if (has_hash_prefixes) {
  5310. metaindex_iter->Seek(kHashIndexPrefixesBlock);
  5311. ASSERT_TRUE(metaindex_iter->Valid());
  5312. ASSERT_EQ(kHashIndexPrefixesBlock, metaindex_iter->key().ToString());
  5313. }
  5314. c.ResetTableReader();
  5315. }
  5316. TEST_P(BlockBasedTableTest, BadOptions) {
  5317. ROCKSDB_NAMESPACE::Options options;
  5318. options.compression = kNoCompression;
  5319. options.create_if_missing = true;
  5320. BlockBasedTableOptions bbto = GetBlockBasedTableOptions();
  5321. bbto.block_size = 4000;
  5322. bbto.block_align = true;
  5323. const std::string kDBPath =
  5324. test::PerThreadDBPath("block_based_table_bad_options_test");
  5325. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  5326. ASSERT_OK(DestroyDB(kDBPath, options));
  5327. std::unique_ptr<DB> db;
  5328. {
  5329. ROCKSDB_NAMESPACE::DB* _db;
  5330. ASSERT_NOK(ROCKSDB_NAMESPACE::DB::Open(options, kDBPath, &_db));
  5331. bbto.block_size = 4096;
  5332. options.compression = kSnappyCompression;
  5333. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  5334. ASSERT_NOK(ROCKSDB_NAMESPACE::DB::Open(options, kDBPath, &_db));
  5335. options.compression = kNoCompression;
  5336. options.bottommost_compression = kSnappyCompression;
  5337. ASSERT_NOK(ROCKSDB_NAMESPACE::DB::Open(options, kDBPath, &_db));
  5338. options.bottommost_compression = kNoCompression;
  5339. options.compression_per_level.emplace_back(kSnappyCompression);
  5340. ASSERT_NOK(ROCKSDB_NAMESPACE::DB::Open(options, kDBPath, &_db));
  5341. options.compression_per_level.clear();
  5342. ASSERT_OK(ROCKSDB_NAMESPACE::DB::Open(options, kDBPath, &_db));
  5343. db.reset(_db);
  5344. }
  5345. }
  5346. TEST_F(BBTTailPrefetchTest, TestTailPrefetchStats) {
  5347. TailPrefetchStats tpstats;
  5348. ASSERT_EQ(0, tpstats.GetSuggestedPrefetchSize());
  5349. tpstats.RecordEffectiveSize(size_t{1000});
  5350. tpstats.RecordEffectiveSize(size_t{1005});
  5351. tpstats.RecordEffectiveSize(size_t{1002});
  5352. ASSERT_EQ(1005, tpstats.GetSuggestedPrefetchSize());
  5353. // One single super large value shouldn't influence much
  5354. tpstats.RecordEffectiveSize(size_t{1002000});
  5355. tpstats.RecordEffectiveSize(size_t{999});
  5356. ASSERT_LE(1005, tpstats.GetSuggestedPrefetchSize());
  5357. ASSERT_GT(1200, tpstats.GetSuggestedPrefetchSize());
  5358. // Only history of 32 is kept
  5359. for (int i = 0; i < 32; i++) {
  5360. tpstats.RecordEffectiveSize(size_t{100});
  5361. }
  5362. ASSERT_EQ(100, tpstats.GetSuggestedPrefetchSize());
  5363. // 16 large values and 16 small values. The result should be closer
  5364. // to the small value as the algorithm.
  5365. for (int i = 0; i < 16; i++) {
  5366. tpstats.RecordEffectiveSize(size_t{1000});
  5367. }
  5368. tpstats.RecordEffectiveSize(size_t{10});
  5369. tpstats.RecordEffectiveSize(size_t{20});
  5370. for (int i = 0; i < 6; i++) {
  5371. tpstats.RecordEffectiveSize(size_t{100});
  5372. }
  5373. ASSERT_LE(80, tpstats.GetSuggestedPrefetchSize());
  5374. ASSERT_GT(200, tpstats.GetSuggestedPrefetchSize());
  5375. }
  5376. TEST_F(BBTTailPrefetchTest, FilePrefetchBufferMinOffset) {
  5377. TailPrefetchStats tpstats;
  5378. FilePrefetchBuffer buffer(ReadaheadParams(), false /* enable */,
  5379. true /* track_min_offset */);
  5380. IOOptions opts;
  5381. buffer.TryReadFromCache(opts, nullptr /* reader */, 500 /* offset */,
  5382. 10 /* n */, nullptr /* result */,
  5383. nullptr /* status */);
  5384. buffer.TryReadFromCache(opts, nullptr /* reader */, 480 /* offset */,
  5385. 10 /* n */, nullptr /* result */,
  5386. nullptr /* status */);
  5387. buffer.TryReadFromCache(opts, nullptr /* reader */, 490 /* offset */,
  5388. 10 /* n */, nullptr /* result */,
  5389. nullptr /* status */);
  5390. ASSERT_EQ(480, buffer.min_offset_read());
  5391. }
  5392. TEST_P(BlockBasedTableTest, DataBlockHashIndex) {
  5393. const int kNumKeys = 500;
  5394. const int kKeySize = 8;
  5395. const int kValSize = 40;
  5396. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  5397. table_options.data_block_index_type =
  5398. BlockBasedTableOptions::kDataBlockBinaryAndHash;
  5399. Options options;
  5400. options.comparator = BytewiseComparator();
  5401. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  5402. TableConstructor c(options.comparator);
  5403. static Random rnd(1048);
  5404. for (int i = 0; i < kNumKeys; i++) {
  5405. // padding one "0" to mark existent keys.
  5406. std::string random_key(rnd.RandomString(kKeySize - 1) + "1");
  5407. InternalKey k(random_key, 0, kTypeValue);
  5408. c.Add(k.Encode().ToString(), rnd.RandomString(kValSize));
  5409. }
  5410. std::vector<std::string> keys;
  5411. stl_wrappers::KVMap kvmap;
  5412. const ImmutableOptions ioptions(options);
  5413. const MutableCFOptions moptions(options);
  5414. const InternalKeyComparator internal_comparator(options.comparator);
  5415. c.Finish(options, ioptions, moptions, table_options, internal_comparator,
  5416. &keys, &kvmap);
  5417. auto reader = c.GetTableReader();
  5418. std::unique_ptr<InternalIterator> seek_iter;
  5419. ReadOptions read_options;
  5420. seek_iter.reset(reader->NewIterator(
  5421. read_options, moptions.prefix_extractor.get(), /*arena=*/nullptr,
  5422. /*skip_filters=*/false, TableReaderCaller::kUncategorized));
  5423. for (int i = 0; i < 2; ++i) {
  5424. ReadOptions ro;
  5425. // for every kv, we seek using two method: Get() and Seek()
  5426. // Get() will use the SuffixIndexHash in Block. For non-existent key it
  5427. // will invalidate the iterator
  5428. // Seek() will use the default BinarySeek() in Block. So for non-existent
  5429. // key it will land at the closest key that is large than target.
  5430. // Search for existent keys
  5431. for (auto& kv : kvmap) {
  5432. if (i == 0) {
  5433. // Search using Seek()
  5434. seek_iter->Seek(kv.first);
  5435. ASSERT_OK(seek_iter->status());
  5436. ASSERT_TRUE(seek_iter->Valid());
  5437. ASSERT_EQ(seek_iter->key(), kv.first);
  5438. ASSERT_EQ(seek_iter->value(), kv.second);
  5439. } else {
  5440. // Search using Get()
  5441. PinnableSlice value;
  5442. std::string user_key = ExtractUserKey(kv.first).ToString();
  5443. GetContext get_context(options.comparator, nullptr, nullptr, nullptr,
  5444. GetContext::kNotFound, user_key, &value, nullptr,
  5445. nullptr, nullptr, true, nullptr, nullptr);
  5446. ASSERT_OK(reader->Get(ro, kv.first, &get_context,
  5447. moptions.prefix_extractor.get()));
  5448. ASSERT_EQ(get_context.State(), GetContext::kFound);
  5449. ASSERT_EQ(value, Slice(kv.second));
  5450. value.Reset();
  5451. }
  5452. }
  5453. // Search for non-existent keys
  5454. for (auto& kv : kvmap) {
  5455. std::string user_key = ExtractUserKey(kv.first).ToString();
  5456. user_key.back() = '0'; // make it non-existent key
  5457. InternalKey internal_key(user_key, 0, kTypeValue);
  5458. std::string encoded_key = internal_key.Encode().ToString();
  5459. if (i == 0) { // Search using Seek()
  5460. seek_iter->Seek(encoded_key);
  5461. ASSERT_OK(seek_iter->status());
  5462. if (seek_iter->Valid()) {
  5463. ASSERT_TRUE(BytewiseComparator()->Compare(
  5464. user_key, ExtractUserKey(seek_iter->key())) < 0);
  5465. }
  5466. } else { // Search using Get()
  5467. PinnableSlice value;
  5468. GetContext get_context(options.comparator, nullptr, nullptr, nullptr,
  5469. GetContext::kNotFound, user_key, &value, nullptr,
  5470. nullptr, nullptr, true, nullptr, nullptr);
  5471. ASSERT_OK(reader->Get(ro, encoded_key, &get_context,
  5472. moptions.prefix_extractor.get()));
  5473. ASSERT_EQ(get_context.State(), GetContext::kNotFound);
  5474. value.Reset();
  5475. }
  5476. }
  5477. }
  5478. }
  5479. // BlockBasedTableIterator should invalidate itself and return
  5480. // OutOfBound()=true immediately after Seek(), to allow LevelIterator
  5481. // filter out corresponding level.
  5482. TEST_P(BlockBasedTableTest, OutOfBoundOnSeek) {
  5483. TableConstructor c(BytewiseComparator(), true /*convert_to_internal_key*/);
  5484. c.Add("foo", "v1");
  5485. std::vector<std::string> keys;
  5486. stl_wrappers::KVMap kvmap;
  5487. Options options;
  5488. BlockBasedTableOptions table_opt(GetBlockBasedTableOptions());
  5489. options.table_factory.reset(NewBlockBasedTableFactory(table_opt));
  5490. const ImmutableOptions ioptions(options);
  5491. const MutableCFOptions moptions(options);
  5492. c.Finish(options, ioptions, moptions, table_opt,
  5493. GetPlainInternalComparator(BytewiseComparator()), &keys, &kvmap);
  5494. auto* reader = c.GetTableReader();
  5495. ReadOptions read_opt;
  5496. std::string upper_bound = "bar";
  5497. Slice upper_bound_slice(upper_bound);
  5498. read_opt.iterate_upper_bound = &upper_bound_slice;
  5499. std::unique_ptr<InternalIterator> iter;
  5500. iter.reset(new KeyConvertingIterator(reader->NewIterator(
  5501. read_opt, /*prefix_extractor=*/nullptr, /*arena=*/nullptr,
  5502. /*skip_filters=*/false, TableReaderCaller::kUncategorized)));
  5503. iter->SeekToFirst();
  5504. ASSERT_FALSE(iter->Valid());
  5505. ASSERT_OK(iter->status());
  5506. ASSERT_TRUE(iter->UpperBoundCheckResult() == IterBoundCheck::kOutOfBound);
  5507. iter.reset(new KeyConvertingIterator(reader->NewIterator(
  5508. read_opt, /*prefix_extractor=*/nullptr, /*arena=*/nullptr,
  5509. /*skip_filters=*/false, TableReaderCaller::kUncategorized)));
  5510. iter->Seek("foo");
  5511. ASSERT_FALSE(iter->Valid());
  5512. ASSERT_OK(iter->status());
  5513. ASSERT_TRUE(iter->UpperBoundCheckResult() == IterBoundCheck::kOutOfBound);
  5514. }
  5515. // BlockBasedTableIterator should invalidate itself and return
  5516. // OutOfBound()=true after Next(), if it finds current index key is no smaller
  5517. // than upper bound, unless it is pointing to the last data block.
  5518. TEST_P(BlockBasedTableTest, OutOfBoundOnNext) {
  5519. TableConstructor c(BytewiseComparator(), true /*convert_to_internal_key*/);
  5520. c.Add("bar", "v");
  5521. c.Add("foo", "v");
  5522. std::vector<std::string> keys;
  5523. stl_wrappers::KVMap kvmap;
  5524. Options options;
  5525. BlockBasedTableOptions table_opt(GetBlockBasedTableOptions());
  5526. table_opt.flush_block_policy_factory =
  5527. std::make_shared<FlushBlockEveryKeyPolicyFactory>();
  5528. options.table_factory.reset(NewBlockBasedTableFactory(table_opt));
  5529. const ImmutableOptions ioptions(options);
  5530. const MutableCFOptions moptions(options);
  5531. c.Finish(options, ioptions, moptions, table_opt,
  5532. GetPlainInternalComparator(BytewiseComparator()), &keys, &kvmap);
  5533. auto* reader = c.GetTableReader();
  5534. ReadOptions read_opt;
  5535. std::string ub1 = "bar_after";
  5536. Slice ub_slice1(ub1);
  5537. read_opt.iterate_upper_bound = &ub_slice1;
  5538. std::unique_ptr<InternalIterator> iter;
  5539. iter.reset(new KeyConvertingIterator(reader->NewIterator(
  5540. read_opt, /*prefix_extractor=*/nullptr, /*arena=*/nullptr,
  5541. /*skip_filters=*/false, TableReaderCaller::kUncategorized)));
  5542. iter->Seek("bar");
  5543. ASSERT_TRUE(iter->Valid());
  5544. ASSERT_EQ("bar", iter->key());
  5545. iter->Next();
  5546. ASSERT_FALSE(iter->Valid());
  5547. ASSERT_TRUE(iter->UpperBoundCheckResult() == IterBoundCheck::kOutOfBound);
  5548. std::string ub2 = "foo_after";
  5549. Slice ub_slice2(ub2);
  5550. read_opt.iterate_upper_bound = &ub_slice2;
  5551. iter.reset(new KeyConvertingIterator(reader->NewIterator(
  5552. read_opt, /*prefix_extractor=*/nullptr, /*arena=*/nullptr,
  5553. /*skip_filters=*/false, TableReaderCaller::kUncategorized)));
  5554. iter->Seek("foo");
  5555. ASSERT_TRUE(iter->Valid());
  5556. ASSERT_EQ("foo", iter->key());
  5557. iter->Next();
  5558. ASSERT_FALSE(iter->Valid());
  5559. ASSERT_FALSE(iter->UpperBoundCheckResult() == IterBoundCheck::kOutOfBound);
  5560. }
  5561. class ChargeCompressionDictionaryBuildingBufferTest
  5562. : public BlockBasedTableTestBase {};
  5563. TEST_F(ChargeCompressionDictionaryBuildingBufferTest, Basic) {
  5564. if (GetSupportedDictCompressions().empty()) {
  5565. ROCKSDB_GTEST_SKIP("No supported dict compression");
  5566. return;
  5567. }
  5568. const auto kCompression = GetSupportedDictCompressions()[0];
  5569. constexpr std::size_t kSizeDummyEntry = 256 * 1024;
  5570. constexpr std::size_t kMetaDataChargeOverhead = 10000;
  5571. constexpr std::size_t kCacheCapacity = 8 * 1024 * 1024;
  5572. constexpr std::size_t kMaxDictBytes = 1024;
  5573. constexpr std::size_t kMaxDictBufferBytes = 1024;
  5574. for (CacheEntryRoleOptions::Decision
  5575. charge_compression_dictionary_building_buffer :
  5576. {CacheEntryRoleOptions::Decision::kEnabled,
  5577. CacheEntryRoleOptions::Decision::kDisabled}) {
  5578. BlockBasedTableOptions table_options;
  5579. LRUCacheOptions lo;
  5580. lo.capacity = kCacheCapacity;
  5581. lo.num_shard_bits = 0; // 2^0 shard
  5582. lo.strict_capacity_limit = true;
  5583. std::shared_ptr<Cache> cache(NewLRUCache(lo));
  5584. table_options.block_cache = cache;
  5585. table_options.flush_block_policy_factory =
  5586. std::make_shared<FlushBlockEveryKeyPolicyFactory>();
  5587. table_options.cache_usage_options.options_overrides.insert(
  5588. {CacheEntryRole::kCompressionDictionaryBuildingBuffer,
  5589. {/*.charged = */ charge_compression_dictionary_building_buffer}});
  5590. Options options;
  5591. options.compression = kCompression;
  5592. options.compression_opts.max_dict_bytes = kMaxDictBytes;
  5593. options.compression_opts.max_dict_buffer_bytes = kMaxDictBufferBytes;
  5594. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  5595. test::StringSink* sink = new test::StringSink();
  5596. std::unique_ptr<FSWritableFile> holder(sink);
  5597. std::unique_ptr<WritableFileWriter> file_writer(new WritableFileWriter(
  5598. std::move(holder), "test_file_name", FileOptions()));
  5599. ImmutableOptions ioptions(options);
  5600. MutableCFOptions moptions(options);
  5601. InternalKeyComparator ikc(options.comparator);
  5602. InternalTblPropCollFactories internal_tbl_prop_coll_factories;
  5603. const ReadOptions read_options;
  5604. const WriteOptions write_options;
  5605. std::unique_ptr<TableBuilder> builder(
  5606. options.table_factory->NewTableBuilder(
  5607. TableBuilderOptions(ioptions, moptions, read_options, write_options,
  5608. ikc, &internal_tbl_prop_coll_factories,
  5609. kCompression, options.compression_opts,
  5610. kUnknownColumnFamily, "test_cf", -1 /* level */,
  5611. kUnknownNewestKeyTime),
  5612. file_writer.get()));
  5613. std::string key1 = "key1";
  5614. std::string value1 = "val1";
  5615. InternalKey ik1(key1, 0 /* sequnce number */, kTypeValue);
  5616. // Adding the first key won't trigger a flush by FlushBlockEveryKeyPolicy
  5617. // therefore won't trigger any data block's buffering
  5618. builder->Add(ik1.Encode(), value1);
  5619. ASSERT_EQ(cache->GetPinnedUsage(), 0 * kSizeDummyEntry);
  5620. std::string key2 = "key2";
  5621. std::string value2 = "val2";
  5622. InternalKey ik2(key2, 1 /* sequnce number */, kTypeValue);
  5623. // Adding the second key will trigger a flush of the last data block (the
  5624. // one containing key1 and value1) by FlushBlockEveryKeyPolicy and hence
  5625. // trigger buffering of that data block.
  5626. builder->Add(ik2.Encode(), value2);
  5627. // Cache charging will increase for last buffered data block (the one
  5628. // containing key1 and value1) since the buffer limit is not exceeded after
  5629. // that buffering and the cache will not be full after this reservation
  5630. if (charge_compression_dictionary_building_buffer ==
  5631. CacheEntryRoleOptions::Decision::kEnabled) {
  5632. EXPECT_GE(cache->GetPinnedUsage(), 1 * kSizeDummyEntry);
  5633. EXPECT_LT(cache->GetPinnedUsage(),
  5634. 1 * kSizeDummyEntry + kMetaDataChargeOverhead);
  5635. } else {
  5636. EXPECT_EQ(cache->GetPinnedUsage(), 0 * kSizeDummyEntry);
  5637. }
  5638. ASSERT_OK(builder->Finish());
  5639. EXPECT_EQ(cache->GetPinnedUsage(), 0 * kSizeDummyEntry);
  5640. }
  5641. }
  5642. TEST_F(ChargeCompressionDictionaryBuildingBufferTest,
  5643. BasicWithBufferLimitExceed) {
  5644. if (GetSupportedDictCompressions().empty()) {
  5645. ROCKSDB_GTEST_SKIP("No supported dict compression");
  5646. return;
  5647. }
  5648. const auto kCompression = GetSupportedDictCompressions()[0];
  5649. constexpr std::size_t kSizeDummyEntry = 256 * 1024;
  5650. constexpr std::size_t kMetaDataChargeOverhead = 10000;
  5651. constexpr std::size_t kCacheCapacity = 8 * 1024 * 1024;
  5652. constexpr std::size_t kMaxDictBytes = 1024;
  5653. constexpr std::size_t kMaxDictBufferBytes = 2 * kSizeDummyEntry;
  5654. // `CacheEntryRoleOptions::charged` is enabled by default for
  5655. // CacheEntryRole::kCompressionDictionaryBuildingBuffer
  5656. BlockBasedTableOptions table_options;
  5657. LRUCacheOptions lo;
  5658. lo.capacity = kCacheCapacity;
  5659. lo.num_shard_bits = 0; // 2^0 shard
  5660. lo.strict_capacity_limit = true;
  5661. std::shared_ptr<Cache> cache(NewLRUCache(lo));
  5662. table_options.block_cache = cache;
  5663. table_options.flush_block_policy_factory =
  5664. std::make_shared<FlushBlockEveryKeyPolicyFactory>();
  5665. Options options;
  5666. options.compression = kCompression;
  5667. options.compression_opts.max_dict_bytes = kMaxDictBytes;
  5668. options.compression_opts.max_dict_buffer_bytes = kMaxDictBufferBytes;
  5669. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  5670. test::StringSink* sink = new test::StringSink();
  5671. std::unique_ptr<FSWritableFile> holder(sink);
  5672. std::unique_ptr<WritableFileWriter> file_writer(new WritableFileWriter(
  5673. std::move(holder), "test_file_name", FileOptions()));
  5674. ImmutableOptions ioptions(options);
  5675. MutableCFOptions moptions(options);
  5676. InternalKeyComparator ikc(options.comparator);
  5677. InternalTblPropCollFactories internal_tbl_prop_coll_factories;
  5678. const ReadOptions read_options;
  5679. const WriteOptions write_options;
  5680. std::unique_ptr<TableBuilder> builder(options.table_factory->NewTableBuilder(
  5681. TableBuilderOptions(ioptions, moptions, read_options, write_options, ikc,
  5682. &internal_tbl_prop_coll_factories, kCompression,
  5683. options.compression_opts, kUnknownColumnFamily,
  5684. "test_cf", -1 /* level */, kUnknownNewestKeyTime),
  5685. file_writer.get()));
  5686. std::string key1 = "key1";
  5687. std::string value1(kSizeDummyEntry, '0');
  5688. InternalKey ik1(key1, 0 /* sequnce number */, kTypeValue);
  5689. // Adding the first key won't trigger a flush by FlushBlockEveryKeyPolicy
  5690. // therefore won't trigger any data block's buffering
  5691. builder->Add(ik1.Encode(), value1);
  5692. ASSERT_EQ(cache->GetPinnedUsage(), 0 * kSizeDummyEntry);
  5693. std::string key2 = "key2";
  5694. std::string value2(kSizeDummyEntry, '0');
  5695. InternalKey ik2(key2, 1 /* sequnce number */, kTypeValue);
  5696. // Adding the second key will trigger a flush of the last data block (the one
  5697. // containing key1 and value1) by FlushBlockEveryKeyPolicy and hence trigger
  5698. // buffering of the last data block.
  5699. builder->Add(ik2.Encode(), value2);
  5700. // Cache charging will increase for last buffered data block (the one
  5701. // containing key1 and value1) since the buffer limit is not exceeded after
  5702. // the buffering and the cache will not be full after this reservation
  5703. EXPECT_GE(cache->GetPinnedUsage(), 2 * kSizeDummyEntry);
  5704. EXPECT_LT(cache->GetPinnedUsage(),
  5705. 2 * kSizeDummyEntry + kMetaDataChargeOverhead);
  5706. std::string key3 = "key3";
  5707. std::string value3 = "val3";
  5708. InternalKey ik3(key3, 2 /* sequnce number */, kTypeValue);
  5709. // Adding the third key will trigger a flush of the last data block (the one
  5710. // containing key2 and value2) by FlushBlockEveryKeyPolicy and hence trigger
  5711. // buffering of the last data block.
  5712. builder->Add(ik3.Encode(), value3);
  5713. // Cache charging will decrease since the buffer limit is now exceeded
  5714. // after the last buffering and EnterUnbuffered() is triggered
  5715. EXPECT_EQ(cache->GetPinnedUsage(), 0 * kSizeDummyEntry);
  5716. ASSERT_OK(builder->Finish());
  5717. EXPECT_EQ(cache->GetPinnedUsage(), 0 * kSizeDummyEntry);
  5718. }
  5719. TEST_F(ChargeCompressionDictionaryBuildingBufferTest, BasicWithCacheFull) {
  5720. if (GetSupportedDictCompressions().empty()) {
  5721. ROCKSDB_GTEST_SKIP("No supported dict compression");
  5722. return;
  5723. }
  5724. const auto kCompression = GetSupportedDictCompressions()[0];
  5725. constexpr std::size_t kSizeDummyEntry = 256 * 1024;
  5726. constexpr std::size_t kMetaDataChargeOverhead = 10000;
  5727. // A small kCacheCapacity is chosen so that increase cache charging for
  5728. // buffering two data blocks, each containing key1/value1, key2/a big
  5729. // value2, will cause cache full
  5730. constexpr std::size_t kCacheCapacity =
  5731. 1 * kSizeDummyEntry + kSizeDummyEntry / 2;
  5732. constexpr std::size_t kMaxDictBytes = 1024;
  5733. // A big kMaxDictBufferBytes is chosen so that adding a big key value pair
  5734. // (key2, value2) won't exceed the buffer limit
  5735. constexpr std::size_t kMaxDictBufferBytes = 1024 * 1024 * 1024;
  5736. // `CacheEntryRoleOptions::charged` is enabled by default for
  5737. // CacheEntryRole::kCompressionDictionaryBuildingBuffer
  5738. BlockBasedTableOptions table_options;
  5739. LRUCacheOptions lo;
  5740. lo.capacity = kCacheCapacity;
  5741. lo.num_shard_bits = 0; // 2^0 shard
  5742. lo.strict_capacity_limit = true;
  5743. std::shared_ptr<Cache> cache(NewLRUCache(lo));
  5744. table_options.block_cache = cache;
  5745. table_options.flush_block_policy_factory =
  5746. std::make_shared<FlushBlockEveryKeyPolicyFactory>();
  5747. Options options;
  5748. options.compression = kCompression;
  5749. options.compression_opts.max_dict_bytes = kMaxDictBytes;
  5750. options.compression_opts.max_dict_buffer_bytes = kMaxDictBufferBytes;
  5751. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  5752. test::StringSink* sink = new test::StringSink();
  5753. std::unique_ptr<FSWritableFile> holder(sink);
  5754. std::unique_ptr<WritableFileWriter> file_writer(new WritableFileWriter(
  5755. std::move(holder), "test_file_name", FileOptions()));
  5756. ImmutableOptions ioptions(options);
  5757. MutableCFOptions moptions(options);
  5758. InternalKeyComparator ikc(options.comparator);
  5759. InternalTblPropCollFactories internal_tbl_prop_coll_factories;
  5760. const ReadOptions read_options;
  5761. const WriteOptions write_options;
  5762. std::unique_ptr<TableBuilder> builder(options.table_factory->NewTableBuilder(
  5763. TableBuilderOptions(ioptions, moptions, read_options, write_options, ikc,
  5764. &internal_tbl_prop_coll_factories, kCompression,
  5765. options.compression_opts, kUnknownColumnFamily,
  5766. "test_cf", -1 /* level */, kUnknownNewestKeyTime),
  5767. file_writer.get()));
  5768. std::string key1 = "key1";
  5769. std::string value1 = "val1";
  5770. InternalKey ik1(key1, 0 /* sequnce number */, kTypeValue);
  5771. // Adding the first key won't trigger a flush by FlushBlockEveryKeyPolicy
  5772. // therefore won't trigger any data block's buffering
  5773. builder->Add(ik1.Encode(), value1);
  5774. ASSERT_EQ(cache->GetPinnedUsage(), 0 * kSizeDummyEntry);
  5775. std::string key2 = "key2";
  5776. std::string value2(kSizeDummyEntry, '0');
  5777. InternalKey ik2(key2, 1 /* sequnce number */, kTypeValue);
  5778. // Adding the second key will trigger a flush of the last data block (the one
  5779. // containing key1 and value1) by FlushBlockEveryKeyPolicy and hence trigger
  5780. // buffering of the last data block.
  5781. builder->Add(ik2.Encode(), value2);
  5782. // Cache charging will increase for the last buffered data block (the one
  5783. // containing key1 and value1) since the buffer limit is not exceeded after
  5784. // the buffering and the cache will not be full after this reservation
  5785. EXPECT_GE(cache->GetPinnedUsage(), 1 * kSizeDummyEntry);
  5786. EXPECT_LT(cache->GetPinnedUsage(),
  5787. 1 * kSizeDummyEntry + kMetaDataChargeOverhead);
  5788. std::string key3 = "key3";
  5789. std::string value3 = "value3";
  5790. InternalKey ik3(key3, 2 /* sequnce number */, kTypeValue);
  5791. // Adding the third key will trigger a flush of the last data block (the one
  5792. // containing key2 and value2) by FlushBlockEveryKeyPolicy and hence trigger
  5793. // buffering of the last data block.
  5794. builder->Add(ik3.Encode(), value3);
  5795. // Cache charging will decrease since the cache is now full after
  5796. // increasing reservation for the last buffered block and EnterUnbuffered() is
  5797. // triggered
  5798. EXPECT_EQ(cache->GetPinnedUsage(), 0 * kSizeDummyEntry);
  5799. ASSERT_OK(builder->Finish());
  5800. EXPECT_EQ(cache->GetPinnedUsage(), 0 * kSizeDummyEntry);
  5801. }
  5802. class CacheUsageOptionsOverridesTest : public DBTestBase {
  5803. public:
  5804. CacheUsageOptionsOverridesTest()
  5805. : DBTestBase("cache_usage_options_overrides_test",
  5806. /*env_do_fsync=*/false) {}
  5807. };
  5808. TEST_F(CacheUsageOptionsOverridesTest, SanitizeAndValidateOptions) {
  5809. // To test `cache_usage_options.options_overrides` is sanitized
  5810. // where `cache_usage_options.options` is used when there is no entry in
  5811. // `cache_usage_options.options_overrides`
  5812. Options options;
  5813. options.create_if_missing = true;
  5814. BlockBasedTableOptions table_options = BlockBasedTableOptions();
  5815. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  5816. Destroy(options);
  5817. Status s = TryReopen(options);
  5818. EXPECT_TRUE(s.ok());
  5819. const auto* sanitized_table_options =
  5820. options.table_factory->GetOptions<BlockBasedTableOptions>();
  5821. const auto sanitized_options_overrides =
  5822. sanitized_table_options->cache_usage_options.options_overrides;
  5823. EXPECT_EQ(sanitized_options_overrides.size(), kNumCacheEntryRoles);
  5824. for (auto options_overrides_iter = sanitized_options_overrides.cbegin();
  5825. options_overrides_iter != sanitized_options_overrides.cend();
  5826. ++options_overrides_iter) {
  5827. CacheEntryRoleOptions role_options = options_overrides_iter->second;
  5828. CacheEntryRoleOptions default_options =
  5829. sanitized_table_options->cache_usage_options.options;
  5830. EXPECT_TRUE(role_options == default_options);
  5831. }
  5832. Destroy(options);
  5833. // To test option validation on unsupported CacheEntryRole
  5834. table_options = BlockBasedTableOptions();
  5835. table_options.cache_usage_options.options_overrides.insert(
  5836. {CacheEntryRole::kDataBlock,
  5837. {/*.charged = */ CacheEntryRoleOptions::Decision::kDisabled}});
  5838. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  5839. Destroy(options);
  5840. s = TryReopen(options);
  5841. EXPECT_TRUE(s.IsNotSupported());
  5842. EXPECT_TRUE(
  5843. s.ToString().find("Enable/Disable CacheEntryRoleOptions::charged") !=
  5844. std::string::npos);
  5845. EXPECT_TRUE(
  5846. s.ToString().find(kCacheEntryRoleToCamelString[static_cast<uint32_t>(
  5847. CacheEntryRole::kDataBlock)]) != std::string::npos);
  5848. Destroy(options);
  5849. // To test option validation on existence of block cache
  5850. table_options = BlockBasedTableOptions();
  5851. table_options.no_block_cache = true;
  5852. table_options.cache_usage_options.options_overrides.insert(
  5853. {CacheEntryRole::kFilterConstruction,
  5854. {/*.charged = */ CacheEntryRoleOptions::Decision::kEnabled}});
  5855. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  5856. Destroy(options);
  5857. s = TryReopen(options);
  5858. EXPECT_TRUE(s.IsInvalidArgument());
  5859. EXPECT_TRUE(s.ToString().find("Enable CacheEntryRoleOptions::charged") !=
  5860. std::string::npos);
  5861. EXPECT_TRUE(
  5862. s.ToString().find(kCacheEntryRoleToCamelString[static_cast<std::size_t>(
  5863. CacheEntryRole::kFilterConstruction)]) != std::string::npos);
  5864. EXPECT_TRUE(s.ToString().find("block cache is disabled") !=
  5865. std::string::npos);
  5866. Destroy(options);
  5867. }
  5868. class ExternalTableTest : public DBTestBase {
  5869. public:
  5870. ExternalTableTest()
  5871. : DBTestBase("external_table_test", /*env_do_fsync=*/false) {}
  5872. protected:
  5873. class DummyExternalTableFile {
  5874. public:
  5875. explicit DummyExternalTableFile(const std::string& file_path,
  5876. FSWritableFile* file)
  5877. : file_path_(file_path), file_(file), file_size_(0) {
  5878. props_.comparator_name = BytewiseComparator()->Name();
  5879. }
  5880. Status Serialize(
  5881. const std::vector<std::pair<std::string, std::string>>& kv_vec) {
  5882. // First append the property block if one exists
  5883. uint32_t prop_block_size = static_cast<uint32_t>(prop_block_.length());
  5884. buf_.append(static_cast<char*>(static_cast<void*>(&prop_block_size)),
  5885. sizeof(prop_block_size));
  5886. if (!prop_block_.empty()) {
  5887. buf_.append(prop_block_);
  5888. }
  5889. for (auto& kv : kv_vec) {
  5890. SerializeOne(kv.first, kv.second);
  5891. props_.raw_key_size += kv.first.length();
  5892. props_.raw_value_size += kv.second.length();
  5893. }
  5894. props_.num_entries = kv_vec.size();
  5895. file_size_ = buf_.length();
  5896. if (file_) {
  5897. return file_->Append(buf_, IOOptions(), /*dbg=*/nullptr);
  5898. } else {
  5899. return WriteStringToFile(Env::Default(), buf_, file_path_);
  5900. }
  5901. }
  5902. Status Deserialize(std::map<std::string, std::string>& kv_map) {
  5903. Status s = ReadFileToString(Env::Default(), file_path_, &buf_);
  5904. if (!s.ok()) {
  5905. return s;
  5906. }
  5907. uint32_t prop_block_size = 0;
  5908. buf_.copy(static_cast<char*>(static_cast<void*>(&prop_block_size)),
  5909. sizeof(prop_block_size));
  5910. buf_.erase(0, sizeof(prop_block_size));
  5911. prop_block_.assign(buf_.substr(0, prop_block_size));
  5912. buf_.erase(0, prop_block_size);
  5913. while (buf_.length() > 0) {
  5914. std::pair<std::string, std::string> kv;
  5915. s = DeserializeOne(kv);
  5916. if (!s.ok()) {
  5917. break;
  5918. }
  5919. size_t key_size = kv.first.length();
  5920. size_t value_size = kv.second.length();
  5921. kv_map.emplace(std::move(kv));
  5922. props_.raw_key_size += key_size;
  5923. props_.raw_value_size += value_size;
  5924. }
  5925. props_.num_entries = kv_map.size();
  5926. return s;
  5927. }
  5928. Status PutPropertiesBlock(const Slice& prop_block) {
  5929. prop_block_.assign(prop_block.data(), prop_block.size());
  5930. return Status::OK();
  5931. }
  5932. Status GetPropertiesBlock(std::unique_ptr<char[]>* block, uint64_t* size,
  5933. uint64_t* file_offset) {
  5934. if (!prop_block_.empty()) {
  5935. *block = std::make_unique<char[]>(prop_block_.length());
  5936. memcpy(block->get(), prop_block_.data(), prop_block_.length());
  5937. *size = prop_block_.length();
  5938. *file_offset = sizeof(uint32_t);
  5939. } else {
  5940. *size = 0;
  5941. }
  5942. return Status::OK();
  5943. }
  5944. TableProperties GetTableProperties() const { return props_; }
  5945. uint64_t FileSize() const { return file_size_; }
  5946. private:
  5947. struct ItemHeader {
  5948. uint32_t key_size;
  5949. uint32_t value_size;
  5950. };
  5951. void SerializeOne(const Slice& key, const Slice& value) {
  5952. ItemHeader hdr;
  5953. hdr.key_size = static_cast<uint32_t>(key.size());
  5954. hdr.value_size = static_cast<uint32_t>(value.size());
  5955. buf_.append(static_cast<char*>(static_cast<void*>(&hdr)), sizeof(hdr));
  5956. buf_.append(key.data(), key.size());
  5957. buf_.append(value.data(), value.size());
  5958. }
  5959. Status DeserializeOne(std::pair<std::string, std::string>& kv) {
  5960. ItemHeader hdr;
  5961. size_t copied =
  5962. buf_.copy(static_cast<char*>(static_cast<void*>(&hdr)), sizeof(hdr));
  5963. if (copied < sizeof(hdr)) {
  5964. return Status::Corruption();
  5965. }
  5966. buf_.erase(0, sizeof(hdr));
  5967. if (buf_.length() < hdr.key_size + hdr.value_size) {
  5968. return Status::Corruption();
  5969. }
  5970. kv.first.assign(std::string_view(buf_.data(), hdr.key_size));
  5971. buf_.erase(0, hdr.key_size);
  5972. kv.second.assign(std::string_view(buf_.data(), hdr.value_size));
  5973. buf_.erase(0, hdr.value_size);
  5974. return Status::OK();
  5975. }
  5976. std::string file_path_;
  5977. FSWritableFile* file_;
  5978. std::string buf_;
  5979. TableProperties props_;
  5980. uint64_t file_size_;
  5981. std::string prop_block_;
  5982. };
  5983. class DummyExternalTableIterator : public ExternalTableIterator {
  5984. public:
  5985. explicit DummyExternalTableIterator(
  5986. const ReadOptions& /*ro*/,
  5987. const std::map<std::string, std::string>& kv_map)
  5988. : scan_options_(nullptr),
  5989. num_opts_(0),
  5990. scan_idx_(0),
  5991. kv_map_(kv_map),
  5992. valid_(false) {
  5993. TEST_SYNC_POINT_CALLBACK("DummyExternalTableIterator::Constructor",
  5994. &status_);
  5995. }
  5996. bool Valid() const override { return valid_; }
  5997. void SeekToFirst() override {
  5998. if (scan_options_) {
  5999. status_ = Status::InvalidArgument();
  6000. } else {
  6001. iter_ = kv_map_.begin();
  6002. valid_ = iter_ != kv_map_.end();
  6003. status_ = Status::OK();
  6004. }
  6005. }
  6006. void SeekToLast() override {
  6007. if (scan_options_) {
  6008. status_ = Status::InvalidArgument();
  6009. } else {
  6010. if (!kv_map_.empty()) {
  6011. iter_ = kv_map_.begin();
  6012. for (uint64_t i = 0; i < kv_map_.size() - 1; ++i) {
  6013. iter_++;
  6014. }
  6015. valid_ = true;
  6016. } else {
  6017. valid_ = false;
  6018. }
  6019. status_ = Status::OK();
  6020. }
  6021. }
  6022. void Seek(const Slice& target) override {
  6023. if (status_.ok()) {
  6024. iter_ = kv_map_.find(target.ToString());
  6025. valid_ = iter_ != kv_map_.end();
  6026. eof_ = iter_ == kv_map_.end();
  6027. }
  6028. if (scan_options_) {
  6029. if (scan_idx_ >= num_opts_ ||
  6030. target != scan_options_[scan_idx_].range.start.value().ToString()) {
  6031. status_ = Status::InvalidArgument();
  6032. } else {
  6033. if (valid_ && scan_options_[scan_idx_].range.limit.has_value() &&
  6034. iter_->first.compare(
  6035. scan_options_[scan_idx_].range.limit.value().ToString()) >=
  6036. 0) {
  6037. valid_ = false;
  6038. }
  6039. scan_idx_++;
  6040. }
  6041. }
  6042. }
  6043. void SeekForPrev(const Slice& /*target*/) override {
  6044. valid_ = false;
  6045. status_ = Status::NotSupported();
  6046. }
  6047. void Next() override {
  6048. iter_++;
  6049. valid_ = iter_ != kv_map_.end();
  6050. eof_ = iter_ == kv_map_.end();
  6051. if (valid_ && scan_options_ &&
  6052. scan_options_[scan_idx_ - 1].range.limit.has_value() &&
  6053. iter_->first.compare(
  6054. scan_options_[scan_idx_ - 1].range.limit.value().ToString()) >=
  6055. 0) {
  6056. valid_ = false;
  6057. }
  6058. // status_ is still ok. !valid_ indicates end of scan
  6059. }
  6060. bool NextAndGetResult(IterateResult* result) override {
  6061. Next();
  6062. if (valid_) {
  6063. result->key = key();
  6064. result->bound_check_result = IterBoundCheck::kInbound;
  6065. result->value_prepared = true;
  6066. } else {
  6067. result->key = Slice();
  6068. result->bound_check_result =
  6069. eof_ ? IterBoundCheck::kUnknown : IterBoundCheck::kOutOfBound;
  6070. result->value_prepared = false;
  6071. }
  6072. return valid_;
  6073. }
  6074. bool PrepareValue() override { return valid_ ? true : false; }
  6075. IterBoundCheck UpperBoundCheckResult() override {
  6076. return eof_ ? IterBoundCheck::kUnknown : IterBoundCheck::kOutOfBound;
  6077. }
  6078. void Prev() override {
  6079. valid_ = false;
  6080. status_ = Status::NotSupported();
  6081. }
  6082. Slice key() const override {
  6083. // If valid_ is false or status_ is non-ok, behavior is indeterminate
  6084. return Slice(iter_->first);
  6085. }
  6086. Status status() const override {
  6087. // status_ gets overwritten by next Seek
  6088. return status_;
  6089. }
  6090. Slice value() const override {
  6091. // If valid_ is false or status_ is non-ok, behavior is indeterminate
  6092. return Slice(iter_->second);
  6093. }
  6094. void Prepare(const ScanOptions scan_opts[], size_t num_opts) override {
  6095. scan_options_ = scan_opts;
  6096. num_opts_ = num_opts;
  6097. }
  6098. private:
  6099. const ScanOptions* scan_options_;
  6100. size_t num_opts_;
  6101. size_t scan_idx_;
  6102. std::map<std::string, std::string> kv_map_;
  6103. bool valid_ = false;
  6104. bool eof_ = false;
  6105. Status status_ = Status::OK();
  6106. std::map<std::string, std::string>::iterator iter_;
  6107. };
  6108. class DummyExternalTableReader : public ExternalTableReader {
  6109. public:
  6110. explicit DummyExternalTableReader(const std::string& file_path,
  6111. bool support_property_block)
  6112. : file_(file_path, /*file=*/nullptr),
  6113. support_property_block_(support_property_block) {
  6114. Status s = file_.Deserialize(kv_map_);
  6115. EXPECT_OK(s);
  6116. }
  6117. ExternalTableIterator* NewIterator(
  6118. const ReadOptions& read_options,
  6119. const SliceTransform* /*prefix_extractor*/) override {
  6120. return new DummyExternalTableIterator(read_options, kv_map_);
  6121. }
  6122. Status Get(const ReadOptions& /*read_options*/, const Slice& key,
  6123. const SliceTransform* /*prefix_extractor*/,
  6124. std::string* value) override {
  6125. auto iter = kv_map_.find(key.ToString());
  6126. if (iter != kv_map_.end()) {
  6127. value->assign(iter->second);
  6128. return Status::OK();
  6129. }
  6130. return Status::NotFound();
  6131. }
  6132. void MultiGet(const ReadOptions& read_options,
  6133. const std::vector<Slice>& keys,
  6134. const SliceTransform* prefix_extractor,
  6135. std::vector<std::string>* values,
  6136. std::vector<Status>* statuses) override {
  6137. values->resize(keys.size());
  6138. statuses->resize(keys.size());
  6139. for (size_t i = 0; i < keys.size(); ++i) {
  6140. statuses->at(i) =
  6141. Get(read_options, keys[i], prefix_extractor, &values->at(i));
  6142. }
  6143. }
  6144. Status GetPropertiesBlock(std::unique_ptr<char[]>* block, uint64_t* size,
  6145. uint64_t* file_offset) override {
  6146. if (!support_property_block_) {
  6147. return Status::NotSupported();
  6148. }
  6149. return file_.GetPropertiesBlock(block, size, file_offset);
  6150. }
  6151. std::shared_ptr<const TableProperties> GetTableProperties() const override {
  6152. std::shared_ptr<TableProperties> props =
  6153. std::make_shared<TableProperties>();
  6154. props->comparator_name.assign(BytewiseComparator()->Name());
  6155. props->num_entries = 1;
  6156. props->raw_key_size = 3;
  6157. props->raw_value_size = 3;
  6158. return props;
  6159. }
  6160. private:
  6161. std::map<std::string, std::string> kv_map_;
  6162. DummyExternalTableFile file_;
  6163. bool support_property_block_;
  6164. };
  6165. class DummyExternalTableBuilder : public ExternalTableBuilder {
  6166. public:
  6167. explicit DummyExternalTableBuilder(const std::string& file_path,
  6168. FSWritableFile* file,
  6169. bool support_property_block)
  6170. : file_(file_path, file),
  6171. support_property_block_(support_property_block) {}
  6172. void Add(const Slice& key, const Slice& value) override {
  6173. if (!kv_vec_.empty()) {
  6174. ASSERT_LT(BytewiseComparator()->Compare(kv_vec_.back().first, key), 0);
  6175. }
  6176. kv_vec_.emplace_back(key.ToString(), value.ToString());
  6177. }
  6178. Status Finish() override {
  6179. status_ = file_.Serialize(kv_vec_);
  6180. return status_;
  6181. }
  6182. void Abandon() override { kv_vec_.clear(); }
  6183. uint64_t FileSize() const override { return file_.FileSize(); }
  6184. Status PutPropertiesBlock(const Slice& block) override {
  6185. if (!support_property_block_) {
  6186. return Status::NotSupported();
  6187. }
  6188. return file_.PutPropertiesBlock(block);
  6189. }
  6190. TableProperties GetTableProperties() const override {
  6191. return file_.GetTableProperties();
  6192. }
  6193. Status status() const override { return status_; }
  6194. private:
  6195. std::vector<std::pair<std::string, std::string>> kv_vec_;
  6196. DummyExternalTableFile file_;
  6197. Status status_;
  6198. bool support_property_block_;
  6199. };
  6200. class DummyExternalTableFactory : public ExternalTableFactory {
  6201. public:
  6202. explicit DummyExternalTableFactory(bool support_property_block)
  6203. : support_property_block_(support_property_block) {}
  6204. const char* Name() const override { return "DummyExternalTableFactory"; }
  6205. Status NewTableReader(
  6206. const ReadOptions& /*read_options*/, const std::string& file_path,
  6207. const ExternalTableOptions& topts,
  6208. std::unique_ptr<ExternalTableReader>* table_reader) const override {
  6209. // Sanity check some options
  6210. EXPECT_EQ(topts.file_options.handoff_checksum_type,
  6211. ChecksumType::kCRC32c);
  6212. table_reader->reset(
  6213. new DummyExternalTableReader(file_path, support_property_block_));
  6214. return Status::OK();
  6215. }
  6216. ExternalTableBuilder* NewTableBuilder(
  6217. const ExternalTableBuilderOptions& /*opts*/,
  6218. const std::string& file_path, FSWritableFile* file) const override {
  6219. return new DummyExternalTableBuilder(file_path, file,
  6220. support_property_block_);
  6221. }
  6222. private:
  6223. bool support_property_block_;
  6224. };
  6225. };
  6226. TEST_F(ExternalTableTest, BasicTest) {
  6227. std::shared_ptr<ExternalTableFactory> factory =
  6228. std::make_shared<DummyExternalTableFactory>(
  6229. /*support_property_block=*/false);
  6230. std::string file_path = test::PerThreadDBPath("external_table");
  6231. {
  6232. std::unique_ptr<ExternalTableBuilder> builder;
  6233. builder.reset(factory->NewTableBuilder(
  6234. ExternalTableBuilderOptions(ReadOptions(), WriteOptions(),
  6235. std::shared_ptr<const SliceTransform>(),
  6236. BytewiseComparator(), "default",
  6237. TableFileCreationReason::kMisc),
  6238. file_path, /*file=*/nullptr));
  6239. builder->Add("foo", "bar");
  6240. ASSERT_OK(builder->Finish());
  6241. }
  6242. std::unique_ptr<ExternalTableReader> reader;
  6243. std::shared_ptr<SliceTransform> prefix_extractor;
  6244. ASSERT_OK(factory->NewTableReader(
  6245. {}, file_path,
  6246. ExternalTableOptions(prefix_extractor, /*comparator=*/nullptr,
  6247. /*fs=*/nullptr, FileOptions()),
  6248. &reader));
  6249. ReadOptions ro;
  6250. std::unique_ptr<ExternalTableIterator> iter(reader->NewIterator(ro, nullptr));
  6251. ASSERT_NE(iter, nullptr);
  6252. iter->Seek("foo");
  6253. ASSERT_TRUE(iter->Valid() && iter->status().ok());
  6254. ASSERT_EQ(iter->value(), "bar");
  6255. iter->Next();
  6256. ASSERT_FALSE(iter->Valid());
  6257. std::string val;
  6258. ASSERT_OK(reader->Get({}, "foo", nullptr, &val));
  6259. ASSERT_EQ(val, "bar");
  6260. std::vector<std::string> vals;
  6261. std::vector<Status> statuses;
  6262. reader->MultiGet({}, {"foo", "bar"}, nullptr, &vals, &statuses);
  6263. ASSERT_EQ(vals.size(), 2);
  6264. ASSERT_EQ(statuses.size(), 2);
  6265. ASSERT_EQ(vals[0], "bar");
  6266. ASSERT_EQ(statuses[0], Status::OK());
  6267. ASSERT_EQ(statuses[1], Status::NotFound());
  6268. }
  6269. TEST_F(ExternalTableTest, SstReaderTest) {
  6270. if (encrypted_env_) {
  6271. ROCKSDB_GTEST_SKIP("Test requires non-encrypted environment");
  6272. return;
  6273. }
  6274. Options options = GetDefaultOptions();
  6275. std::string dbname = test::PerThreadDBPath("external_table_test");
  6276. std::string ingest_file = dbname + "test.immutabledb";
  6277. dbname += "_db";
  6278. std::shared_ptr<ExternalTableFactory> factory =
  6279. std::make_shared<DummyExternalTableFactory>(
  6280. /*support_property_block=*/false);
  6281. options.table_factory = NewExternalTableFactory(factory);
  6282. std::unique_ptr<SstFileWriter> writer;
  6283. writer.reset(new SstFileWriter(EnvOptions(), options));
  6284. ASSERT_OK(writer->Open(ingest_file));
  6285. ASSERT_OK(writer->Put("foo", "bar"));
  6286. ASSERT_OK(writer->Finish());
  6287. writer.reset();
  6288. std::unique_ptr<SstFileReader> reader(new SstFileReader(options));
  6289. ASSERT_OK(reader->Open(ingest_file));
  6290. ReadOptions ro;
  6291. std::unique_ptr<Iterator> iter(reader->NewIterator(ro));
  6292. ASSERT_NE(iter, nullptr);
  6293. iter->Seek("foo");
  6294. ASSERT_TRUE(iter->Valid() && iter->status().ok());
  6295. ASSERT_EQ(iter->value(), "bar");
  6296. iter->Next();
  6297. ASSERT_FALSE(iter->Valid());
  6298. ASSERT_TRUE(iter->status().ok());
  6299. }
  6300. TEST_F(ExternalTableTest, ExternalFileChecksumTest) {
  6301. if (encrypted_env_) {
  6302. ROCKSDB_GTEST_SKIP("Test requires non-encrypted environment");
  6303. return;
  6304. }
  6305. Options options = GetDefaultOptions();
  6306. std::string dbname = test::PerThreadDBPath("external_table_test");
  6307. std::string ingest_file = dbname + "test.immutable";
  6308. dbname += "_db";
  6309. ASSERT_OK(DestroyDB(dbname, options));
  6310. std::shared_ptr<ExternalTableFactory> factory =
  6311. std::make_shared<DummyExternalTableFactory>(
  6312. /*support_property_block=*/true);
  6313. options.table_factory = NewExternalTableFactory(factory);
  6314. // Create a file
  6315. options.file_checksum_gen_factory = GetFileChecksumGenCrc32cFactory();
  6316. std::unique_ptr<SstFileWriter> writer;
  6317. writer.reset(new SstFileWriter(EnvOptions(), options));
  6318. ASSERT_OK(writer->Open(ingest_file));
  6319. ASSERT_OK(writer->Put("foo", "bar"));
  6320. ASSERT_OK(writer->Put("foo2", "bar2"));
  6321. ExternalSstFileInfo info;
  6322. ASSERT_OK(writer->Finish(&info));
  6323. writer.reset();
  6324. FileChecksumGenContext cksum_ctx;
  6325. FileChecksumGenCrc32c cksum_gen(cksum_ctx);
  6326. std::string file_data;
  6327. ASSERT_OK(ReadFileToString(options.env, ingest_file, &file_data));
  6328. cksum_gen.Update(file_data.data(), file_data.size());
  6329. cksum_gen.Finalize();
  6330. ASSERT_EQ(info.file_checksum, cksum_gen.GetChecksum());
  6331. }
  6332. TEST_F(ExternalTableTest, DBIterTest) {
  6333. if (encrypted_env_) {
  6334. ROCKSDB_GTEST_SKIP("Test requires non-encrypted environment");
  6335. return;
  6336. }
  6337. Options options = GetDefaultOptions();
  6338. std::string dbname = test::PerThreadDBPath("external_table_test");
  6339. std::string ingest_file = dbname + "test.immutable";
  6340. dbname += "_db";
  6341. ASSERT_OK(DestroyDB(dbname, options));
  6342. std::shared_ptr<ExternalTableFactory> factory =
  6343. std::make_shared<DummyExternalTableFactory>(
  6344. /*support_property_block=*/true);
  6345. options.table_factory = NewExternalTableFactory(factory);
  6346. // Create a file
  6347. std::unique_ptr<SstFileWriter> writer;
  6348. writer.reset(new SstFileWriter(EnvOptions(), options));
  6349. ASSERT_OK(writer->Open(ingest_file));
  6350. ASSERT_OK(writer->Put("foo", "bar"));
  6351. ASSERT_OK(writer->Put("foo2", "bar2"));
  6352. ASSERT_OK(writer->Finish());
  6353. writer.reset();
  6354. std::unique_ptr<DB> db;
  6355. options.create_if_missing = true;
  6356. Status s = DB::Open(options, dbname, &db);
  6357. ASSERT_OK(s);
  6358. ASSERT_TRUE(db != nullptr);
  6359. ColumnFamilyHandle* cfh = nullptr;
  6360. ASSERT_OK(db->CreateColumnFamily(options, "new_cf", &cfh));
  6361. IngestExternalFileOptions ifo;
  6362. ifo.allow_db_generated_files = true;
  6363. ifo.fill_cache = false;
  6364. s = db->IngestExternalFile(cfh, {ingest_file}, ifo);
  6365. ASSERT_OK(s);
  6366. std::unique_ptr<Iterator> iter(db->NewIterator({}, cfh));
  6367. ASSERT_NE(iter, nullptr);
  6368. iter->Seek("foo");
  6369. ASSERT_TRUE(iter->Valid() && iter->status().ok());
  6370. ASSERT_EQ(iter->value(), "bar");
  6371. iter->Next();
  6372. ASSERT_TRUE(iter->Valid() && iter->status().ok());
  6373. ASSERT_EQ(iter->key(), "foo2");
  6374. ASSERT_EQ(iter->value(), "bar2");
  6375. iter->Next();
  6376. ASSERT_FALSE(iter->Valid());
  6377. ASSERT_OK(iter->status());
  6378. iter.reset();
  6379. ASSERT_OK(db->DestroyColumnFamilyHandle(cfh));
  6380. ASSERT_OK(db->Close());
  6381. }
  6382. TEST_F(ExternalTableTest, DBMultiScanTest) {
  6383. if (encrypted_env_) {
  6384. ROCKSDB_GTEST_SKIP("Test requires non-encrypted environment");
  6385. return;
  6386. }
  6387. Options options = GetDefaultOptions();
  6388. std::string dbname = test::PerThreadDBPath("external_table_test");
  6389. std::string ingest_file = dbname + "test.immutable";
  6390. dbname += "_db";
  6391. ASSERT_OK(DestroyDB(dbname, options));
  6392. std::shared_ptr<ExternalTableFactory> factory =
  6393. std::make_shared<DummyExternalTableFactory>(
  6394. /*support_property_block=*/true);
  6395. options.table_factory = NewExternalTableFactory(factory);
  6396. // Create a file
  6397. std::unique_ptr<SstFileWriter> writer;
  6398. writer.reset(new SstFileWriter(EnvOptions(), options));
  6399. ASSERT_OK(writer->Open(ingest_file));
  6400. for (int i = 0; i < 100; ++i) {
  6401. std::stringstream ss;
  6402. ss << std::setw(2) << std::setfill('0') << i;
  6403. ASSERT_OK(writer->Put("k" + ss.str(), "val" + ss.str()));
  6404. }
  6405. ASSERT_OK(writer->Finish());
  6406. writer.reset();
  6407. std::unique_ptr<DB> db;
  6408. options.create_if_missing = true;
  6409. Status s = DB::Open(options, dbname, &db);
  6410. ASSERT_OK(s);
  6411. ASSERT_TRUE(db != nullptr);
  6412. ColumnFamilyHandle* cfh = nullptr;
  6413. ASSERT_OK(db->CreateColumnFamily(options, "new_cf", &cfh));
  6414. IngestExternalFileOptions ifo;
  6415. ifo.allow_db_generated_files = true;
  6416. ifo.fill_cache = false;
  6417. s = db->IngestExternalFile(cfh, {ingest_file}, ifo);
  6418. ASSERT_OK(s);
  6419. std::vector<std::string> key_ranges({"k03", "k10", "k25", "k50"});
  6420. ReadOptions ro;
  6421. MultiScanArgs scan_options(BytewiseComparator());
  6422. scan_options.insert(key_ranges[0], key_ranges[1]);
  6423. scan_options.insert(key_ranges[2], key_ranges[3]);
  6424. std::unique_ptr<MultiScan> iter = db->NewMultiScan(ro, cfh, scan_options);
  6425. try {
  6426. int idx = 0;
  6427. int count = 0;
  6428. for (auto range : *iter) {
  6429. for (auto it : range) {
  6430. ASSERT_GE(it.first.ToString().compare(key_ranges[idx]), 0);
  6431. ASSERT_LT(it.first.ToString().compare(key_ranges[idx + 1]), 0);
  6432. count++;
  6433. }
  6434. idx += 2;
  6435. }
  6436. ASSERT_EQ(count, 32);
  6437. } catch (MultiScanException& ex) {
  6438. // Make sure exception contains the status
  6439. ASSERT_NOK(ex.status());
  6440. std::cerr << "Iterator returned status " << ex.what();
  6441. abort();
  6442. } catch (std::logic_error& ex) {
  6443. std::cerr << "Iterator returned logic error " << ex.what();
  6444. abort();
  6445. }
  6446. iter.reset();
  6447. // Test the overlapping scan case
  6448. key_ranges[1] = "k30";
  6449. scan_options = MultiScanArgs(BytewiseComparator());
  6450. scan_options.insert(key_ranges[0], key_ranges[1]);
  6451. scan_options.insert(key_ranges[2], key_ranges[3]);
  6452. iter = db->NewMultiScan(ro, cfh, scan_options);
  6453. try {
  6454. int idx = 0;
  6455. int count = 0;
  6456. for (auto range : *iter) {
  6457. for (auto it : range) {
  6458. ASSERT_GE(it.first.ToString().compare(key_ranges[idx]), 0);
  6459. ASSERT_LT(it.first.ToString().compare(key_ranges[idx + 1]), 0);
  6460. count++;
  6461. }
  6462. idx += 2;
  6463. }
  6464. ASSERT_EQ(count, 52);
  6465. } catch (MultiScanException& ex) {
  6466. // Make sure exception contains the status
  6467. ASSERT_NOK(ex.status());
  6468. } catch (std::logic_error& ex) {
  6469. std::cerr << "Iterator returned logic error " << ex.what();
  6470. abort();
  6471. }
  6472. iter.reset();
  6473. // Test the no limit scan case
  6474. scan_options = MultiScanArgs(BytewiseComparator());
  6475. scan_options.insert(key_ranges[0]);
  6476. scan_options.insert(key_ranges[2]);
  6477. iter = db->NewMultiScan(ro, cfh, scan_options);
  6478. try {
  6479. int idx = 0;
  6480. int count = 0;
  6481. for (auto range : *iter) {
  6482. for (auto it : range) {
  6483. ASSERT_GE(it.first.ToString().compare(key_ranges[idx]), 0);
  6484. if (it.first.ToString().compare(key_ranges[idx + 1]) == 0) {
  6485. break;
  6486. }
  6487. count++;
  6488. }
  6489. idx += 2;
  6490. }
  6491. ASSERT_EQ(count, 52);
  6492. } catch (MultiScanException& ex) {
  6493. // Make sure exception contains the status
  6494. ASSERT_NOK(ex.status());
  6495. } catch (std::logic_error& ex) {
  6496. std::cerr << "Iterator returned logic error " << ex.what();
  6497. abort();
  6498. }
  6499. iter.reset();
  6500. SyncPoint::GetInstance()->SetCallBack(
  6501. "DummyExternalTableIterator::Constructor", [](void* arg) {
  6502. Status* status = static_cast<Status*>(arg);
  6503. *status = Status::IOError();
  6504. });
  6505. SyncPoint::GetInstance()->EnableProcessing();
  6506. iter = db->NewMultiScan(ro, cfh, scan_options);
  6507. try {
  6508. for (auto range : *iter) {
  6509. // Should not get here. Iterator should throw an exception
  6510. assert(false);
  6511. for (auto it : range) {
  6512. (void)it;
  6513. assert(false);
  6514. }
  6515. }
  6516. } catch (MultiScanException& ex) {
  6517. // Make sure exception contains the status
  6518. ASSERT_NOK(ex.status());
  6519. } catch (std::logic_error& ex) {
  6520. std::cerr << "Iterator returned logic error " << ex.what();
  6521. abort();
  6522. }
  6523. iter.reset();
  6524. SyncPoint::GetInstance()->DisableProcessing();
  6525. SyncPoint::GetInstance()->ClearAllCallBacks();
  6526. ASSERT_OK(db->DestroyColumnFamilyHandle(cfh));
  6527. ASSERT_OK(db->Close());
  6528. }
  6529. TEST_F(ExternalTableTest, IngestionTest) {
  6530. if (encrypted_env_) {
  6531. ROCKSDB_GTEST_SKIP("Test requires non-encrypted environment");
  6532. return;
  6533. }
  6534. Options options = GetDefaultOptions();
  6535. std::string dbname = test::PerThreadDBPath("external_table_test");
  6536. std::string ingest_file = dbname + "test.immutable";
  6537. dbname += "_db";
  6538. ASSERT_OK(DestroyDB(dbname, options));
  6539. std::shared_ptr<ExternalTableFactory> factory =
  6540. std::make_shared<DummyExternalTableFactory>(
  6541. /*support_property_block=*/true);
  6542. options.table_factory = NewExternalTableFactory(factory);
  6543. // Create a file
  6544. std::unique_ptr<SstFileWriter> writer;
  6545. writer.reset(new SstFileWriter(EnvOptions(), options));
  6546. ASSERT_OK(writer->Open(ingest_file));
  6547. ASSERT_OK(writer->Put("foo", "bar"));
  6548. ASSERT_OK(writer->Put("foo2", "bar2"));
  6549. ASSERT_OK(writer->Finish());
  6550. writer.reset();
  6551. std::unique_ptr<DB> db;
  6552. options.create_if_missing = true;
  6553. Status s = DB::Open(options, dbname, &db);
  6554. ASSERT_OK(s);
  6555. ASSERT_TRUE(db != nullptr);
  6556. ColumnFamilyHandle* cfh = nullptr;
  6557. ASSERT_OK(db->CreateColumnFamily(options, "new_cf", &cfh));
  6558. IngestExternalFileOptions ifo;
  6559. ifo.allow_db_generated_files = false;
  6560. ifo.fill_cache = false;
  6561. s = db->IngestExternalFile(cfh, {ingest_file}, ifo);
  6562. ASSERT_OK(s);
  6563. std::unique_ptr<Iterator> iter(db->NewIterator({}, cfh));
  6564. ASSERT_NE(iter, nullptr);
  6565. iter->Seek("foo");
  6566. ASSERT_TRUE(iter->Valid() && iter->status().ok());
  6567. ASSERT_EQ(iter->value(), "bar");
  6568. iter->Next();
  6569. ASSERT_TRUE(iter->Valid() && iter->status().ok());
  6570. ASSERT_EQ(iter->key(), "foo2");
  6571. ASSERT_EQ(iter->value(), "bar2");
  6572. iter->Next();
  6573. ASSERT_FALSE(iter->Valid());
  6574. ASSERT_OK(iter->status());
  6575. iter.reset();
  6576. // Create an overlapping file to ingest with atomic_replace_range option
  6577. ingest_file += "2";
  6578. writer.reset(new SstFileWriter(EnvOptions(), options));
  6579. ASSERT_OK(writer->Open(ingest_file));
  6580. ASSERT_OK(writer->Put("foo", "val"));
  6581. ASSERT_OK(writer->Put("foo2", "val2"));
  6582. ASSERT_OK(writer->Finish());
  6583. writer.reset();
  6584. ifo.snapshot_consistency = false;
  6585. s = db->IngestExternalFiles({{cfh,
  6586. {ingest_file},
  6587. ifo,
  6588. {},
  6589. {},
  6590. Temperature::kUnknown,
  6591. {{nullptr, nullptr}}}});
  6592. ASSERT_OK(s);
  6593. iter.reset(db->NewIterator({}, cfh));
  6594. ASSERT_NE(iter, nullptr);
  6595. iter->Seek("foo");
  6596. ASSERT_TRUE(iter->Valid() && iter->status().ok());
  6597. ASSERT_EQ(iter->value(), "val");
  6598. iter->Next();
  6599. ASSERT_TRUE(iter->Valid() && iter->status().ok());
  6600. ASSERT_EQ(iter->key(), "foo2");
  6601. ASSERT_EQ(iter->value(), "val2");
  6602. iter->Next();
  6603. ASSERT_FALSE(iter->Valid());
  6604. ASSERT_OK(iter->status());
  6605. iter.reset();
  6606. // Create an overlapping file to ingest without atomic_replace_range option.
  6607. // This should fail as we don't support ingesting an external file with
  6608. // non-zero assigned sequence number.
  6609. ingest_file += "3";
  6610. writer.reset(new SstFileWriter(EnvOptions(), options));
  6611. ASSERT_OK(writer->Open(ingest_file));
  6612. ASSERT_OK(writer->Put("foo", "newval"));
  6613. ASSERT_OK(writer->Put("foo2", "newval2"));
  6614. ASSERT_OK(writer->Finish());
  6615. writer.reset();
  6616. s = db->IngestExternalFiles(
  6617. {{cfh, {ingest_file}, ifo, {}, {}, Temperature::kUnknown, {}}});
  6618. ASSERT_EQ(s, Status::NotSupported());
  6619. ASSERT_OK(db->DestroyColumnFamilyHandle(cfh));
  6620. ASSERT_OK(db->Close());
  6621. }
  6622. class UserDefinedIndexTestBase : public BlockBasedTableTestBase {
  6623. public:
  6624. class CustomFlushBlockPolicy : public FlushBlockPolicy {
  6625. public:
  6626. explicit CustomFlushBlockPolicy(int keys_per_block)
  6627. : keys_in_current_block_(0), keys_per_block_(keys_per_block) {}
  6628. bool Update(const Slice& /*key*/, const Slice& /*value*/) override {
  6629. if (keys_in_current_block_ >= keys_per_block_) {
  6630. keys_in_current_block_ = 1;
  6631. return true;
  6632. }
  6633. keys_in_current_block_++;
  6634. return false;
  6635. }
  6636. private:
  6637. int keys_in_current_block_;
  6638. int keys_per_block_;
  6639. };
  6640. class CustomFlushBlockPolicyFactory : public FlushBlockPolicyFactory {
  6641. public:
  6642. CustomFlushBlockPolicyFactory(int keys_per_block = 3)
  6643. : keys_per_block_(keys_per_block) {}
  6644. const char* Name() const override { return "CustomFlushBlockPolicy"; }
  6645. FlushBlockPolicy* NewFlushBlockPolicy(const BlockBasedTableOptions&,
  6646. const BlockBuilder&) const override {
  6647. return new CustomFlushBlockPolicy(keys_per_block_);
  6648. }
  6649. int keys_per_block_;
  6650. };
  6651. public:
  6652. class TestUserDefinedIndexFactory : public UserDefinedIndexFactory {
  6653. public:
  6654. const char* Name() const override { return "test_index"; }
  6655. Status NewBuilder(
  6656. const UserDefinedIndexOption& /*option*/,
  6657. std::unique_ptr<UserDefinedIndexBuilder>& builder) const override {
  6658. builder = std::make_unique<TestUserDefinedIndexBuilder>();
  6659. return Status::OK();
  6660. }
  6661. struct CustomizedMapComparator {
  6662. CustomizedMapComparator(const Comparator* _comparator)
  6663. : comparator(_comparator) {}
  6664. const Comparator* comparator;
  6665. bool operator()(const std::string& lhs, const std::string& rhs) const {
  6666. return comparator->Compare(lhs, rhs) < 0;
  6667. }
  6668. };
  6669. // Deprecated API
  6670. UserDefinedIndexBuilder* NewBuilder() const override { return nullptr; }
  6671. std::unique_ptr<UserDefinedIndexReader> NewReader(
  6672. Slice& /*index_block*/) const override {
  6673. return nullptr;
  6674. }
  6675. Status NewReader(
  6676. const UserDefinedIndexOption& option, Slice& index_block,
  6677. std::unique_ptr<UserDefinedIndexReader>& reader) const override {
  6678. reader = std::make_unique<TestUserDefinedIndexReader>(
  6679. index_block, option.comparator, this);
  6680. return Status::OK();
  6681. }
  6682. uint64_t seek_error_count_ = 0;
  6683. uint64_t next_error_count_ = 0;
  6684. private:
  6685. class TestUserDefinedIndexBuilder : public UserDefinedIndexBuilder {
  6686. public:
  6687. TestUserDefinedIndexBuilder() : entries_added_(0), keys_added_(0) {}
  6688. Slice AddIndexEntry(const Slice& last_key_in_current_block,
  6689. const Slice* first_key_in_next_block,
  6690. const BlockHandle& block_handle,
  6691. std::string* separator_scratch) override {
  6692. if (keys_added_ == 0) {
  6693. return last_key_in_current_block;
  6694. }
  6695. EXPECT_EQ(last_key_in_current_block.size(), 5);
  6696. if (first_key_in_next_block) {
  6697. EXPECT_EQ(first_key_in_next_block->size(), 5);
  6698. }
  6699. // Unused parameters
  6700. (void)separator_scratch;
  6701. entries_added_++;
  6702. index_data_[last_key_in_current_block.ToString()].clear();
  6703. // Store the block handle for each key
  6704. PutFixed64(&index_data_[last_key_in_current_block.ToString()],
  6705. block_handle.offset);
  6706. PutFixed64(&index_data_[last_key_in_current_block.ToString()],
  6707. block_handle.size);
  6708. PutFixed32(&index_data_[last_key_in_current_block.ToString()],
  6709. keys_added_);
  6710. keys_added_ = 0;
  6711. return last_key_in_current_block;
  6712. }
  6713. void OnKeyAdded(const Slice& key, ValueType /*value*/,
  6714. const Slice& /*value*/) override {
  6715. if (key.starts_with("dummy")) {
  6716. return;
  6717. }
  6718. EXPECT_EQ(key.size(), 5);
  6719. // Track keys added to the index
  6720. keys_added_++;
  6721. // Add dummy entry
  6722. PutFixed64(&index_data_[key.ToString()], 0);
  6723. PutFixed64(&index_data_[key.ToString()], 0);
  6724. PutFixed32(&index_data_[key.ToString()], 0);
  6725. }
  6726. Status Finish(Slice* index_contents) override {
  6727. if (entries_added_ == 0) {
  6728. *index_contents = Slice();
  6729. return Status::OK();
  6730. }
  6731. // Serialize the index data
  6732. std::string result;
  6733. for (const auto& entry : index_data_) {
  6734. PutLengthPrefixedSlice(&result, entry.first);
  6735. result.append(entry.second);
  6736. }
  6737. index_contents_data_ = result;
  6738. *index_contents = index_contents_data_;
  6739. return Status::OK();
  6740. }
  6741. int GetEntriesAdded() const { return entries_added_; }
  6742. private:
  6743. int entries_added_;
  6744. std::map<std::string, std::string> index_data_;
  6745. uint32_t keys_added_;
  6746. std::string index_contents_data_;
  6747. };
  6748. class TestUserDefinedIndexReader : public UserDefinedIndexReader {
  6749. public:
  6750. explicit TestUserDefinedIndexReader(
  6751. Slice& index_block, const Comparator* comparator,
  6752. const TestUserDefinedIndexFactory* factory)
  6753. : factory_(factory),
  6754. comparator_(comparator),
  6755. index_data_(CustomizedMapComparator(comparator)) {
  6756. Slice block = index_block;
  6757. while (!block.empty()) {
  6758. Slice key;
  6759. uint64_t offset = 0;
  6760. uint64_t size = 0;
  6761. uint32_t num_keys = 0;
  6762. EXPECT_TRUE(GetLengthPrefixedSlice(&block, &key));
  6763. EXPECT_TRUE(GetFixed64(&block, &offset));
  6764. EXPECT_TRUE(GetFixed64(&block, &size));
  6765. EXPECT_TRUE(GetFixed32(&block, &num_keys));
  6766. UserDefinedIndexBuilder::BlockHandle handle{0, 0};
  6767. handle.offset = offset;
  6768. handle.size = size;
  6769. index_data_[key.ToString()] =
  6770. std::make_pair<UserDefinedIndexBuilder::BlockHandle, uint32_t>(
  6771. std::move(handle), std::move(num_keys));
  6772. }
  6773. }
  6774. std::unique_ptr<UserDefinedIndexIterator> NewIterator(
  6775. const ReadOptions& /*ro*/) override {
  6776. return std::make_unique<TestUserDefinedIndexIterator>(
  6777. index_data_, factory_, comparator_);
  6778. }
  6779. size_t ApproximateMemoryUsage() const override { return 0; }
  6780. private:
  6781. class TestUserDefinedIndexIterator : public UserDefinedIndexIterator {
  6782. public:
  6783. TestUserDefinedIndexIterator(
  6784. std::map<std::string,
  6785. std::pair<UserDefinedIndexBuilder::BlockHandle, uint32_t>,
  6786. CustomizedMapComparator>& index,
  6787. const TestUserDefinedIndexFactory* factory,
  6788. const Comparator* comparator)
  6789. : index_(index),
  6790. iter_(index_.end()),
  6791. scan_opts_(nullptr),
  6792. num_opts_(0),
  6793. target_num_keys_(0),
  6794. seek_error_count_(factory->seek_error_count_),
  6795. next_error_count_(factory->next_error_count_),
  6796. comparator_(comparator) {}
  6797. Status SeekAndGetResult(const Slice& key,
  6798. IterateResult* result) override {
  6799. Status s;
  6800. if (seek_error_count_) {
  6801. seek_error_count_--;
  6802. s = Status::IOError();
  6803. }
  6804. if (!s.ok()) {
  6805. return s;
  6806. }
  6807. if (scan_opts_) {
  6808. // Seeks should be in order specified in scan_opts_
  6809. EXPECT_EQ(comparator_->Compare(
  6810. scan_opts_[scan_idx_].range.start.value(), key),
  6811. 0);
  6812. EXPECT_TRUE(scan_opts_[scan_idx_].property_bag.has_value());
  6813. target_num_keys_ = std::stoi(scan_opts_[scan_idx_]
  6814. .property_bag.value()
  6815. .find("count")
  6816. ->second);
  6817. scan_idx_++;
  6818. }
  6819. iter_ = index_.lower_bound(key.ToString());
  6820. if ((iter_ != index_.end()) && IsInbound()) {
  6821. AdvanceToNextIndexEntry();
  6822. result->bound_check_result = IterBoundCheck::kInbound;
  6823. result->key = Slice(iter_->first);
  6824. if (scan_opts_ && target_num_keys_ > 0 &&
  6825. comparator_->Compare(key, iter_->first) == 0) {
  6826. target_num_keys_--;
  6827. }
  6828. } else {
  6829. result->bound_check_result = IterBoundCheck::kOutOfBound;
  6830. result->key = Slice();
  6831. }
  6832. return Status::OK();
  6833. }
  6834. Status NextAndGetResult(IterateResult* result) override {
  6835. Status s;
  6836. if (next_error_count_) {
  6837. next_error_count_--;
  6838. s = Status::IOError();
  6839. }
  6840. if (!s.ok()) {
  6841. return s;
  6842. }
  6843. if (scan_opts_ && scan_opts_[scan_idx_ - 1].range.limit.has_value()) {
  6844. if (comparator_->Compare(
  6845. iter_->first,
  6846. scan_opts_[scan_idx_ - 1].range.limit.value()) >= 0) {
  6847. result->bound_check_result = IterBoundCheck::kOutOfBound;
  6848. result->key = Slice();
  6849. return Status::OK();
  6850. }
  6851. }
  6852. if (scan_opts_ && target_num_keys_ == 0) {
  6853. result->key = Slice();
  6854. result->bound_check_result = IterBoundCheck::kOutOfBound;
  6855. return Status::OK();
  6856. }
  6857. iter_++;
  6858. if ((iter_ != index_.end()) && IsInbound()) {
  6859. AdvanceToNextIndexEntry();
  6860. result->bound_check_result = IterBoundCheck::kInbound;
  6861. result->key = Slice(iter_->first);
  6862. target_num_keys_ -=
  6863. std::min(target_num_keys_, iter_->second.second);
  6864. } else {
  6865. // EOF
  6866. result->bound_check_result = IterBoundCheck::kUnknown;
  6867. result->key = Slice();
  6868. }
  6869. return Status::OK();
  6870. }
  6871. void AdvanceToNextIndexEntry() {
  6872. while (iter_->second.second == 0) {
  6873. iter_++;
  6874. }
  6875. }
  6876. bool IsInbound() {
  6877. if (!scan_opts_) {
  6878. return true;
  6879. }
  6880. if (scan_opts_[scan_idx_ - 1].range.limit.has_value() &&
  6881. comparator_->Compare(
  6882. scan_opts_[scan_idx_ - 1].range.limit.value(),
  6883. iter_->first) <= 0) {
  6884. return false;
  6885. }
  6886. return true;
  6887. }
  6888. UserDefinedIndexBuilder::BlockHandle value() override {
  6889. UserDefinedIndexBuilder::BlockHandle handle{0, 0};
  6890. handle.offset = iter_->second.first.offset;
  6891. handle.size = iter_->second.first.size;
  6892. return handle;
  6893. }
  6894. void Prepare(const ScanOptions scan_opts[], size_t num_opts) override {
  6895. // Prepare should only be called once
  6896. EXPECT_EQ(scan_opts_, nullptr);
  6897. scan_opts_ = scan_opts;
  6898. num_opts_ = num_opts;
  6899. scan_idx_ = 0;
  6900. }
  6901. private:
  6902. std::map<std::string,
  6903. std::pair<UserDefinedIndexBuilder::BlockHandle, uint32_t>,
  6904. CustomizedMapComparator>& index_;
  6905. std::map<std::string, std::pair<UserDefinedIndexBuilder::BlockHandle,
  6906. uint32_t>>::iterator iter_;
  6907. const ScanOptions* scan_opts_;
  6908. size_t num_opts_{};
  6909. size_t scan_idx_{};
  6910. uint32_t target_num_keys_;
  6911. uint64_t seek_error_count_;
  6912. uint64_t next_error_count_;
  6913. const Comparator* comparator_;
  6914. };
  6915. const TestUserDefinedIndexFactory* factory_;
  6916. const Comparator* comparator_;
  6917. std::map<std::string,
  6918. std::pair<UserDefinedIndexBuilder::BlockHandle, uint32_t>,
  6919. CustomizedMapComparator>
  6920. index_data_;
  6921. };
  6922. };
  6923. protected:
  6924. std::vector<std::pair<std::string, std::string>> generateKVWithValue(
  6925. int key_count, const std::string& value) {
  6926. std::vector<std::pair<std::string, std::string>> kvs(key_count);
  6927. for (int i = 0; i < key_count; i++) {
  6928. std::stringstream ss;
  6929. ss << std::setw(2) << std::setfill('0') << i;
  6930. std::string key = "key" + ss.str();
  6931. kvs[i] = std::make_pair(key, value);
  6932. }
  6933. if (is_reverse_comparator_) {
  6934. std::reverse(kvs.begin(), kvs.end());
  6935. }
  6936. return kvs;
  6937. }
  6938. std::vector<std::pair<std::string, std::string>> generateKVs(
  6939. int key_count, int value_size = 0) {
  6940. std::vector<std::pair<std::string, std::string>> kvs(key_count);
  6941. for (int i = 0; i < key_count; i++) {
  6942. std::stringstream ss;
  6943. ss << std::setw(2) << std::setfill('0') << i;
  6944. std::string key = "key" + ss.str();
  6945. std::string value;
  6946. if (value_size != 0) {
  6947. value = rnd.RandomString(1024);
  6948. } else {
  6949. value = "value" + ss.str();
  6950. }
  6951. kvs[i] = std::make_pair(key, value);
  6952. }
  6953. if (is_reverse_comparator_) {
  6954. std::reverse(kvs.begin(), kvs.end());
  6955. }
  6956. return kvs;
  6957. }
  6958. void BasicTest(bool use_partitioned_index);
  6959. void ValidateMultiScan(
  6960. std::vector<std::tuple<std::vector<std::string>, int, int>>
  6961. scan_opt_validation_arg,
  6962. std::unordered_map<std::string, std::string> property_bag,
  6963. const ReadOptions& ro, MultiScanArgs& scan_opts,
  6964. std::vector<int>& key_counts, std::unique_ptr<DB>& db,
  6965. ColumnFamilyHandle* cfh) {
  6966. key_counts.clear();
  6967. (*scan_opts).clear();
  6968. if (is_reverse_comparator_) {
  6969. for (auto& scan_opt_validation_range : scan_opt_validation_arg) {
  6970. // reverse each range
  6971. std::reverse(std::get<0>(scan_opt_validation_range).begin(),
  6972. std::get<0>(scan_opt_validation_range).end());
  6973. }
  6974. // reverse all the ranges
  6975. std::reverse(scan_opt_validation_arg.begin(),
  6976. scan_opt_validation_arg.end());
  6977. }
  6978. for (auto& scan_opt_validation_range : scan_opt_validation_arg) {
  6979. scan_opts.insert(std::get<0>(scan_opt_validation_range)[0],
  6980. std::get<0>(scan_opt_validation_range)[1],
  6981. std::optional(property_bag));
  6982. if (is_reverse_comparator_) {
  6983. key_counts.push_back(std::get<2>(scan_opt_validation_range));
  6984. } else {
  6985. key_counts.push_back(std::get<1>(scan_opt_validation_range));
  6986. }
  6987. }
  6988. Slice ub;
  6989. ReadOptions read_opts = ro;
  6990. int key_count = 0;
  6991. int index = 0;
  6992. auto opts = scan_opts.GetScanRanges();
  6993. read_opts.iterate_upper_bound = &ub;
  6994. std::unique_ptr<Iterator> iter(db->NewIterator(read_opts, cfh));
  6995. iter->Prepare(scan_opts);
  6996. for (auto opt : opts) {
  6997. ub = opt.range.limit.value();
  6998. iter->Seek(opt.range.start.value());
  6999. if (kVerbose) {
  7000. printf("range start key %s, end key %s\n",
  7001. opt.range.start.value().ToString().c_str(),
  7002. opt.range.limit.value().ToString().c_str());
  7003. }
  7004. EXPECT_OK(iter->status());
  7005. while (iter->Valid()) {
  7006. if (kVerbose) {
  7007. printf("found key %s\n", iter->key().ToString().c_str());
  7008. }
  7009. key_count++;
  7010. iter->Next();
  7011. }
  7012. EXPECT_EQ(key_count, key_counts[index]);
  7013. key_count = 0;
  7014. index++;
  7015. }
  7016. EXPECT_OK(iter->status());
  7017. }
  7018. Options options_;
  7019. const Comparator* comparator_;
  7020. bool is_reverse_comparator_;
  7021. Random rnd{301};
  7022. };
  7023. class UserDefinedIndexTest
  7024. : public UserDefinedIndexTestBase,
  7025. public testing::WithParamInterface<const Comparator*> {
  7026. void SetUp() override {
  7027. comparator_ = GetParam();
  7028. options_.comparator = comparator_;
  7029. is_reverse_comparator_ = comparator_ == ReverseBytewiseComparator();
  7030. }
  7031. };
  7032. void UserDefinedIndexTestBase::BasicTest(bool use_partitioned_index) {
  7033. BlockBasedTableOptions table_options;
  7034. std::string dbname = test::PerThreadDBPath("user_defined_index_test");
  7035. std::string ingest_file = dbname + "test.sst";
  7036. // Set up the user-defined index factory
  7037. auto user_defined_index_factory =
  7038. std::make_shared<TestUserDefinedIndexFactory>();
  7039. table_options.user_defined_index_factory = user_defined_index_factory;
  7040. if (use_partitioned_index) {
  7041. table_options.partition_filters = true;
  7042. table_options.decouple_partitioned_filters = true;
  7043. table_options.index_type = BlockBasedTableOptions::kTwoLevelIndexSearch;
  7044. }
  7045. // Set up custom flush block policy that flushes every 3 keys
  7046. table_options.flush_block_policy_factory =
  7047. std::make_shared<CustomFlushBlockPolicyFactory>();
  7048. options_.table_factory.reset(NewBlockBasedTableFactory(table_options));
  7049. std::unique_ptr<SstFileWriter> writer;
  7050. writer.reset(new SstFileWriter(EnvOptions(), options_));
  7051. ASSERT_OK(writer->Open(ingest_file));
  7052. auto kvs = generateKVs(/*key_count*/ 100);
  7053. for (const auto& kv : kvs) {
  7054. ASSERT_OK(writer->Put(kv.first, kv.second));
  7055. }
  7056. ASSERT_OK(writer->Finish());
  7057. writer.reset();
  7058. ImmutableOptions ioptions(options_);
  7059. MutableCFOptions moptions((ColumnFamilyOptions(options_)));
  7060. EnvOptions eoptions(options_);
  7061. TableReaderOptions toptions(
  7062. ioptions, moptions.prefix_extractor,
  7063. /*_compression_manager=*/nullptr, eoptions, ioptions.internal_comparator,
  7064. moptions.block_protection_bytes_per_key,
  7065. /*skip_filters*/ false, /*immortal*/ false,
  7066. /*force_direct_prefetch*/ false, /*level*/ -1,
  7067. /*block_cache_tracer*/ nullptr,
  7068. /*max_file_size_for_l0_meta_pin*/ 0, /*cur_db_session_id*/ "",
  7069. /*cur_file_num*/ 0,
  7070. /* unique_id */ {}, /* largest_seqno */ 0,
  7071. /* tail_size */ 0, ioptions.persist_user_defined_timestamps);
  7072. // Verify that the user-defined index was created
  7073. std::string meta_block_name = kUserDefinedIndexPrefix + "test_index";
  7074. BlockHandle block_handle;
  7075. uint64_t file_size = 0;
  7076. std::unique_ptr<FSRandomAccessFile> file;
  7077. std::unique_ptr<RandomAccessFileReader> file_reader;
  7078. const auto& fs = options_.env->GetFileSystem();
  7079. ASSERT_OK(fs->GetFileSize(ingest_file, IOOptions(), &file_size, nullptr));
  7080. ASSERT_OK(fs->NewRandomAccessFile(ingest_file, eoptions, &file, nullptr));
  7081. file_reader.reset(new RandomAccessFileReader(std::move(file), ingest_file));
  7082. ASSERT_OK(FindMetaBlockInFile(file_reader.get(), file_size,
  7083. kBlockBasedTableMagicNumber, ioptions,
  7084. ReadOptions(), meta_block_name, &block_handle));
  7085. file_reader.reset();
  7086. // With our custom flush policy that flushes every 3 keys,
  7087. // we expect around 34 data blocks (100/3 rounded up)
  7088. // Verify the number of entries in the user-defined index
  7089. // Each data block should have an entry in the index
  7090. // With our flush policy of 3 keys per block, we expect around 34 entries
  7091. int expected_entries = (100 + 2) / 3; // Ceiling of 100/3
  7092. ASSERT_GE(block_handle.size(),
  7093. expected_entries); // At least this many entries
  7094. std::unique_ptr<SstFileReader> reader(new SstFileReader(options_));
  7095. ASSERT_OK(reader->Open(ingest_file));
  7096. ReadOptions ro;
  7097. std::unique_ptr<Iterator> iter(reader->NewIterator(ro));
  7098. ASSERT_NE(iter, nullptr);
  7099. // Test that we can read all the keys
  7100. int key_count = 0;
  7101. for (iter->SeekToFirst(); iter->Valid() && iter->status().ok();
  7102. iter->Next()) {
  7103. key_count++;
  7104. }
  7105. ASSERT_EQ(key_count, 100); // We added 100 keys
  7106. ASSERT_OK(iter->status());
  7107. iter.reset();
  7108. ro.table_index_factory = user_defined_index_factory.get();
  7109. iter.reset(reader->NewIterator(ro));
  7110. ASSERT_NE(iter, nullptr);
  7111. // Test seek specific key
  7112. key_count = 0;
  7113. for (iter->Seek("key40"); iter->Valid(); iter->Next()) {
  7114. key_count++;
  7115. }
  7116. ASSERT_EQ(key_count, is_reverse_comparator_ ? 41 : 60);
  7117. ASSERT_OK(iter->status());
  7118. // Test upper bound
  7119. Slice ub(is_reverse_comparator_ ? "key25" : "key75");
  7120. ro.iterate_upper_bound = &ub;
  7121. iter.reset(reader->NewIterator(ro));
  7122. ASSERT_NE(iter, nullptr);
  7123. // Test seek specific key with upper bound
  7124. key_count = 0;
  7125. for (iter->Seek("key40"); iter->Valid(); iter->Next()) {
  7126. key_count++;
  7127. }
  7128. ASSERT_EQ(key_count, is_reverse_comparator_ ? 15 : 35);
  7129. ASSERT_OK(iter->status());
  7130. user_defined_index_factory->seek_error_count_ = 1;
  7131. iter.reset(reader->NewIterator(ro));
  7132. ASSERT_NE(iter, nullptr);
  7133. iter->Seek("key40");
  7134. ASSERT_NOK(iter->status());
  7135. user_defined_index_factory->seek_error_count_ = 0;
  7136. user_defined_index_factory->next_error_count_ = 1;
  7137. iter.reset(reader->NewIterator(ro));
  7138. ASSERT_NE(iter, nullptr);
  7139. iter->Seek(is_reverse_comparator_ ? "key92" : "key09");
  7140. ASSERT_OK(iter->status());
  7141. iter->Next();
  7142. ASSERT_OK(iter->status());
  7143. iter->Next();
  7144. if (!is_reverse_comparator_) {
  7145. ASSERT_OK(iter->status());
  7146. iter->Next();
  7147. }
  7148. ASSERT_NOK(iter->status());
  7149. user_defined_index_factory->next_error_count_ = 0;
  7150. ro.iterate_upper_bound = &ub;
  7151. iter.reset(reader->NewIterator(ro));
  7152. ASSERT_NE(iter, nullptr);
  7153. MultiScanArgs scan_opts(comparator_);
  7154. std::unordered_map<std::string, std::string> property_bag;
  7155. property_bag["count"] = std::to_string(25);
  7156. std::vector<std::string> boundaries = {"key10", "key50"};
  7157. if (is_reverse_comparator_) {
  7158. std::reverse(boundaries.begin(), boundaries.end());
  7159. }
  7160. scan_opts.insert(boundaries[0], boundaries[1], std::optional(property_bag));
  7161. iter->Prepare(scan_opts);
  7162. // Test that UDI is used to help fetch the number of keys
  7163. key_count = 0;
  7164. ub = boundaries[1];
  7165. for (iter->Seek(scan_opts.GetScanRanges()[0].range.start.value());
  7166. iter->Valid(); iter->Next()) {
  7167. key_count++;
  7168. }
  7169. // The index may undercount by 2 blocks
  7170. ASSERT_EQ(key_count, 29);
  7171. ASSERT_OK(iter->status());
  7172. }
  7173. TEST_P(UserDefinedIndexTest, BasicTestWithPartitionedIndex) {
  7174. BasicTest(/*use_partitioned_index=*/true);
  7175. }
  7176. TEST_P(UserDefinedIndexTest, BasicTestWithoutPartitionedIndex) {
  7177. BasicTest(/*use_partitioned_index=*/false);
  7178. }
  7179. TEST_P(UserDefinedIndexTest, InvalidArgumentTest1) {
  7180. BlockBasedTableOptions table_options;
  7181. std::string dbname = test::PerThreadDBPath("user_defined_index_test");
  7182. std::string ingest_file = dbname + "test.sst";
  7183. // Set up the user-defined index factory
  7184. auto user_defined_index_factory =
  7185. std::make_shared<TestUserDefinedIndexFactory>();
  7186. table_options.user_defined_index_factory = user_defined_index_factory;
  7187. // Set up custom flush block policy that flushes every 3 keys
  7188. table_options.flush_block_policy_factory =
  7189. std::make_shared<CustomFlushBlockPolicyFactory>();
  7190. options_.table_factory.reset(NewBlockBasedTableFactory(table_options));
  7191. options_.compression_opts.parallel_threads = 10;
  7192. std::unique_ptr<SstFileWriter> writer;
  7193. writer.reset(new SstFileWriter(EnvOptions(), options_));
  7194. ASSERT_OK(writer->Open(ingest_file));
  7195. std::string key = "foo";
  7196. std::string value = "bar";
  7197. ASSERT_EQ(writer->Put(key, value), Status::InvalidArgument());
  7198. ASSERT_EQ(writer->Finish(), Status::InvalidArgument());
  7199. writer.reset();
  7200. }
  7201. TEST_P(UserDefinedIndexTest, InvalidArgumentTest2) {
  7202. BlockBasedTableOptions table_options;
  7203. std::string dbname = test::PerThreadDBPath("user_defined_index_test");
  7204. std::string ingest_file = dbname + "test.sst";
  7205. // Set up the user-defined index factory
  7206. auto user_defined_index_factory =
  7207. std::make_shared<TestUserDefinedIndexFactory>();
  7208. table_options.user_defined_index_factory = user_defined_index_factory;
  7209. // Set up custom flush block policy that flushes every 3 keys
  7210. table_options.flush_block_policy_factory =
  7211. std::make_shared<CustomFlushBlockPolicyFactory>();
  7212. options_.table_factory.reset(NewBlockBasedTableFactory(table_options));
  7213. std::unique_ptr<SstFileWriter> writer;
  7214. writer.reset(new SstFileWriter(EnvOptions(), options_));
  7215. ASSERT_OK(writer->Open(ingest_file));
  7216. std::string key = "foo";
  7217. std::string value = "bar";
  7218. ASSERT_OK(writer->Merge(key, value));
  7219. ASSERT_EQ(writer->Finish(), Status::InvalidArgument());
  7220. writer.reset();
  7221. }
  7222. TEST_P(UserDefinedIndexTest, IngestTest) {
  7223. BlockBasedTableOptions table_options;
  7224. std::string dbname = test::PerThreadDBPath("user_defined_index_test");
  7225. std::string ingest_file = dbname + "test.sst";
  7226. // Set up the user-defined index factory
  7227. auto user_defined_index_factory =
  7228. std::make_shared<TestUserDefinedIndexFactory>();
  7229. table_options.user_defined_index_factory = user_defined_index_factory;
  7230. // Set up custom flush block policy that flushes every 3 keys
  7231. table_options.flush_block_policy_factory =
  7232. std::make_shared<CustomFlushBlockPolicyFactory>();
  7233. options_.table_factory.reset(NewBlockBasedTableFactory(table_options));
  7234. std::unique_ptr<SstFileWriter> writer;
  7235. writer.reset(new SstFileWriter(EnvOptions(), options_));
  7236. ASSERT_OK(writer->Open(ingest_file));
  7237. auto kvs = generateKVs(/*key_count*/ 100);
  7238. for (const auto& kv : kvs) {
  7239. ASSERT_OK(writer->Put(kv.first, kv.second));
  7240. }
  7241. ASSERT_OK(writer->Finish());
  7242. writer.reset();
  7243. std::unique_ptr<DB> db;
  7244. options_.create_if_missing = true;
  7245. Status s = DB::Open(options_, dbname, &db);
  7246. ASSERT_OK(s);
  7247. ASSERT_TRUE(db != nullptr);
  7248. ColumnFamilyHandle* cfh = nullptr;
  7249. ASSERT_OK(db->CreateColumnFamily(options_, "new_cf", &cfh));
  7250. IngestExternalFileOptions ifo;
  7251. s = db->IngestExternalFile(cfh, {ingest_file}, ifo);
  7252. ASSERT_OK(s);
  7253. ReadOptions ro;
  7254. std::unique_ptr<Iterator> iter(db->NewIterator(ro, cfh));
  7255. ASSERT_NE(iter, nullptr);
  7256. ASSERT_OK(iter->status());
  7257. // Test that we can read all the keys
  7258. int key_count = 0;
  7259. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  7260. key_count++;
  7261. }
  7262. ASSERT_EQ(key_count, 100); // We added 100 keys
  7263. ASSERT_OK(iter->status());
  7264. iter.reset();
  7265. ro.table_index_factory = user_defined_index_factory.get();
  7266. iter.reset(db->NewIterator(ro, cfh));
  7267. ASSERT_NE(iter, nullptr);
  7268. // Test seek specific key
  7269. key_count = 0;
  7270. for (iter->Seek("key40"); iter->Valid(); iter->Next()) {
  7271. key_count++;
  7272. }
  7273. ASSERT_EQ(key_count, is_reverse_comparator_ ? 41 : 60);
  7274. ASSERT_OK(iter->status());
  7275. // Test upper bound
  7276. Slice ub(is_reverse_comparator_ ? "key25" : "key75");
  7277. ro.iterate_upper_bound = &ub;
  7278. iter.reset(db->NewIterator(ro, cfh));
  7279. ASSERT_NE(iter, nullptr);
  7280. // Test seek specific key with upper bound
  7281. key_count = 0;
  7282. for (iter->Seek("key40"); iter->Valid(); iter->Next()) {
  7283. key_count++;
  7284. }
  7285. ASSERT_EQ(key_count, is_reverse_comparator_ ? 15 : 35);
  7286. ASSERT_OK(iter->status());
  7287. iter.reset();
  7288. ASSERT_OK(db->DestroyColumnFamilyHandle(cfh));
  7289. ASSERT_OK(db->Close());
  7290. ASSERT_OK(DestroyDB(dbname, options_));
  7291. }
  7292. TEST_P(UserDefinedIndexTest, EmptyRangeTest) {
  7293. BlockBasedTableOptions table_options;
  7294. std::string dbname = test::PerThreadDBPath("user_defined_index_test");
  7295. std::string ingest_file = dbname + "test.sst";
  7296. // Set up the user-defined index factory
  7297. auto user_defined_index_factory =
  7298. std::make_shared<TestUserDefinedIndexFactory>();
  7299. table_options.user_defined_index_factory = user_defined_index_factory;
  7300. // Set up custom flush block policy that flushes every 3 keys
  7301. table_options.flush_block_policy_factory =
  7302. std::make_shared<CustomFlushBlockPolicyFactory>();
  7303. options_.table_factory.reset(NewBlockBasedTableFactory(table_options));
  7304. std::unique_ptr<SstFileWriter> writer;
  7305. writer.reset(new SstFileWriter(EnvOptions(), options_));
  7306. ASSERT_OK(writer->Open(ingest_file));
  7307. // Generate key range key0 ~ key19, key40 ~ key59, key80 ~ key99
  7308. std::vector<std::pair<std::string, std::string>> kvs;
  7309. bool skip = false;
  7310. for (int i = 0; i < 100; i++) {
  7311. if (i > 0 && i % 20 == 0) {
  7312. skip = !skip;
  7313. }
  7314. if (skip) {
  7315. continue;
  7316. }
  7317. std::stringstream ss;
  7318. ss << std::setw(2) << std::setfill('0') << i;
  7319. std::string key = "key" + ss.str();
  7320. std::string value = "value" + ss.str();
  7321. kvs.emplace_back(key, value);
  7322. }
  7323. if (is_reverse_comparator_) {
  7324. std::reverse(kvs.begin(), kvs.end());
  7325. }
  7326. for (const auto& kv : kvs) {
  7327. ASSERT_OK(writer->Put(kv.first, kv.second));
  7328. }
  7329. ASSERT_OK(writer->Finish());
  7330. writer.reset();
  7331. std::unique_ptr<DB> db;
  7332. options_.create_if_missing = true;
  7333. Status s = DB::Open(options_, dbname, &db);
  7334. ASSERT_OK(s);
  7335. ASSERT_TRUE(db != nullptr);
  7336. ColumnFamilyHandle* cfh = nullptr;
  7337. ASSERT_OK(db->CreateColumnFamily(options_, "new_cf", &cfh));
  7338. IngestExternalFileOptions ifo;
  7339. s = db->IngestExternalFile(cfh, {ingest_file}, ifo);
  7340. ASSERT_OK(s);
  7341. ReadOptions ro;
  7342. std::unique_ptr<Iterator> iter(db->NewIterator(ro, cfh));
  7343. ASSERT_NE(iter, nullptr);
  7344. ASSERT_OK(iter->status());
  7345. // Test that we can read all the keys
  7346. int key_count = 0;
  7347. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  7348. key_count++;
  7349. }
  7350. ASSERT_EQ(key_count, 60);
  7351. ASSERT_OK(iter->status());
  7352. iter.reset();
  7353. ro.table_index_factory = user_defined_index_factory.get();
  7354. std::vector<int> key_counts;
  7355. MultiScanArgs scan_opts(options_.comparator);
  7356. std::unordered_map<std::string, std::string> property_bag;
  7357. property_bag["count"] = std::to_string(5);
  7358. ValidateMultiScan({{{"key25", "key30"}, 0, 0},
  7359. {{"key33", "key37"}, 0, 0},
  7360. // Non-empty scan with range greater than count
  7361. // In the key42:key56 range, we might read an additional
  7362. // block worth of keys due to the boundaries (5 + 3)
  7363. {{"key42", "key56"}, 8, 7},
  7364. // Empty scan succeeding a non-empty one
  7365. {{"key65", "key70"}, 0, 0},
  7366. // A non-empty scan with range smaller than count
  7367. {{"key85", "key87"}, 2, 2},
  7368. // Scan range completely outside the DB
  7369. {{"key991", "key999"}, 0, 0}},
  7370. property_bag, ro, scan_opts, key_counts, db, cfh);
  7371. // Scans that overlap with part of key range, with overlap less than count
  7372. ValidateMultiScan({{{"key18", "key25"}, 2, 1}, {{"key38", "key43"}, 3, 4}},
  7373. property_bag, ro, scan_opts, key_counts, db, cfh);
  7374. // Scans that overlap with part of key range, with overlap same as count
  7375. ValidateMultiScan({{{"key15", "key26"}, 5, 4}, {{"key38", "key46"}, 6, 7}},
  7376. property_bag, ro, scan_opts, key_counts, db, cfh);
  7377. // Scans that overlap with part of key range, with overlap greater than count
  7378. ValidateMultiScan({{{"key10", "key26"}, 8, 8},
  7379. // Cross block boundary
  7380. {{"key38", "key49"}, 7, 9}},
  7381. property_bag, ro, scan_opts, key_counts, db, cfh);
  7382. // Scan bigger than one contiguous range of keys, with overlap greater than
  7383. // count
  7384. ValidateMultiScan({{{"key75", "key991"}, 8, 9}}, property_bag, ro, scan_opts,
  7385. key_counts, db, cfh);
  7386. // Scan bigger than one contiguous range of keys, with overlap less than count
  7387. property_bag["count"] = std::to_string(25);
  7388. ValidateMultiScan({{{"key75", "key991"}, 20, 20}}, property_bag, ro,
  7389. scan_opts, key_counts, db, cfh);
  7390. ASSERT_OK(db->DestroyColumnFamilyHandle(cfh));
  7391. ASSERT_OK(db->Close());
  7392. ASSERT_OK(DestroyDB(dbname, options_));
  7393. }
  7394. // Verify that external file ingestion fails if we try to ingest an SST file
  7395. // without the UDI and a UDI factory is configured in BlockBasedTableOptions
  7396. // and fail_if_no_udi_on_open is true in BlockBasedTableOptions.
  7397. TEST_P(UserDefinedIndexTest, IngestFailTest) {
  7398. BlockBasedTableOptions table_options;
  7399. std::string dbname = test::PerThreadDBPath("user_defined_index_test");
  7400. std::string ingest_file = dbname + "test.sst";
  7401. // Set up custom flush block policy that flushes every 3 keys
  7402. table_options.flush_block_policy_factory =
  7403. std::make_shared<CustomFlushBlockPolicyFactory>();
  7404. options_.table_factory.reset(NewBlockBasedTableFactory(table_options));
  7405. std::unique_ptr<SstFileWriter> writer;
  7406. writer.reset(new SstFileWriter(EnvOptions(), options_));
  7407. ASSERT_OK(writer->Open(ingest_file));
  7408. auto kvs = generateKVs(/*key_count*/ 100);
  7409. for (const auto& kv : kvs) {
  7410. ASSERT_OK(writer->Put(kv.first, kv.second));
  7411. }
  7412. ASSERT_OK(writer->Finish());
  7413. writer.reset();
  7414. // Set up the user-defined index factory
  7415. auto user_defined_index_factory =
  7416. std::make_shared<TestUserDefinedIndexFactory>();
  7417. table_options.user_defined_index_factory = user_defined_index_factory;
  7418. table_options.fail_if_no_udi_on_open = true;
  7419. options_.table_factory.reset(NewBlockBasedTableFactory(table_options));
  7420. std::unique_ptr<DB> db;
  7421. options_.create_if_missing = true;
  7422. Status s = DB::Open(options_, dbname, &db);
  7423. ASSERT_OK(s);
  7424. ASSERT_TRUE(db != nullptr);
  7425. ColumnFamilyHandle* cfh = nullptr;
  7426. ASSERT_OK(db->CreateColumnFamily(options_, "new_cf", &cfh));
  7427. IngestExternalFileOptions ifo;
  7428. s = db->IngestExternalFile(cfh, {ingest_file}, ifo);
  7429. ASSERT_NOK(s);
  7430. ASSERT_OK(db->SetOptions(
  7431. cfh, {{"block_based_table_factory", "{fail_if_no_udi_on_open=false;}"}}));
  7432. s = db->IngestExternalFile(cfh, {ingest_file}, ifo);
  7433. ASSERT_OK(s);
  7434. ASSERT_OK(db->DestroyColumnFamilyHandle(cfh));
  7435. ASSERT_OK(db->Close());
  7436. ASSERT_OK(DestroyDB(dbname, options_));
  7437. }
  7438. TEST_P(UserDefinedIndexTest, IngestEmptyUDI) {
  7439. BlockBasedTableOptions table_options;
  7440. std::string dbname = test::PerThreadDBPath("user_defined_index_test");
  7441. std::string ingest_file = dbname + "test.sst";
  7442. std::string ingest_file2 = dbname + "dummy.sst";
  7443. // Set up the user-defined index factory
  7444. auto user_defined_index_factory =
  7445. std::make_shared<TestUserDefinedIndexFactory>();
  7446. table_options.user_defined_index_factory = user_defined_index_factory;
  7447. // Set up custom flush block policy that flushes every 3 keys
  7448. table_options.flush_block_policy_factory =
  7449. std::make_shared<CustomFlushBlockPolicyFactory>();
  7450. options_.table_factory.reset(NewBlockBasedTableFactory(table_options));
  7451. std::unique_ptr<SstFileWriter> writer;
  7452. writer.reset(new SstFileWriter(EnvOptions(), options_));
  7453. ASSERT_OK(writer->Open(ingest_file));
  7454. auto kvs = generateKVs(/*key_count*/ 100);
  7455. for (const auto& kv : kvs) {
  7456. ASSERT_OK(writer->Put(kv.first, kv.second));
  7457. }
  7458. ASSERT_OK(writer->Finish());
  7459. writer.reset();
  7460. writer.reset(new SstFileWriter(EnvOptions(), options_));
  7461. ASSERT_OK(writer->Open(ingest_file2));
  7462. ASSERT_OK(writer->Put("dummy", "val"));
  7463. ASSERT_OK(writer->Finish());
  7464. writer.reset();
  7465. table_options.fail_if_no_udi_on_open = true;
  7466. options_.table_factory.reset(NewBlockBasedTableFactory(table_options));
  7467. std::unique_ptr<DB> db;
  7468. options_.create_if_missing = true;
  7469. Status s = DB::Open(options_, dbname, &db);
  7470. ASSERT_OK(s);
  7471. ASSERT_TRUE(db != nullptr);
  7472. ColumnFamilyHandle* cfh = nullptr;
  7473. ASSERT_OK(db->CreateColumnFamily(options_, "new_cf", &cfh));
  7474. std::vector<IngestExternalFileArg> ifa;
  7475. ifa.emplace_back();
  7476. ifa[0].column_family = cfh;
  7477. ifa[0].external_files.emplace_back(ingest_file);
  7478. ifa[0].external_files.emplace_back(ingest_file2);
  7479. s = db->IngestExternalFiles(ifa);
  7480. ASSERT_OK(s);
  7481. ASSERT_OK(db->DestroyColumnFamilyHandle(cfh));
  7482. ASSERT_OK(db->Close());
  7483. ASSERT_OK(DestroyDB(dbname, options_));
  7484. }
  7485. TEST_P(UserDefinedIndexTest, MultiScanFailureTest) {
  7486. BlockBasedTableOptions table_options;
  7487. std::string dbname = test::PerThreadDBPath("user_defined_index_test");
  7488. std::string ingest_file = dbname + "test.sst";
  7489. // Set up the user-defined index factory
  7490. auto user_defined_index_factory =
  7491. std::make_shared<TestUserDefinedIndexFactory>();
  7492. table_options.user_defined_index_factory = user_defined_index_factory;
  7493. // Set up custom flush block policy that flushes every 3 keys
  7494. table_options.flush_block_policy_factory =
  7495. std::make_shared<CustomFlushBlockPolicyFactory>();
  7496. options_.table_factory.reset(NewBlockBasedTableFactory(table_options));
  7497. std::unique_ptr<SstFileWriter> writer;
  7498. writer.reset(new SstFileWriter(EnvOptions(), options_));
  7499. ASSERT_OK(writer->Open(ingest_file));
  7500. // Use bigger value, so that prefetch size limit will be effective
  7501. auto kvs = generateKVs(/*key_count*/ 100, /* value_size */ 1024);
  7502. for (const auto& kv : kvs) {
  7503. ASSERT_OK(writer->Put(kv.first, kv.second));
  7504. }
  7505. ASSERT_OK(writer->Finish());
  7506. writer.reset();
  7507. std::unique_ptr<DB> db;
  7508. options_.create_if_missing = true;
  7509. Status s = DB::Open(options_, dbname, &db);
  7510. ASSERT_OK(s);
  7511. ASSERT_TRUE(db != nullptr);
  7512. ColumnFamilyHandle* cfh = nullptr;
  7513. ASSERT_OK(db->CreateColumnFamily(options_, "new_cf", &cfh));
  7514. IngestExternalFileOptions ifo;
  7515. s = db->IngestExternalFile(cfh, {ingest_file}, ifo);
  7516. ASSERT_OK(s);
  7517. std::vector<std::string> key_ranges({"key03", "key05", "key12", "key14"});
  7518. ReadOptions ro;
  7519. ro.table_index_factory = user_defined_index_factory.get();
  7520. Slice ub;
  7521. ro.iterate_upper_bound = &ub;
  7522. std::unordered_map<std::string, std::string> property_bag;
  7523. property_bag["count"] = std::to_string(5);
  7524. MultiScanArgs scan_options(comparator_);
  7525. if (is_reverse_comparator_) {
  7526. std::reverse(key_ranges.begin(), key_ranges.end());
  7527. }
  7528. scan_options.insert(key_ranges[0], key_ranges[1], property_bag);
  7529. scan_options.insert(key_ranges[2], key_ranges[3], property_bag);
  7530. scan_options.max_prefetch_size = 3500;
  7531. std::unique_ptr<Iterator> iter(db->NewIterator(ro, cfh));
  7532. ASSERT_NE(iter, nullptr);
  7533. iter->Prepare(scan_options);
  7534. int count = 0;
  7535. ub = key_ranges[1];
  7536. iter->Seek(key_ranges[0]);
  7537. while (iter->status().ok() && iter->Valid()) {
  7538. ASSERT_GE(comparator_->Compare(iter->key(), key_ranges[0]), 0);
  7539. ASSERT_LT(comparator_->Compare(iter->key(), key_ranges[1]), 0);
  7540. count++;
  7541. iter->Next();
  7542. }
  7543. ASSERT_OK(iter->status()) << iter->status().ToString();
  7544. ASSERT_EQ(count, 2);
  7545. ub = key_ranges[3];
  7546. iter->Seek(key_ranges[2]);
  7547. // This should fail due to reaching max_prefetch_size limit
  7548. ASSERT_EQ(iter->status(), Status::Incomplete());
  7549. iter.reset();
  7550. // Empty range multiscan error
  7551. iter.reset(db->NewIterator(ro, cfh));
  7552. scan_options = MultiScanArgs(comparator_);
  7553. iter->Prepare(scan_options);
  7554. ASSERT_EQ(iter->status(), Status::InvalidArgument("Empty MultiScanArgs"));
  7555. // Check no seek key error
  7556. iter.reset(db->NewIterator(ro, cfh));
  7557. scan_options = MultiScanArgs(comparator_);
  7558. scan_options.insert(key_ranges[0], key_ranges[2], property_bag);
  7559. iter->Prepare(scan_options);
  7560. iter->SeekToFirst();
  7561. ASSERT_EQ(iter->status(),
  7562. Status::InvalidArgument("No seek key for MultiScan"));
  7563. // Seek is not allowed to seen a key that is not following the prepare order
  7564. iter.reset(db->NewIterator(ro, cfh));
  7565. ASSERT_NE(iter, nullptr);
  7566. scan_options.max_prefetch_size = 0;
  7567. iter->Prepare(scan_options);
  7568. ub = key_ranges[3];
  7569. iter->Seek(key_ranges[2]);
  7570. ASSERT_EQ(
  7571. iter->status(),
  7572. Status::InvalidArgument(
  7573. "Seek target does not match the start of the next prepared range at "
  7574. "index 0"));
  7575. ASSERT_FALSE(iter->Valid());
  7576. iter.reset();
  7577. // limit is equal to start error
  7578. iter.reset(db->NewIterator(ro, cfh));
  7579. ASSERT_NE(iter, nullptr);
  7580. (*scan_options).clear();
  7581. scan_options.insert(key_ranges[0], key_ranges[0], property_bag);
  7582. iter->Prepare(scan_options);
  7583. ASSERT_EQ(iter->status(),
  7584. Status::InvalidArgument(
  7585. "Scan start key is large or equal than limit at index 0"));
  7586. iter.reset();
  7587. // overlapping ranges error
  7588. iter.reset(db->NewIterator(ro, cfh));
  7589. ASSERT_NE(iter, nullptr);
  7590. (*scan_options).clear();
  7591. scan_options.insert(key_ranges[0], key_ranges[2], property_bag);
  7592. scan_options.insert(key_ranges[1], key_ranges[3], property_bag);
  7593. iter->Prepare(scan_options);
  7594. ASSERT_EQ(iter->status(),
  7595. Status::InvalidArgument("Overlapping ranges at index 1"));
  7596. iter.reset();
  7597. // Validate an error is returned if upper bound is not set to the same value
  7598. // as limit
  7599. iter.reset(db->NewIterator(ro, cfh));
  7600. scan_options = MultiScanArgs(comparator_);
  7601. scan_options.insert(key_ranges[0], key_ranges[1], property_bag);
  7602. iter->Prepare(scan_options);
  7603. ub = "";
  7604. iter->Seek(key_ranges[0]);
  7605. ASSERT_EQ(iter->status(),
  7606. Status::InvalidArgument(
  7607. "Upper bound is not set to the same limit value of the next "
  7608. "prepared range at index 0"));
  7609. ASSERT_FALSE(iter->Valid());
  7610. // Validate an error is returned when seek more keys than prepared
  7611. iter.reset(db->NewIterator(ro, cfh));
  7612. scan_options = MultiScanArgs(comparator_);
  7613. scan_options.insert(key_ranges[0], key_ranges[1], property_bag);
  7614. iter->Prepare(scan_options);
  7615. ub = key_ranges[1];
  7616. iter->Seek(key_ranges[0]);
  7617. ASSERT_OK(iter->status());
  7618. ASSERT_TRUE(iter->Valid());
  7619. iter->Seek(key_ranges[2]);
  7620. ASSERT_EQ(iter->status(),
  7621. Status::InvalidArgument(
  7622. "Seek called after exhausting all of the scan ranges"));
  7623. ASSERT_FALSE(iter->Valid());
  7624. iter.reset();
  7625. // Check error is returned if upper bound is not set and limit is set
  7626. ro.iterate_upper_bound = nullptr;
  7627. iter.reset(db->NewIterator(ro, cfh));
  7628. scan_options = MultiScanArgs(comparator_);
  7629. scan_options.insert(key_ranges[0], key_ranges[1], property_bag);
  7630. iter->Prepare(scan_options);
  7631. iter->Seek(key_ranges[0]);
  7632. ASSERT_EQ(iter->status(),
  7633. Status::InvalidArgument(
  7634. "Upper bound is not set to the same limit value of the next "
  7635. "prepared range at index 0"));
  7636. ASSERT_FALSE(iter->Valid());
  7637. iter.reset();
  7638. // Upper bound is allowed to be empty, if limit is not set
  7639. ro.iterate_upper_bound = nullptr;
  7640. iter.reset(db->NewIterator(ro, cfh));
  7641. scan_options = MultiScanArgs(comparator_);
  7642. scan_options.insert(key_ranges[0], property_bag);
  7643. iter->Prepare(scan_options);
  7644. iter->Seek(key_ranges[0]);
  7645. ASSERT_OK(iter->status());
  7646. ASSERT_TRUE(iter->Valid());
  7647. iter.reset();
  7648. ASSERT_OK(db->DestroyColumnFamilyHandle(cfh));
  7649. ASSERT_OK(db->Close());
  7650. ASSERT_OK(DestroyDB(dbname, options_));
  7651. }
  7652. TEST_P(UserDefinedIndexTest, ConfigTest) {
  7653. BlockBasedTableOptions table_options;
  7654. std::string dbname = test::PerThreadDBPath("user_defined_index_test");
  7655. std::string ingest_file = dbname + "test.sst";
  7656. // Set up the user-defined index factory
  7657. auto user_defined_index_factory =
  7658. std::make_shared<TestUserDefinedIndexFactory>();
  7659. table_options.user_defined_index_factory = user_defined_index_factory;
  7660. // Set up custom flush block policy that flushes every 3 keys
  7661. table_options.flush_block_policy_factory =
  7662. std::make_shared<CustomFlushBlockPolicyFactory>();
  7663. options_.table_factory.reset(NewBlockBasedTableFactory(table_options));
  7664. std::unique_ptr<SstFileWriter> writer;
  7665. writer.reset(new SstFileWriter(EnvOptions(), options_));
  7666. ASSERT_OK(writer->Open(ingest_file));
  7667. auto kvs = generateKVs(/*key_count*/ 100);
  7668. for (const auto& kv : kvs) {
  7669. ASSERT_OK(writer->Put(kv.first, kv.second));
  7670. }
  7671. ASSERT_OK(writer->Finish());
  7672. writer.reset();
  7673. table_options.user_defined_index_factory.reset();
  7674. options_.table_factory.reset(NewBlockBasedTableFactory(table_options));
  7675. // Set up the user-defined index factory
  7676. ObjectLibrary::Default().get()->AddFactory<UserDefinedIndexFactory>(
  7677. "test_index", [](const std::string& /* uri */,
  7678. std::unique_ptr<UserDefinedIndexFactory>* guard,
  7679. std::string* /* errmsg */) {
  7680. auto factory = new TestUserDefinedIndexFactory();
  7681. guard->reset(factory);
  7682. return guard->get();
  7683. });
  7684. ASSERT_OK(GetColumnFamilyOptionsFromString(
  7685. ConfigOptions(), options_,
  7686. "block_based_table_factory={user_defined_index_factory=test_index;}",
  7687. &options_));
  7688. std::unique_ptr<DB> db;
  7689. options_.create_if_missing = true;
  7690. Status s = DB::Open(options_, dbname, &db);
  7691. ASSERT_OK(s);
  7692. ASSERT_TRUE(db != nullptr);
  7693. ColumnFamilyHandle* cfh = nullptr;
  7694. ASSERT_OK(db->CreateColumnFamily(options_, "new_cf", &cfh));
  7695. IngestExternalFileOptions ifo;
  7696. s = db->IngestExternalFile(cfh, {ingest_file}, ifo);
  7697. ASSERT_OK(s);
  7698. ReadOptions ro;
  7699. Slice ub;
  7700. ro.iterate_upper_bound = &ub;
  7701. ro.table_index_factory = user_defined_index_factory.get();
  7702. std::unique_ptr<Iterator> iter(db->NewIterator(ro, cfh));
  7703. ASSERT_NE(iter, nullptr);
  7704. MultiScanArgs scan_opts(options_.comparator);
  7705. std::unordered_map<std::string, std::string> property_bag;
  7706. property_bag["count"] = std::to_string(25);
  7707. std::vector<std::string> boundaries = {"key10", "key50"};
  7708. if (is_reverse_comparator_) {
  7709. std::reverse(boundaries.begin(), boundaries.end());
  7710. }
  7711. scan_opts.insert(boundaries[0], boundaries[1], std::optional(property_bag));
  7712. iter->Prepare(scan_opts);
  7713. // Test that UDI is used to help fetch the number of keys
  7714. ub = boundaries[1];
  7715. int key_count = 0;
  7716. for (iter->Seek(scan_opts.GetScanRanges()[0].range.start.value());
  7717. iter->Valid(); iter->Next()) {
  7718. key_count++;
  7719. }
  7720. // Number of blocks prepared is based on UDI, it would be slightly higher than
  7721. // the limit
  7722. // The index may undercount by 2 blocks
  7723. ASSERT_EQ(key_count, 29);
  7724. ASSERT_OK(iter->status());
  7725. iter.reset();
  7726. ASSERT_OK(db->DestroyColumnFamilyHandle(cfh));
  7727. ASSERT_OK(db->Close());
  7728. ASSERT_OK(DestroyDB(dbname, options_));
  7729. }
  7730. TEST_P(UserDefinedIndexTest, RangeDelete) {
  7731. BlockBasedTableOptions table_options;
  7732. options_.num_levels = 50;
  7733. options_.compaction_style = kCompactionStyleUniversal;
  7734. options_.disable_auto_compactions = true;
  7735. std::string dbname = test::PerThreadDBPath("user_defined_index_test");
  7736. std::string ingest_file = dbname + "test.sst";
  7737. // Set up the user-defined index factory
  7738. auto user_defined_index_factory =
  7739. std::make_shared<TestUserDefinedIndexFactory>();
  7740. table_options.user_defined_index_factory = user_defined_index_factory;
  7741. // Set up custom flush block policy that flushes every 3 keys
  7742. table_options.flush_block_policy_factory =
  7743. std::make_shared<CustomFlushBlockPolicyFactory>();
  7744. options_.table_factory.reset(NewBlockBasedTableFactory(table_options));
  7745. auto create_ingestion_data_file = [&](const std::string& filename) {
  7746. std::unique_ptr<SstFileWriter> writer;
  7747. writer.reset(new SstFileWriter(EnvOptions(), options_));
  7748. ASSERT_OK(writer->Open(filename));
  7749. auto kvs = generateKVs(100);
  7750. for (const auto& kv : kvs) {
  7751. ASSERT_OK(writer->Put(kv.first, kv.second));
  7752. }
  7753. ASSERT_OK(writer->Finish());
  7754. writer.reset();
  7755. };
  7756. // Create first ingestion file with data
  7757. create_ingestion_data_file(ingest_file + "_0");
  7758. // Create second ingestion file with range delete only that covers the first
  7759. // file to delete all of its keys.
  7760. {
  7761. std::unique_ptr<SstFileWriter> writer;
  7762. writer.reset(new SstFileWriter(EnvOptions(), options_));
  7763. ASSERT_OK(writer->Open(ingest_file + "_1"));
  7764. if (is_reverse_comparator_) {
  7765. ASSERT_OK(writer->DeleteRange("keyz", "key"));
  7766. } else {
  7767. ASSERT_OK(writer->DeleteRange("key", "keyz"));
  7768. }
  7769. ASSERT_OK(writer->Finish());
  7770. writer.reset();
  7771. }
  7772. // Create the second ingestion file with data
  7773. create_ingestion_data_file(ingest_file + "_2");
  7774. std::unique_ptr<DB> db;
  7775. options_.create_if_missing = true;
  7776. Status s = DB::Open(options_, dbname, &db);
  7777. ASSERT_OK(s);
  7778. ASSERT_TRUE(db != nullptr);
  7779. ColumnFamilyHandle* cfh = nullptr;
  7780. ASSERT_OK(db->CreateColumnFamily(options_, "new_cf", &cfh));
  7781. IngestExternalFileOptions ifo;
  7782. // ingest first data file key00~key99
  7783. s = db->IngestExternalFile(cfh, {ingest_file + "_0"}, ifo);
  7784. ASSERT_OK(s);
  7785. // ingest delete range (key-keyz) and new data file (key00-key99) together
  7786. s = db->IngestExternalFile(cfh, {ingest_file + "_1", ingest_file + "_2"},
  7787. ifo);
  7788. ASSERT_OK(s);
  7789. std::vector<Slice> range = {
  7790. Slice("key10"),
  7791. Slice("key25"),
  7792. Slice("key80"),
  7793. Slice("key95"),
  7794. };
  7795. if (is_reverse_comparator_) {
  7796. std::reverse(range.begin(), range.end());
  7797. }
  7798. Slice ub("");
  7799. ReadOptions ro;
  7800. ro.iterate_upper_bound = &ub;
  7801. std::unique_ptr<Iterator> iter(db->NewIterator(ro, cfh));
  7802. ASSERT_NE(iter, nullptr);
  7803. MultiScanArgs scan_opts(options_.comparator);
  7804. std::unordered_map<std::string, std::string> property_bag;
  7805. property_bag["count"] = std::to_string(9);
  7806. std::vector<std::vector<char>> decoded_ranges;
  7807. for (size_t i = 0; i < range.size() / 2; i++) {
  7808. scan_opts.insert(range[i * 2], range[i * 2 + 1],
  7809. std::optional(property_bag));
  7810. }
  7811. iter->Prepare(scan_opts);
  7812. for (size_t i = 0; i < range.size() / 2; i++) {
  7813. // Update upper bound before each seek
  7814. ub = range[2 * i + 1];
  7815. auto key_count = 0;
  7816. for (iter->Seek(range[i * 2]); iter->Valid(); iter->Next()) {
  7817. key_count++;
  7818. }
  7819. ASSERT_OK(iter->status());
  7820. ASSERT_EQ(key_count, 15);
  7821. }
  7822. iter.reset();
  7823. ASSERT_OK(db->DestroyColumnFamilyHandle(cfh));
  7824. ASSERT_OK(db->Close());
  7825. ASSERT_OK(DestroyDB(dbname, options_));
  7826. }
  7827. TEST_P(UserDefinedIndexTest, QueryCrossTwoFiles) {
  7828. BlockBasedTableOptions table_options;
  7829. options_.num_levels = 50;
  7830. options_.compaction_style = kCompactionStyleUniversal;
  7831. options_.disable_auto_compactions = true;
  7832. options_.sst_partitioner_factory = NewSstPartitionerFixedPrefixFactory(4);
  7833. std::string dbname = test::PerThreadDBPath("user_defined_index_test");
  7834. std::string ingest_file = dbname + "test.sst";
  7835. // Set up the user-defined index factory
  7836. auto user_defined_index_factory =
  7837. std::make_shared<TestUserDefinedIndexFactory>();
  7838. table_options.user_defined_index_factory = user_defined_index_factory;
  7839. // Set up custom flush block policy that flushes every 3 keys
  7840. table_options.flush_block_policy_factory =
  7841. std::make_shared<CustomFlushBlockPolicyFactory>();
  7842. options_.table_factory.reset(NewBlockBasedTableFactory(table_options));
  7843. auto create_ingestion_data_file = [&](const std::string& filename,
  7844. const std::string& value) {
  7845. std::unique_ptr<SstFileWriter> writer;
  7846. writer.reset(new SstFileWriter(EnvOptions(), options_));
  7847. ASSERT_OK(writer->Open(filename));
  7848. auto kvs = generateKVWithValue(100, value);
  7849. for (const auto& kv : kvs) {
  7850. ASSERT_OK(writer->Put(kv.first, kv.second));
  7851. }
  7852. ASSERT_OK(writer->Finish());
  7853. writer.reset();
  7854. };
  7855. // Create first ingestion file with data
  7856. create_ingestion_data_file(ingest_file + "_0", "old");
  7857. std::unique_ptr<DB> db;
  7858. options_.create_if_missing = true;
  7859. Status s = DB::Open(options_, dbname, &db);
  7860. ASSERT_OK(s);
  7861. ASSERT_TRUE(db != nullptr);
  7862. ColumnFamilyHandle* cfh = nullptr;
  7863. ASSERT_OK(db->CreateColumnFamily(options_, "new_cf", &cfh));
  7864. IngestExternalFileOptions ifo;
  7865. // ingest data file key00~key99
  7866. s = db->IngestExternalFile(cfh, {ingest_file + "_0"}, ifo);
  7867. ASSERT_OK(s);
  7868. // Compact the file with SST partitioner, so that files are split into
  7869. // multiple ones
  7870. s = db->CompactRange(
  7871. {.exclusive_manual_compaction = true,
  7872. .bottommost_level_compaction = BottommostLevelCompaction::kForce},
  7873. cfh, nullptr, nullptr);
  7874. ASSERT_OK(s);
  7875. std::vector<Slice> range = {
  7876. // Each range span across 2 files
  7877. Slice("key16"),
  7878. Slice("key24"),
  7879. Slice("key26"),
  7880. Slice("key34"),
  7881. };
  7882. if (is_reverse_comparator_) {
  7883. std::reverse(range.begin(), range.end());
  7884. }
  7885. Slice ub("");
  7886. ReadOptions ro;
  7887. ro.iterate_upper_bound = &ub;
  7888. std::unique_ptr<Iterator> iter(db->NewIterator(ro, cfh));
  7889. ASSERT_NE(iter, nullptr);
  7890. MultiScanArgs scan_opts(options_.comparator);
  7891. std::unordered_map<std::string, std::string> property_bag;
  7892. auto read_key_per_range_limit = 2;
  7893. property_bag["count"] = std::to_string(read_key_per_range_limit);
  7894. for (size_t i = 0; i < range.size() / 2; i++) {
  7895. scan_opts.insert(range[i * 2], range[i * 2 + 1],
  7896. std::optional(property_bag));
  7897. }
  7898. iter->Prepare(scan_opts);
  7899. for (size_t i = 0; i < range.size() / 2; i++) {
  7900. // Update upper bound before each seek
  7901. ub = range[2 * i + 1];
  7902. auto key_count = 0;
  7903. for (iter->Seek(range[i * 2]); iter->Valid(); iter->Next()) {
  7904. key_count++;
  7905. ASSERT_EQ(iter->value(), "old");
  7906. if (key_count >= read_key_per_range_limit) {
  7907. break;
  7908. }
  7909. }
  7910. ASSERT_OK(iter->status());
  7911. ASSERT_EQ(key_count, read_key_per_range_limit);
  7912. }
  7913. // Create another ingestion file with range delete only that covers the first
  7914. // file to delete all of its keys.
  7915. {
  7916. std::unique_ptr<SstFileWriter> writer;
  7917. writer.reset(new SstFileWriter(EnvOptions(), options_));
  7918. ASSERT_OK(writer->Open(ingest_file + "_1"));
  7919. if (is_reverse_comparator_) {
  7920. ASSERT_OK(writer->DeleteRange("keyz", "key"));
  7921. } else {
  7922. ASSERT_OK(writer->DeleteRange("key", "keyz"));
  7923. }
  7924. ASSERT_OK(writer->Finish());
  7925. writer.reset();
  7926. }
  7927. s = db->IngestExternalFile(cfh, {ingest_file + "_1"}, ifo);
  7928. ASSERT_OK(s);
  7929. // ingest new data
  7930. create_ingestion_data_file(ingest_file + "_2", "new");
  7931. s = db->IngestExternalFile(cfh, {ingest_file + "_2"}, ifo);
  7932. ASSERT_OK(s);
  7933. iter.reset(db->NewIterator(ro, cfh));
  7934. ASSERT_NE(iter, nullptr);
  7935. ASSERT_OK(iter->status());
  7936. iter->Prepare(scan_opts);
  7937. for (size_t i = 0; i < range.size() / 2; i++) {
  7938. // Update upper bound before each seek
  7939. ub = range[2 * i + 1];
  7940. auto key_count = 0;
  7941. for (iter->Seek(range[i * 2]); iter->Valid(); iter->Next()) {
  7942. key_count++;
  7943. ASSERT_EQ(iter->value(), "new");
  7944. if (key_count >= read_key_per_range_limit) {
  7945. break;
  7946. }
  7947. }
  7948. ASSERT_OK(iter->status());
  7949. ASSERT_EQ(key_count, read_key_per_range_limit);
  7950. }
  7951. iter.reset();
  7952. ASSERT_OK(db->DestroyColumnFamilyHandle(cfh));
  7953. ASSERT_OK(db->Close());
  7954. ASSERT_OK(DestroyDB(dbname, options_));
  7955. }
  7956. INSTANTIATE_TEST_CASE_P(UserDefinedIndexTest, UserDefinedIndexTest,
  7957. ::testing::Values(BytewiseComparator(),
  7958. ReverseBytewiseComparator()));
  7959. struct UserDefinedIndexStressTestParam {
  7960. const Comparator* comparator;
  7961. bool enable_udi;
  7962. bool enable_compaction_with_sst_partitioner;
  7963. using UserDefinedIndexStressTestTuple =
  7964. std::tuple<const Comparator*, bool, bool>;
  7965. UserDefinedIndexStressTestParam(const UserDefinedIndexStressTestTuple& tuple)
  7966. : comparator(std::get<0>(tuple)),
  7967. enable_udi(std::get<1>(tuple)),
  7968. enable_compaction_with_sst_partitioner(std::get<2>(tuple)) {}
  7969. };
  7970. std::ostream& operator<<(std::ostream& os,
  7971. const UserDefinedIndexStressTestParam& param) {
  7972. return os << "UserDefinedIndexStressTestParam{comparator="
  7973. << (param.comparator ? param.comparator->Name() : "nullptr")
  7974. << ", enable_udi=" << param.enable_udi
  7975. << ", enable_compaction_with_sst_partitioner="
  7976. << param.enable_compaction_with_sst_partitioner << "}";
  7977. }
  7978. struct DataRange {
  7979. size_t start; // inclusive
  7980. size_t end; // exclusive
  7981. std::string value;
  7982. bool is_range_delete;
  7983. bool skipped;
  7984. size_t scan_key_count_limit;
  7985. std::string start_key;
  7986. std::string end_key;
  7987. // print the range in human readable format
  7988. std::string ToString() const {
  7989. std::ostringstream oss;
  7990. oss << "[" << start << ", " << end << "), value: " << value
  7991. << ", is_range_delete: " << is_range_delete << ", skipped: " << skipped
  7992. << ", scan_key_count_limit: " << scan_key_count_limit
  7993. << ", start_key: " << start_key << ", end_key: " << end_key;
  7994. return oss.str();
  7995. }
  7996. };
  7997. class UserDefinedIndexStressTest
  7998. : public UserDefinedIndexTestBase,
  7999. public testing::WithParamInterface<
  8000. UserDefinedIndexStressTestParam::UserDefinedIndexStressTestTuple> {
  8001. public:
  8002. void SetUp() override {
  8003. rand_seed_ = static_cast<uint32_t>(
  8004. std::chrono::duration_cast<std::chrono::nanoseconds>(
  8005. std::chrono::system_clock::now().time_since_epoch())
  8006. .count());
  8007. std::cout << "Random seed: " << rand_seed_ << std::endl;
  8008. rnd = Random(rand_seed_);
  8009. UserDefinedIndexStressTestParam param = GetParam();
  8010. comparator_ = param.comparator;
  8011. enable_udi_ = param.enable_udi;
  8012. enable_compaction_with_sst_partitioner_ =
  8013. param.enable_compaction_with_sst_partitioner;
  8014. options_.comparator = comparator_;
  8015. is_reverse_comparator_ = comparator_ == ReverseBytewiseComparator();
  8016. options_.compaction_style = kCompactionStyleUniversal;
  8017. // Set up custom flush block policy that flushes every 3 keys
  8018. table_options_.flush_block_policy_factory =
  8019. std::make_shared<CustomFlushBlockPolicyFactory>();
  8020. options_.table_factory.reset(NewBlockBasedTableFactory(table_options_));
  8021. }
  8022. void TearDown() override {
  8023. ASSERT_OK(db_->DestroyColumnFamilyHandle(ingest_cfh_));
  8024. ASSERT_OK(db_->DestroyColumnFamilyHandle(regular_cfh_));
  8025. ASSERT_OK(db_->Close());
  8026. ASSERT_OK(DestroyDB(dbname_, options_));
  8027. }
  8028. protected:
  8029. static constexpr auto kKeyRange = 100;
  8030. bool enable_udi_{};
  8031. bool enable_compaction_with_sst_partitioner_{};
  8032. uint32_t rand_seed_{};
  8033. std::shared_ptr<UserDefinedIndexFactory> user_defined_index_factory_;
  8034. BlockBasedTableOptions table_options_;
  8035. const Comparator* comparator_{};
  8036. bool is_reverse_comparator_{};
  8037. Random rnd{0};
  8038. ColumnFamilyHandle* ingest_cfh_ = nullptr;
  8039. ColumnFamilyHandle* regular_cfh_ = nullptr;
  8040. std::unique_ptr<DB> db_;
  8041. std::vector<std::vector<DataRange>> ranges_in_levels_;
  8042. std::string dbname_;
  8043. void SetupDB(const std::string& dbname) {
  8044. options_.create_if_missing = true;
  8045. options_.disable_auto_compactions = true;
  8046. Status s = DB::Open(options_, dbname, &db_);
  8047. ASSERT_OK(s);
  8048. ASSERT_TRUE(db_ != nullptr);
  8049. if (enable_compaction_with_sst_partitioner_) {
  8050. // Use a SST partitioner to create multiple files, use the first 4 bytes
  8051. // of key to partition the file, The key is formatted with 2 digit
  8052. // following "key" string, e.g. key01, key99
  8053. options_.sst_partitioner_factory = NewSstPartitionerFixedPrefixFactory(4);
  8054. }
  8055. ASSERT_OK(db_->CreateColumnFamily(options_, "regular_cf", &regular_cfh_));
  8056. if (enable_udi_) {
  8057. // Set up the user-defined index factory
  8058. user_defined_index_factory_ =
  8059. std::make_shared<TestUserDefinedIndexFactory>();
  8060. table_options_.user_defined_index_factory = user_defined_index_factory_;
  8061. }
  8062. options_.table_factory.reset(NewBlockBasedTableFactory(table_options_));
  8063. ASSERT_OK(db_->CreateColumnFamily(options_, "ingest_cf", &ingest_cfh_));
  8064. }
  8065. template <typename T>
  8066. std::string FormatKey(T i) {
  8067. std::stringstream ss;
  8068. ss << std::setw(2) << std::setfill('0') << i;
  8069. return "key" + ss.str();
  8070. }
  8071. std::vector<DataRange> GenerateKeyRanges(size_t range_count,
  8072. int skip_range_count,
  8073. const std::string& value) {
  8074. std::set<size_t> boundaries;
  8075. // generate n + 1 number of unique boundaries to form n contiguoes ranges
  8076. while (boundaries.size() < range_count + 1) {
  8077. boundaries.insert(rnd.Uniform(kKeyRange));
  8078. }
  8079. std::vector<size_t> sorted_boundaries(boundaries.begin(), boundaries.end());
  8080. if (is_reverse_comparator_) {
  8081. std::reverse(sorted_boundaries.begin(), sorted_boundaries.end());
  8082. }
  8083. auto ranges = std::vector<DataRange>();
  8084. std::optional<size_t> prev_bound;
  8085. for (auto it = sorted_boundaries.begin(); it != sorted_boundaries.end();
  8086. it++) {
  8087. if (prev_bound.has_value()) {
  8088. ranges.push_back({.start = prev_bound.value(),
  8089. .end = *it,
  8090. .value = value,
  8091. .is_range_delete = rnd.OneIn(6),
  8092. .skipped = false,
  8093. .scan_key_count_limit = rnd.Uniform(10) + 1,
  8094. .start_key = FormatKey(prev_bound.value()),
  8095. .end_key = FormatKey(*it)});
  8096. }
  8097. prev_bound = *it;
  8098. }
  8099. // skipped some of them
  8100. for (int j = 0; j < skip_range_count; j++) {
  8101. ranges[rnd.Uniform(static_cast<uint32_t>(range_count))].skipped = true;
  8102. }
  8103. if (kVerbose) {
  8104. for (auto const& range : ranges) {
  8105. std::cout << range.ToString() << std::endl;
  8106. }
  8107. }
  8108. return ranges;
  8109. }
  8110. void CreateSstFileWithRanges(const std::string& ingest_file,
  8111. const std::vector<DataRange>& ranges,
  8112. bool& data_added) {
  8113. std::unique_ptr<SstFileWriter> writer;
  8114. data_added = false;
  8115. std::vector<DataRange> ranges_in_file;
  8116. for (auto const& range : ranges) {
  8117. assert(range.start != range.end);
  8118. if (range.skipped) {
  8119. continue;
  8120. }
  8121. if (writer == nullptr) {
  8122. // lazy create writer until there is data to be written to avoid
  8123. // unchecked status error
  8124. writer = std::make_unique<SstFileWriter>(EnvOptions(), options_);
  8125. ASSERT_OK(writer->Open(ingest_file));
  8126. }
  8127. ranges_in_file.push_back(range);
  8128. data_added = true;
  8129. if (range.is_range_delete) {
  8130. ASSERT_OK(writer->DeleteRange(range.start_key, range.end_key));
  8131. } else {
  8132. for (size_t i = range.start; i != range.end;) {
  8133. auto key = FormatKey(i);
  8134. range.start < range.end ? i++ : i--;
  8135. ASSERT_OK(writer->Put(key, range.value));
  8136. }
  8137. }
  8138. }
  8139. if (kVerbose) {
  8140. std::cout << "Ingested file: " + ingest_file + "; Range: {" << std::endl;
  8141. for (const auto& range : ranges_in_file) {
  8142. std::cout << " " << range.ToString() << "," << std::endl;
  8143. }
  8144. std::cout << "}" << std::endl;
  8145. }
  8146. if (data_added) {
  8147. ASSERT_OK(writer->Finish());
  8148. }
  8149. }
  8150. void RangeScan(std::unique_ptr<Iterator>& iter,
  8151. const std::vector<DataRange>& ranges, Slice& upper_bound,
  8152. std::vector<std::pair<std::string, std::string>>& result,
  8153. bool use_multi_scan) {
  8154. ASSERT_NE(iter, nullptr);
  8155. ASSERT_OK(iter->status());
  8156. ASSERT_TRUE(!ranges.empty());
  8157. MultiScanArgs scan_opts(options_.comparator);
  8158. std::unordered_map<std::string, std::string> property_bag;
  8159. if (use_multi_scan) {
  8160. for (auto const& range : ranges) {
  8161. if (range.skipped) {
  8162. continue;
  8163. }
  8164. property_bag["count"] = std::to_string(range.scan_key_count_limit);
  8165. scan_opts.insert(range.start_key, range.end_key, property_bag);
  8166. // print range start end key
  8167. if (kVerbose) {
  8168. std::cout << "range start " << range.start_key << " end "
  8169. << range.end_key << std::endl;
  8170. }
  8171. }
  8172. iter->Prepare(scan_opts);
  8173. ASSERT_OK(iter->status());
  8174. }
  8175. for (auto const& range : ranges) {
  8176. if (range.skipped) {
  8177. continue;
  8178. }
  8179. size_t scan_key_count = 0;
  8180. if (kVerbose) {
  8181. std::cout << "seek key " << range.start_key << std::endl;
  8182. }
  8183. upper_bound = range.end_key;
  8184. for (iter->Seek(range.start_key);
  8185. iter->Valid() && scan_key_count < range.scan_key_count_limit;
  8186. iter->Next()) {
  8187. if (kVerbose) {
  8188. std::cout << "key " << iter->key().ToString() << " value "
  8189. << iter->value().ToString() << std::endl;
  8190. }
  8191. result.emplace_back(iter->key().ToString(), iter->value().ToString());
  8192. scan_key_count++;
  8193. }
  8194. ASSERT_OK(iter->status());
  8195. }
  8196. }
  8197. void AddDataToRegularCF() {
  8198. for (auto const& ranges_in_level : ranges_in_levels_) {
  8199. for (auto const& range : ranges_in_level) {
  8200. if (!range.skipped) {
  8201. for (auto i = range.start; i != range.end;
  8202. range.start < range.end ? i++ : i--) {
  8203. if (range.is_range_delete) {
  8204. ASSERT_OK(
  8205. db_->Delete(WriteOptions(), regular_cfh_, FormatKey(i)));
  8206. } else {
  8207. ASSERT_OK(db_->Put(WriteOptions(), regular_cfh_, FormatKey(i),
  8208. range.value));
  8209. }
  8210. }
  8211. }
  8212. }
  8213. }
  8214. ASSERT_OK(db_->Flush(FlushOptions(), regular_cfh_));
  8215. }
  8216. void ValidateQueryResult() {
  8217. // Query both CF with same range scan and validate result are same
  8218. for (auto i = 0; i < 200; i++) {
  8219. if (kVerbose) {
  8220. std::cout << "iteration " << i << std::endl;
  8221. }
  8222. SCOPED_TRACE("Iteration " + std::to_string(i));
  8223. // randomly generate 1 to 3 ranges
  8224. auto ranges = GenerateKeyRanges(rnd.Uniform(3) + 4, 2, "");
  8225. // Query regular CF
  8226. std::vector<std::pair<std::string, std::string>> expected_result;
  8227. Slice upper_bound("");
  8228. ReadOptions ro;
  8229. ro.iterate_upper_bound = &upper_bound;
  8230. std::unique_ptr<Iterator> iter(db_->NewIterator(ro, regular_cfh_));
  8231. ASSERT_NO_FATAL_FAILURE(
  8232. RangeScan(iter, ranges, upper_bound, expected_result, false));
  8233. ASSERT_OK(iter->status());
  8234. // Query ingest CF
  8235. iter.reset(db_->NewIterator(ro, ingest_cfh_));
  8236. std::vector<std::pair<std::string, std::string>> ingest_cf_result;
  8237. ASSERT_NO_FATAL_FAILURE(
  8238. RangeScan(iter, ranges, upper_bound, ingest_cf_result, false));
  8239. ASSERT_EQ(expected_result, ingest_cf_result);
  8240. ASSERT_OK(iter->status());
  8241. // Query ingest CF with UDI if it is enabled
  8242. if (enable_udi_) {
  8243. ro.table_index_factory = user_defined_index_factory_.get();
  8244. }
  8245. iter.reset(db_->NewIterator(ro, ingest_cfh_));
  8246. std::vector<std::pair<std::string, std::string>>
  8247. ingest_cf_multi_scan_result;
  8248. ASSERT_NO_FATAL_FAILURE(RangeScan(iter, ranges, upper_bound,
  8249. ingest_cf_multi_scan_result, true));
  8250. ASSERT_EQ(expected_result, ingest_cf_multi_scan_result);
  8251. ASSERT_OK(iter->status());
  8252. }
  8253. }
  8254. void IngestFilesInOneLevel(const std::vector<DataRange>& ranges_in_level,
  8255. const std::string& ingest_file_name_prefix,
  8256. size_t& ingest_file_count,
  8257. const IngestExternalFileOptions& ifo,
  8258. bool combine_ranges = false) {
  8259. // Generate SST file and bulk load them one level at a time
  8260. std::vector<std::string> ingest_files;
  8261. if (combine_ranges) {
  8262. size_t i = 0;
  8263. while (i < ranges_in_level.size()) {
  8264. // if combine ranges, generate 1 SST file that combines muliple ranges
  8265. // together
  8266. // Randomly combine ranges to SST file.
  8267. size_t batch_end_idx =
  8268. std::min(i + rnd.Uniform(3) + 2, ranges_in_level.size());
  8269. bool data_added = false;
  8270. ASSERT_NO_FATAL_FAILURE(CreateSstFileWithRanges(
  8271. ingest_file_name_prefix + std::to_string(ingest_file_count),
  8272. {ranges_in_level.begin() + i,
  8273. ranges_in_level.begin() + batch_end_idx},
  8274. data_added));
  8275. if (data_added) {
  8276. ingest_files.push_back(ingest_file_name_prefix +
  8277. std::to_string(ingest_file_count));
  8278. ingest_file_count++;
  8279. }
  8280. i = batch_end_idx;
  8281. }
  8282. } else {
  8283. for (auto const& range : ranges_in_level) {
  8284. if (!range.skipped) {
  8285. bool data_added = false;
  8286. ASSERT_NO_FATAL_FAILURE(CreateSstFileWithRanges(
  8287. ingest_file_name_prefix + std::to_string(ingest_file_count),
  8288. {range}, data_added));
  8289. ASSERT_TRUE(data_added);
  8290. ingest_files.push_back(ingest_file_name_prefix +
  8291. std::to_string(ingest_file_count));
  8292. ingest_file_count++;
  8293. }
  8294. }
  8295. }
  8296. ASSERT_OK(db_->IngestExternalFile(ingest_cfh_, ingest_files, ifo));
  8297. }
  8298. void IngestDataToCF() {
  8299. IngestExternalFileOptions ifo;
  8300. ifo.snapshot_consistency = false;
  8301. auto ingest_file_name_prefix = dbname_ + "ingest_file_";
  8302. size_t ingest_file_count = 0;
  8303. for (auto const& ranges_in_level : ranges_in_levels_) {
  8304. ASSERT_NO_FATAL_FAILURE(IngestFilesInOneLevel(
  8305. ranges_in_level, ingest_file_name_prefix, ingest_file_count, ifo));
  8306. }
  8307. ASSERT_GE(ingest_file_count, 0);
  8308. }
  8309. void CompactIngestedCF() {
  8310. auto s = db_->CompactRange(
  8311. {.exclusive_manual_compaction = true,
  8312. .bottommost_level_compaction = BottommostLevelCompaction::kForce},
  8313. ingest_cfh_, nullptr, nullptr);
  8314. ASSERT_OK(s);
  8315. }
  8316. };
  8317. TEST_P(UserDefinedIndexStressTest, PartialDeleteRange) {
  8318. // Create 2 column families. One use normal put/del, the other uses sst
  8319. // ingest Randomly generate multiple non overlapping range for multiple
  8320. // levels Range scan same range between the 2 CF and validate the result is
  8321. // same
  8322. SCOPED_TRACE("Start with random seed: " + std::to_string(rand_seed_));
  8323. dbname_ =
  8324. test::PerThreadDBPath("UserDefinedIndexStressTest_PartialDeleteRange");
  8325. SCOPED_TRACE("dbname: " + dbname_);
  8326. ASSERT_NO_FATAL_FAILURE(SetupDB(dbname_));
  8327. if (enable_udi_) {
  8328. // Skip UDI for now.
  8329. // The issue is that with UDI enabled, prepare might not prepare enough keys
  8330. // at lower level due to range delete from upper level.
  8331. // E.g. consider a LSM tree:
  8332. // L1: Data [0-1]
  8333. // L2: Delete Range [0-6]
  8334. // L3: Data [0-9]
  8335. // When multiscan queries range [0-9) with UDI count as 3, the L3 file
  8336. // will only prepare range [0-3). However, this range is masked out by upper
  8337. // layer delete range from [0-6] from L2. This causes query to only return
  8338. // [0,1], while [0,1,7] is the right result. Until prepare is able to
  8339. // preparing additional block supported, UDI is skipped.
  8340. return;
  8341. }
  8342. for (int i = 0; i < 5; i++) {
  8343. ranges_in_levels_.push_back(
  8344. GenerateKeyRanges(rnd.Uniform(3) + 4, 2,
  8345. "L" + std::to_string(options_.num_levels - 1 - i)));
  8346. }
  8347. ASSERT_NO_FATAL_FAILURE(IngestDataToCF());
  8348. if (enable_compaction_with_sst_partitioner_) {
  8349. ASSERT_NO_FATAL_FAILURE(CompactIngestedCF());
  8350. }
  8351. ASSERT_NO_FATAL_FAILURE(AddDataToRegularCF());
  8352. ASSERT_NO_FATAL_FAILURE(ValidateQueryResult());
  8353. }
  8354. TEST_P(UserDefinedIndexStressTest, DeleteRangeMixedWithDataFile) {
  8355. // Create 2 column families. One use normal put/del, the other uses sst
  8356. // ingest.
  8357. // Test the case where there are 3 levels, the middle level is a delete
  8358. // range file that span across the entire key space. The top and bottom level
  8359. // file have multiple files and each one has both data and delete range. Scan
  8360. // same range between the 2 CF and validate the result is same
  8361. SCOPED_TRACE("Start with random seed: " + std::to_string(rand_seed_));
  8362. dbname_ = test::PerThreadDBPath(
  8363. "UserDefinedIndexStressTest_DeleteRangeMixedWithDataFile");
  8364. SCOPED_TRACE("dbname: " + dbname_);
  8365. ASSERT_NO_FATAL_FAILURE(SetupDB(dbname_));
  8366. // Test 3 levels.
  8367. // Bottom level is mixed data with delete range.
  8368. ranges_in_levels_.push_back(GenerateKeyRanges(rnd.Uniform(3) + 6, 2, "L6"));
  8369. // Middle level delete range across entire key space.
  8370. if (is_reverse_comparator_) {
  8371. ranges_in_levels_.push_back({{.start = 100,
  8372. .end = 0,
  8373. .is_range_delete = true,
  8374. .skipped = false,
  8375. .start_key = "keyz",
  8376. .end_key = "key"}});
  8377. } else {
  8378. ranges_in_levels_.push_back({{.start = 0,
  8379. .end = 100,
  8380. .is_range_delete = true,
  8381. .skipped = false,
  8382. .start_key = "key",
  8383. .end_key = "keyz"}});
  8384. }
  8385. // Top level is mixed data with delete range.
  8386. ranges_in_levels_.push_back(GenerateKeyRanges(rnd.Uniform(3) + 6, 2, "L4"));
  8387. IngestExternalFileOptions ifo;
  8388. ifo.snapshot_consistency = false;
  8389. auto ingest_file_name_prefix = dbname_ + "ingest_file_";
  8390. size_t ingest_file_count = 0;
  8391. auto first_level = true;
  8392. for (auto const& ranges_in_level : ranges_in_levels_) {
  8393. ASSERT_NO_FATAL_FAILURE(
  8394. IngestFilesInOneLevel(ranges_in_level, ingest_file_name_prefix,
  8395. ingest_file_count, ifo, /*combine_ranges=*/true));
  8396. if (first_level) {
  8397. first_level = false;
  8398. if (enable_compaction_with_sst_partitioner_) {
  8399. // When compaction is enabled, do a compaction at the first level
  8400. ASSERT_NO_FATAL_FAILURE(CompactIngestedCF());
  8401. }
  8402. }
  8403. }
  8404. ASSERT_NO_FATAL_FAILURE(AddDataToRegularCF());
  8405. ASSERT_NO_FATAL_FAILURE(ValidateQueryResult());
  8406. }
  8407. TEST_P(UserDefinedIndexStressTest, DeleteRange) {
  8408. // Create 2 column families. One use normal put/del, the other uses sst
  8409. // ingest.
  8410. // Test the case where there are 3 levels, the middle level is a delete
  8411. // range file that span across the entire key space. Range scan same range
  8412. // between the 2 CF and validate the result is same
  8413. SCOPED_TRACE("Start with random seed: " + std::to_string(rand_seed_));
  8414. dbname_ = test::PerThreadDBPath("UserDefinedIndexStressTest_DeleteRange");
  8415. SCOPED_TRACE("dbname: " + dbname_);
  8416. ASSERT_NO_FATAL_FAILURE(SetupDB(dbname_));
  8417. // Test 3 levels.
  8418. // bottom level constains multiple files, each could have data or delete
  8419. // ranges or both.
  8420. ranges_in_levels_.push_back(GenerateKeyRanges(rnd.Uniform(3) + 4, 2, "L6"));
  8421. // middle level delete range across entire key space
  8422. if (is_reverse_comparator_) {
  8423. ranges_in_levels_.push_back({{.start = 100,
  8424. .end = 0,
  8425. .is_range_delete = true,
  8426. .skipped = false,
  8427. .start_key = "keyz",
  8428. .end_key = "key"}});
  8429. } else {
  8430. ranges_in_levels_.push_back({{.start = 0,
  8431. .end = 100,
  8432. .is_range_delete = true,
  8433. .skipped = false,
  8434. .start_key = "key",
  8435. .end_key = "keyz"}});
  8436. }
  8437. // Top level constains multiple files, each could have data or delete
  8438. // ranges or both.
  8439. ranges_in_levels_.push_back(GenerateKeyRanges(rnd.Uniform(3) + 4, 2, "L4"));
  8440. IngestExternalFileOptions ifo;
  8441. ifo.snapshot_consistency = false;
  8442. auto ingest_file_name_prefix = dbname_ + "ingest_file_";
  8443. size_t ingest_file_count = 0;
  8444. auto first_level = true;
  8445. for (auto const& ranges_in_level : ranges_in_levels_) {
  8446. ASSERT_NO_FATAL_FAILURE(IngestFilesInOneLevel(
  8447. ranges_in_level, ingest_file_name_prefix, ingest_file_count, ifo));
  8448. if (first_level) {
  8449. first_level = false;
  8450. if (enable_compaction_with_sst_partitioner_) {
  8451. // When compaction is enabled, do a compaction at the first level
  8452. ASSERT_NO_FATAL_FAILURE(CompactIngestedCF());
  8453. }
  8454. }
  8455. }
  8456. ASSERT_NO_FATAL_FAILURE(AddDataToRegularCF());
  8457. ASSERT_NO_FATAL_FAILURE(ValidateQueryResult());
  8458. }
  8459. TEST_P(UserDefinedIndexStressTest, AtomicReplaceBulkLoad) {
  8460. // Create 2 column families. One use normal put/del, the other uses SST
  8461. // ingest. The SST ingest uses atomic range replace.
  8462. SCOPED_TRACE("Start with random seed: " + std::to_string(rand_seed_));
  8463. dbname_ =
  8464. test::PerThreadDBPath("UserDefinedIndexStressTest_AtomicReplaceBulkLoad");
  8465. SCOPED_TRACE("dbname: " + dbname_);
  8466. ASSERT_NO_FATAL_FAILURE(SetupDB(dbname_));
  8467. // Test 3 levels.
  8468. // bottom level constains multiple files, each could have data or delete
  8469. // ranges or both.
  8470. ranges_in_levels_.push_back(GenerateKeyRanges(rnd.Uniform(3) + 4, 2, "L6"));
  8471. // middle level delete range across entire key space
  8472. if (is_reverse_comparator_) {
  8473. ranges_in_levels_.push_back({{.start = 100,
  8474. .end = 0,
  8475. .is_range_delete = true,
  8476. .skipped = false,
  8477. .start_key = "keyz",
  8478. .end_key = "key"}});
  8479. } else {
  8480. ranges_in_levels_.push_back({{.start = 0,
  8481. .end = 100,
  8482. .is_range_delete = true,
  8483. .skipped = false,
  8484. .start_key = "key",
  8485. .end_key = "keyz"}});
  8486. }
  8487. // Top level constains multiple files, each could have data or delete
  8488. // ranges or both.
  8489. ranges_in_levels_.push_back(GenerateKeyRanges(rnd.Uniform(3) + 4, 2, "L4"));
  8490. IngestExternalFileOptions ifo;
  8491. ifo.snapshot_consistency = false;
  8492. auto ingest_file_name_prefix = dbname_ + "ingest_file_";
  8493. size_t ingest_file_count = 0;
  8494. auto first_level = true;
  8495. for (auto const& ranges_in_level : ranges_in_levels_) {
  8496. ASSERT_NO_FATAL_FAILURE(IngestFilesInOneLevel(
  8497. ranges_in_level, ingest_file_name_prefix, ingest_file_count, ifo));
  8498. if (first_level) {
  8499. first_level = false;
  8500. if (enable_compaction_with_sst_partitioner_) {
  8501. // When compaction is enabled, do a compaction at the first level
  8502. ASSERT_NO_FATAL_FAILURE(CompactIngestedCF());
  8503. }
  8504. }
  8505. }
  8506. // Ingest the a new file with atomic replace with full key space, this layer
  8507. // is exactly same as the one at the top level
  8508. bool data_added;
  8509. ASSERT_NO_FATAL_FAILURE(CreateSstFileWithRanges(
  8510. ingest_file_name_prefix + std::to_string(++ingest_file_count),
  8511. ranges_in_levels_[2], data_added));
  8512. IngestExternalFileArg ingest_arg;
  8513. ingest_arg.column_family = ingest_cfh_;
  8514. ingest_arg.options = ifo;
  8515. ingest_arg.external_files.push_back(ingest_file_name_prefix +
  8516. std::to_string(ingest_file_count));
  8517. ingest_arg.atomic_replace_range = RangeOpt(nullptr, nullptr);
  8518. ASSERT_OK(db_->IngestExternalFiles(
  8519. std::vector<IngestExternalFileArg>({ingest_arg})));
  8520. ASSERT_NO_FATAL_FAILURE(AddDataToRegularCF());
  8521. ASSERT_NO_FATAL_FAILURE(ValidateQueryResult());
  8522. }
  8523. INSTANTIATE_TEST_CASE_P(
  8524. UserDefinedIndexStressTest, UserDefinedIndexStressTest,
  8525. testing::Combine(testing::Values(BytewiseComparator(),
  8526. ReverseBytewiseComparator()),
  8527. testing::Bool(), testing::Bool()));
  8528. } // namespace ROCKSDB_NAMESPACE
  8529. int main(int argc, char** argv) {
  8530. // Opt-in this whole test file
  8531. ROCKSDB_NAMESPACE::TEST_AllowUnsupportedFormatVersion() = true;
  8532. ROCKSDB_NAMESPACE::port::InstallStackTraceHandler();
  8533. ::testing::InitGoogleTest(&argc, argv);
  8534. return RUN_ALL_TESTS();
  8535. }