db_with_timestamp_basic_test.cc 177 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034
  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 "db/db_with_timestamp_test_util.h"
  10. #include "port/stack_trace.h"
  11. #include "rocksdb/perf_context.h"
  12. #include "rocksdb/utilities/debug.h"
  13. #include "table/block_based/block_based_table_reader.h"
  14. #include "table/block_based/block_builder.h"
  15. #include "test_util/sync_point.h"
  16. #include "test_util/testutil.h"
  17. #include "utilities/fault_injection_env.h"
  18. #include "utilities/merge_operators/string_append/stringappend2.h"
  19. namespace ROCKSDB_NAMESPACE {
  20. namespace {
  21. std::string EncodeAsUint64(uint64_t v) {
  22. std::string dst;
  23. PutFixed64(&dst, v);
  24. return dst;
  25. }
  26. } // namespace
  27. class DBBasicTestWithTimestamp : public DBBasicTestWithTimestampBase {
  28. public:
  29. DBBasicTestWithTimestamp()
  30. : DBBasicTestWithTimestampBase("db_basic_test_with_timestamp") {}
  31. };
  32. TEST_F(DBBasicTestWithTimestamp, SanityChecks) {
  33. Options options = CurrentOptions();
  34. options.env = env_;
  35. options.create_if_missing = true;
  36. options.avoid_flush_during_shutdown = true;
  37. options.merge_operator = MergeOperators::CreateStringAppendTESTOperator();
  38. DestroyAndReopen(options);
  39. Options options1 = CurrentOptions();
  40. options1.env = env_;
  41. options1.comparator = test::BytewiseComparatorWithU64TsWrapper();
  42. options1.merge_operator = MergeOperators::CreateStringAppendTESTOperator();
  43. assert(options1.comparator &&
  44. options1.comparator->timestamp_size() == sizeof(uint64_t));
  45. ColumnFamilyHandle* handle = nullptr;
  46. Status s = db_->CreateColumnFamily(options1, "data", &handle);
  47. ASSERT_OK(s);
  48. std::string dummy_ts(sizeof(uint64_t), '\0');
  49. // Perform timestamp operations on default cf.
  50. ASSERT_TRUE(
  51. db_->Put(WriteOptions(), "key", dummy_ts, "value").IsInvalidArgument());
  52. ASSERT_TRUE(db_->Merge(WriteOptions(), db_->DefaultColumnFamily(), "key",
  53. dummy_ts, "value")
  54. .IsInvalidArgument());
  55. ASSERT_TRUE(db_->Delete(WriteOptions(), "key", dummy_ts).IsInvalidArgument());
  56. ASSERT_TRUE(
  57. db_->SingleDelete(WriteOptions(), "key", dummy_ts).IsInvalidArgument());
  58. ASSERT_TRUE(db_->DeleteRange(WriteOptions(), db_->DefaultColumnFamily(),
  59. "begin_key", "end_key", dummy_ts)
  60. .IsInvalidArgument());
  61. // Perform non-timestamp operations on "data" cf.
  62. ASSERT_TRUE(
  63. db_->Put(WriteOptions(), handle, "key", "value").IsInvalidArgument());
  64. ASSERT_TRUE(db_->Delete(WriteOptions(), handle, "key").IsInvalidArgument());
  65. ASSERT_TRUE(
  66. db_->SingleDelete(WriteOptions(), handle, "key").IsInvalidArgument());
  67. ASSERT_TRUE(
  68. db_->Merge(WriteOptions(), handle, "key", "value").IsInvalidArgument());
  69. ASSERT_TRUE(db_->DeleteRange(WriteOptions(), handle, "begin_key", "end_key")
  70. .IsInvalidArgument());
  71. {
  72. WriteBatch wb;
  73. ASSERT_OK(wb.Put(handle, "key", "value"));
  74. ASSERT_TRUE(db_->Write(WriteOptions(), &wb).IsInvalidArgument());
  75. }
  76. {
  77. WriteBatch wb;
  78. ASSERT_OK(wb.Delete(handle, "key"));
  79. ASSERT_TRUE(db_->Write(WriteOptions(), &wb).IsInvalidArgument());
  80. }
  81. {
  82. WriteBatch wb;
  83. ASSERT_OK(wb.SingleDelete(handle, "key"));
  84. ASSERT_TRUE(db_->Write(WriteOptions(), &wb).IsInvalidArgument());
  85. }
  86. {
  87. WriteBatch wb;
  88. ASSERT_OK(wb.DeleteRange(handle, "begin_key", "end_key"));
  89. ASSERT_TRUE(db_->Write(WriteOptions(), &wb).IsInvalidArgument());
  90. }
  91. // Perform timestamp operations with timestamps of incorrect size.
  92. const std::string wrong_ts(sizeof(uint32_t), '\0');
  93. ASSERT_TRUE(db_->Put(WriteOptions(), handle, "key", wrong_ts, "value")
  94. .IsInvalidArgument());
  95. ASSERT_TRUE(db_->Merge(WriteOptions(), handle, "key", wrong_ts, "value")
  96. .IsInvalidArgument());
  97. ASSERT_TRUE(
  98. db_->Delete(WriteOptions(), handle, "key", wrong_ts).IsInvalidArgument());
  99. ASSERT_TRUE(db_->SingleDelete(WriteOptions(), handle, "key", wrong_ts)
  100. .IsInvalidArgument());
  101. ASSERT_TRUE(
  102. db_->DeleteRange(WriteOptions(), handle, "begin_key", "end_key", wrong_ts)
  103. .IsInvalidArgument());
  104. delete handle;
  105. }
  106. TEST_F(DBBasicTestWithTimestamp, MixedCfs) {
  107. Options options = CurrentOptions();
  108. options.env = env_;
  109. options.create_if_missing = true;
  110. options.avoid_flush_during_shutdown = true;
  111. DestroyAndReopen(options);
  112. Options options1 = CurrentOptions();
  113. options1.env = env_;
  114. const size_t kTimestampSize = Timestamp(0, 0).size();
  115. TestComparator test_cmp(kTimestampSize);
  116. options1.comparator = &test_cmp;
  117. ColumnFamilyHandle* handle = nullptr;
  118. Status s = db_->CreateColumnFamily(options1, "data", &handle);
  119. ASSERT_OK(s);
  120. WriteBatch wb;
  121. ASSERT_OK(wb.Put("a", "value"));
  122. ASSERT_OK(wb.Put(handle, "a", "value"));
  123. {
  124. std::string ts = Timestamp(1, 0);
  125. const auto ts_sz_func = [kTimestampSize, handle](uint32_t cf_id) {
  126. assert(handle);
  127. if (cf_id == 0) {
  128. return static_cast<size_t>(0);
  129. } else if (cf_id == handle->GetID()) {
  130. return kTimestampSize;
  131. } else {
  132. assert(false);
  133. return std::numeric_limits<size_t>::max();
  134. }
  135. };
  136. ASSERT_OK(wb.UpdateTimestamps(ts, ts_sz_func));
  137. ASSERT_OK(db_->Write(WriteOptions(), &wb));
  138. }
  139. const auto verify_db = [this](ColumnFamilyHandle* h, const std::string& key,
  140. const std::string& ts,
  141. const std::string& expected_value) {
  142. ASSERT_EQ(expected_value, Get(key));
  143. Slice read_ts_slice(ts);
  144. ReadOptions read_opts;
  145. read_opts.timestamp = &read_ts_slice;
  146. std::string value;
  147. ASSERT_OK(db_->Get(read_opts, h, key, &value));
  148. ASSERT_EQ(expected_value, value);
  149. };
  150. verify_db(handle, "a", Timestamp(1, 0), "value");
  151. delete handle;
  152. Close();
  153. std::vector<ColumnFamilyDescriptor> cf_descs;
  154. cf_descs.emplace_back(kDefaultColumnFamilyName, options);
  155. cf_descs.emplace_back("data", options1);
  156. options.create_if_missing = false;
  157. s = DB::Open(options, dbname_, cf_descs, &handles_, &db_);
  158. ASSERT_OK(s);
  159. verify_db(handles_[1], "a", Timestamp(1, 0), "value");
  160. Close();
  161. }
  162. TEST_F(DBBasicTestWithTimestamp, MultiGetMultipleCfs) {
  163. const size_t kTimestampSize = Timestamp(0, 0).size();
  164. TestComparator test_cmp(kTimestampSize);
  165. Options options = CurrentOptions();
  166. options.env = env_;
  167. options.create_if_missing = true;
  168. options.avoid_flush_during_shutdown = true;
  169. options.comparator = &test_cmp;
  170. DestroyAndReopen(options);
  171. Options options1 = CurrentOptions();
  172. options1.env = env_;
  173. options1.comparator = &test_cmp;
  174. ColumnFamilyHandle* handle = nullptr;
  175. Status s = db_->CreateColumnFamily(options1, "data", &handle);
  176. ASSERT_OK(s);
  177. std::string ts = Timestamp(1, 0);
  178. WriteBatch wb(0, 0, 0, kTimestampSize);
  179. ASSERT_OK(wb.Put("a", "value"));
  180. ASSERT_OK(wb.Put(handle, "a", "value"));
  181. const auto ts_sz_func = [kTimestampSize](uint32_t /*cf_id*/) {
  182. return kTimestampSize;
  183. };
  184. ASSERT_OK(wb.UpdateTimestamps(ts, ts_sz_func));
  185. ASSERT_OK(db_->Write(WriteOptions(), &wb));
  186. int num_keys = 2;
  187. std::vector<Slice> keys;
  188. std::vector<std::string> expected_values;
  189. for (int i = 0; i < num_keys; i++) {
  190. keys.push_back("a");
  191. expected_values.push_back("value");
  192. }
  193. std::vector<ColumnFamilyHandle*> handles;
  194. handles.push_back(db_->DefaultColumnFamily());
  195. handles.push_back(handle);
  196. {
  197. Slice read_ts_slice(ts);
  198. ReadOptions read_opts;
  199. read_opts.timestamp = &read_ts_slice;
  200. std::vector<PinnableSlice> values;
  201. values.resize(num_keys);
  202. std::vector<Status> statuses;
  203. statuses.resize(num_keys);
  204. std::vector<std::string> timestamps;
  205. timestamps.resize(num_keys);
  206. db_->MultiGet(read_opts, num_keys, handles.data(), keys.data(),
  207. values.data(), timestamps.data(), statuses.data());
  208. for (int i = 0; i < num_keys; i++) {
  209. ASSERT_OK(statuses[i]);
  210. ASSERT_EQ(expected_values[i], values[i].ToString());
  211. ASSERT_EQ(ts, timestamps[i]);
  212. }
  213. }
  214. delete handle;
  215. Close();
  216. }
  217. TEST_F(DBBasicTestWithTimestamp, CompactRangeWithSpecifiedRange) {
  218. Options options = CurrentOptions();
  219. options.env = env_;
  220. options.create_if_missing = true;
  221. const size_t kTimestampSize = Timestamp(0, 0).size();
  222. TestComparator test_cmp(kTimestampSize);
  223. options.comparator = &test_cmp;
  224. DestroyAndReopen(options);
  225. WriteOptions write_opts;
  226. std::string ts = Timestamp(1, 0);
  227. ASSERT_OK(db_->Put(write_opts, "foo1", ts, "bar"));
  228. ASSERT_OK(Flush());
  229. ASSERT_OK(db_->Put(write_opts, "foo2", ts, "bar"));
  230. ASSERT_OK(Flush());
  231. std::string start_str = "foo";
  232. std::string end_str = "foo2";
  233. Slice start(start_str), end(end_str);
  234. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &start, &end));
  235. Close();
  236. }
  237. TEST_F(DBBasicTestWithTimestamp, GcPreserveLatestVersionBelowFullHistoryLow) {
  238. Options options = CurrentOptions();
  239. options.env = env_;
  240. options.create_if_missing = true;
  241. const size_t kTimestampSize = Timestamp(0, 0).size();
  242. TestComparator test_cmp(kTimestampSize);
  243. options.comparator = &test_cmp;
  244. DestroyAndReopen(options);
  245. std::string ts_str = Timestamp(1, 0);
  246. WriteOptions wopts;
  247. ASSERT_OK(db_->Put(wopts, "k1", ts_str, "v1"));
  248. ASSERT_OK(db_->Put(wopts, "k2", ts_str, "v2"));
  249. ASSERT_OK(db_->Put(wopts, "k3", ts_str, "v3"));
  250. ts_str = Timestamp(2, 0);
  251. ASSERT_OK(db_->Delete(wopts, "k3", ts_str));
  252. ts_str = Timestamp(4, 0);
  253. ASSERT_OK(db_->Put(wopts, "k1", ts_str, "v5"));
  254. ts_str = Timestamp(5, 0);
  255. ASSERT_OK(
  256. db_->DeleteRange(wopts, db_->DefaultColumnFamily(), "k0", "k9", ts_str));
  257. ts_str = Timestamp(3, 0);
  258. Slice ts = ts_str;
  259. CompactRangeOptions cro;
  260. cro.full_history_ts_low = &ts;
  261. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  262. ASSERT_OK(Flush());
  263. ReadOptions ropts;
  264. ropts.timestamp = &ts;
  265. std::string value;
  266. Status s = db_->Get(ropts, "k1", &value);
  267. ASSERT_OK(s);
  268. ASSERT_EQ("v1", value);
  269. std::string key_ts;
  270. ASSERT_TRUE(db_->Get(ropts, "k3", &value, &key_ts).IsNotFound());
  271. ASSERT_EQ(Timestamp(2, 0), key_ts);
  272. ts_str = Timestamp(5, 0);
  273. ts = ts_str;
  274. ropts.timestamp = &ts;
  275. ASSERT_TRUE(db_->Get(ropts, "k2", &value, &key_ts).IsNotFound());
  276. ASSERT_EQ(Timestamp(5, 0), key_ts);
  277. ASSERT_TRUE(db_->Get(ropts, "k2", &value).IsNotFound());
  278. Close();
  279. }
  280. TEST_F(DBBasicTestWithTimestamp, UpdateFullHistoryTsLow) {
  281. Options options = CurrentOptions();
  282. options.env = env_;
  283. options.create_if_missing = true;
  284. const size_t kTimestampSize = Timestamp(0, 0).size();
  285. TestComparator test_cmp(kTimestampSize);
  286. options.comparator = &test_cmp;
  287. DestroyAndReopen(options);
  288. const std::string kKey = "test kKey";
  289. // Test set ts_low first and flush()
  290. int current_ts_low = 5;
  291. std::string ts_low_str = Timestamp(current_ts_low, 0);
  292. Slice ts_low = ts_low_str;
  293. CompactRangeOptions comp_opts;
  294. comp_opts.full_history_ts_low = &ts_low;
  295. comp_opts.bottommost_level_compaction = BottommostLevelCompaction::kForce;
  296. ASSERT_OK(db_->CompactRange(comp_opts, nullptr, nullptr));
  297. auto* cfd =
  298. static_cast_with_check<ColumnFamilyHandleImpl>(db_->DefaultColumnFamily())
  299. ->cfd();
  300. auto result_ts_low = cfd->GetFullHistoryTsLow();
  301. ASSERT_TRUE(test_cmp.CompareTimestamp(ts_low, result_ts_low) == 0);
  302. for (int i = 0; i < 10; i++) {
  303. WriteOptions write_opts;
  304. std::string ts = Timestamp(i, 0);
  305. ASSERT_OK(db_->Put(write_opts, kKey, ts, Key(i)));
  306. }
  307. ASSERT_OK(Flush());
  308. for (int i = 0; i < 10; i++) {
  309. ReadOptions read_opts;
  310. std::string ts_str = Timestamp(i, 0);
  311. Slice ts = ts_str;
  312. read_opts.timestamp = &ts;
  313. std::string value;
  314. Status status = db_->Get(read_opts, kKey, &value);
  315. if (i < current_ts_low) {
  316. ASSERT_TRUE(status.IsInvalidArgument());
  317. } else {
  318. ASSERT_OK(status);
  319. ASSERT_TRUE(value.compare(Key(i)) == 0);
  320. }
  321. }
  322. // Test set ts_low and then trigger compaction
  323. for (int i = 10; i < 20; i++) {
  324. WriteOptions write_opts;
  325. std::string ts = Timestamp(i, 0);
  326. ASSERT_OK(db_->Put(write_opts, kKey, ts, Key(i)));
  327. }
  328. ASSERT_OK(Flush());
  329. current_ts_low = 15;
  330. ts_low_str = Timestamp(current_ts_low, 0);
  331. ts_low = ts_low_str;
  332. comp_opts.full_history_ts_low = &ts_low;
  333. ASSERT_OK(db_->CompactRange(comp_opts, nullptr, nullptr));
  334. result_ts_low = cfd->GetFullHistoryTsLow();
  335. ASSERT_TRUE(test_cmp.CompareTimestamp(ts_low, result_ts_low) == 0);
  336. for (int i = current_ts_low; i < 20; i++) {
  337. ReadOptions read_opts;
  338. std::string ts_str = Timestamp(i, 0);
  339. Slice ts = ts_str;
  340. read_opts.timestamp = &ts;
  341. std::string value;
  342. Status status = db_->Get(read_opts, kKey, &value);
  343. ASSERT_OK(status);
  344. ASSERT_TRUE(value.compare(Key(i)) == 0);
  345. }
  346. // Test invalid compaction with range
  347. Slice start(kKey), end(kKey);
  348. Status s = db_->CompactRange(comp_opts, &start, &end);
  349. ASSERT_TRUE(s.IsInvalidArgument());
  350. s = db_->CompactRange(comp_opts, &start, nullptr);
  351. ASSERT_TRUE(s.IsInvalidArgument());
  352. s = db_->CompactRange(comp_opts, nullptr, &end);
  353. ASSERT_TRUE(s.IsInvalidArgument());
  354. // Test invalid compaction with the decreasing ts_low
  355. ts_low_str = Timestamp(current_ts_low - 1, 0);
  356. ts_low = ts_low_str;
  357. comp_opts.full_history_ts_low = &ts_low;
  358. s = db_->CompactRange(comp_opts, nullptr, nullptr);
  359. ASSERT_TRUE(s.IsInvalidArgument());
  360. Close();
  361. }
  362. TEST_F(DBBasicTestWithTimestamp, UpdateFullHistoryTsLowWithPublicAPI) {
  363. Options options = CurrentOptions();
  364. options.env = env_;
  365. options.create_if_missing = true;
  366. const size_t kTimestampSize = Timestamp(0, 0).size();
  367. TestComparator test_cmp(kTimestampSize);
  368. options.comparator = &test_cmp;
  369. DestroyAndReopen(options);
  370. std::string ts_low_str = Timestamp(9, 0);
  371. ASSERT_OK(
  372. db_->IncreaseFullHistoryTsLow(db_->DefaultColumnFamily(), ts_low_str));
  373. std::string result_ts_low;
  374. ASSERT_OK(db_->GetFullHistoryTsLow(nullptr, &result_ts_low));
  375. ASSERT_TRUE(test_cmp.CompareTimestamp(ts_low_str, result_ts_low) == 0);
  376. // test increase full_history_low backward
  377. std::string ts_low_str_back = Timestamp(8, 0);
  378. auto s = db_->IncreaseFullHistoryTsLow(db_->DefaultColumnFamily(),
  379. ts_low_str_back);
  380. ASSERT_EQ(s, Status::InvalidArgument());
  381. // test IncreaseFullHistoryTsLow with a timestamp whose length is longger
  382. // than the cf's timestamp size
  383. std::string ts_low_str_long(Timestamp(0, 0).size() + 1, 'a');
  384. s = db_->IncreaseFullHistoryTsLow(db_->DefaultColumnFamily(),
  385. ts_low_str_long);
  386. ASSERT_EQ(s, Status::InvalidArgument());
  387. // test IncreaseFullHistoryTsLow with a timestamp which is null
  388. std::string ts_low_str_null;
  389. s = db_->IncreaseFullHistoryTsLow(db_->DefaultColumnFamily(),
  390. ts_low_str_null);
  391. ASSERT_EQ(s, Status::InvalidArgument());
  392. // test IncreaseFullHistoryTsLow for a column family that does not enable
  393. // timestamp
  394. options.comparator = BytewiseComparator();
  395. DestroyAndReopen(options);
  396. ts_low_str = Timestamp(10, 0);
  397. s = db_->IncreaseFullHistoryTsLow(db_->DefaultColumnFamily(), ts_low_str);
  398. ASSERT_EQ(s, Status::InvalidArgument());
  399. // test GetFullHistoryTsLow for a column family that does not enable
  400. // timestamp
  401. std::string current_ts_low;
  402. s = db_->GetFullHistoryTsLow(db_->DefaultColumnFamily(), &current_ts_low);
  403. ASSERT_EQ(s, Status::InvalidArgument());
  404. Close();
  405. }
  406. TEST_F(DBBasicTestWithTimestamp, GetApproximateSizes) {
  407. Options options = CurrentOptions();
  408. options.write_buffer_size = 100000000; // Large write buffer
  409. options.compression = kNoCompression;
  410. options.create_if_missing = true;
  411. const size_t kTimestampSize = Timestamp(0, 0).size();
  412. TestComparator test_cmp(kTimestampSize);
  413. options.comparator = &test_cmp;
  414. DestroyAndReopen(options);
  415. auto default_cf = db_->DefaultColumnFamily();
  416. WriteOptions write_opts;
  417. std::string ts = Timestamp(1, 0);
  418. const int N = 128;
  419. Random rnd(301);
  420. for (int i = 0; i < N; i++) {
  421. ASSERT_OK(db_->Put(write_opts, Key(i), ts, rnd.RandomString(1024)));
  422. }
  423. uint64_t size;
  424. std::string start = Key(50);
  425. std::string end = Key(60);
  426. Range r(start, end);
  427. SizeApproximationOptions size_approx_options;
  428. size_approx_options.include_memtables = true;
  429. size_approx_options.include_files = true;
  430. ASSERT_OK(
  431. db_->GetApproximateSizes(size_approx_options, default_cf, &r, 1, &size));
  432. ASSERT_GT(size, 6000);
  433. ASSERT_LT(size, 204800);
  434. // test multiple ranges
  435. std::vector<Range> ranges;
  436. std::string start_tmp = Key(10);
  437. std::string end_tmp = Key(20);
  438. ranges.emplace_back(start_tmp, end_tmp);
  439. ranges.emplace_back(start, end);
  440. uint64_t range_sizes[2];
  441. ASSERT_OK(db_->GetApproximateSizes(size_approx_options, default_cf,
  442. ranges.data(), 2, range_sizes));
  443. ASSERT_EQ(range_sizes[1], size);
  444. // Zero if not including mem table
  445. ASSERT_OK(db_->GetApproximateSizes(&r, 1, &size));
  446. ASSERT_EQ(size, 0);
  447. start = Key(500);
  448. end = Key(600);
  449. r = Range(start, end);
  450. ASSERT_OK(
  451. db_->GetApproximateSizes(size_approx_options, default_cf, &r, 1, &size));
  452. ASSERT_EQ(size, 0);
  453. // Test range boundaries
  454. ASSERT_OK(db_->Put(write_opts, Key(1000), ts, rnd.RandomString(1024)));
  455. // Should include start key
  456. start = Key(1000);
  457. end = Key(1100);
  458. r = Range(start, end);
  459. ASSERT_OK(
  460. db_->GetApproximateSizes(size_approx_options, default_cf, &r, 1, &size));
  461. ASSERT_GT(size, 0);
  462. uint64_t total_mem_count;
  463. uint64_t total_mem_size;
  464. db_->GetApproximateMemTableStats(default_cf, r, &total_mem_count,
  465. &total_mem_size);
  466. ASSERT_GT(total_mem_count, 0);
  467. ASSERT_GT(total_mem_size, 0);
  468. // Should exclude end key
  469. start = Key(900);
  470. end = Key(1000);
  471. r = Range(start, end);
  472. ASSERT_OK(
  473. db_->GetApproximateSizes(size_approx_options, default_cf, &r, 1, &size));
  474. ASSERT_EQ(size, 0);
  475. Close();
  476. }
  477. TEST_F(DBBasicTestWithTimestamp, SimpleIterate) {
  478. const int kNumKeysPerFile = 128;
  479. const uint64_t kMaxKey = 1024;
  480. Options options = CurrentOptions();
  481. options.env = env_;
  482. options.create_if_missing = true;
  483. const size_t kTimestampSize = Timestamp(0, 0).size();
  484. TestComparator test_cmp(kTimestampSize);
  485. options.comparator = &test_cmp;
  486. options.memtable_factory.reset(
  487. test::NewSpecialSkipListFactory(kNumKeysPerFile));
  488. DestroyAndReopen(options);
  489. const std::vector<uint64_t> start_keys = {1, 0};
  490. const std::vector<std::string> write_timestamps = {Timestamp(1, 0),
  491. Timestamp(3, 0)};
  492. const std::vector<std::string> read_timestamps = {Timestamp(2, 0),
  493. Timestamp(4, 0)};
  494. for (size_t i = 0; i < write_timestamps.size(); ++i) {
  495. WriteOptions write_opts;
  496. for (uint64_t key = start_keys[i]; key <= kMaxKey; ++key) {
  497. Status s = db_->Put(write_opts, Key1(key), write_timestamps[i],
  498. "value" + std::to_string(i));
  499. ASSERT_OK(s);
  500. }
  501. }
  502. for (size_t i = 0; i < read_timestamps.size(); ++i) {
  503. ReadOptions read_opts;
  504. Slice read_ts = read_timestamps[i];
  505. read_opts.timestamp = &read_ts;
  506. std::unique_ptr<Iterator> it(db_->NewIterator(read_opts));
  507. int count = 0;
  508. uint64_t key = 0;
  509. // Forward iterate.
  510. for (it->Seek(Key1(0)), key = start_keys[i]; it->Valid();
  511. it->Next(), ++count, ++key) {
  512. CheckIterUserEntry(it.get(), Key1(key), kTypeValue,
  513. "value" + std::to_string(i), write_timestamps[i]);
  514. }
  515. size_t expected_count = kMaxKey - start_keys[i] + 1;
  516. ASSERT_EQ(expected_count, count);
  517. // Backward iterate.
  518. count = 0;
  519. for (it->SeekForPrev(Key1(kMaxKey)), key = kMaxKey; it->Valid();
  520. it->Prev(), ++count, --key) {
  521. CheckIterUserEntry(it.get(), Key1(key), kTypeValue,
  522. "value" + std::to_string(i), write_timestamps[i]);
  523. }
  524. ASSERT_OK(it->status());
  525. ASSERT_EQ(static_cast<size_t>(kMaxKey) - start_keys[i] + 1, count);
  526. // SeekToFirst()/SeekToLast() with lower/upper bounds.
  527. // Then iter with lower and upper bounds.
  528. uint64_t l = 0;
  529. uint64_t r = kMaxKey + 1;
  530. while (l < r) {
  531. std::string lb_str = Key1(l);
  532. Slice lb = lb_str;
  533. std::string ub_str = Key1(r);
  534. Slice ub = ub_str;
  535. read_opts.iterate_lower_bound = &lb;
  536. read_opts.iterate_upper_bound = &ub;
  537. it.reset(db_->NewIterator(read_opts));
  538. for (it->SeekToFirst(), key = std::max(l, start_keys[i]), count = 0;
  539. it->Valid(); it->Next(), ++key, ++count) {
  540. CheckIterUserEntry(it.get(), Key1(key), kTypeValue,
  541. "value" + std::to_string(i), write_timestamps[i]);
  542. }
  543. ASSERT_OK(it->status());
  544. ASSERT_EQ(r - std::max(l, start_keys[i]), count);
  545. for (it->SeekToLast(), key = std::min(r, kMaxKey + 1), count = 0;
  546. it->Valid(); it->Prev(), --key, ++count) {
  547. CheckIterUserEntry(it.get(), Key1(key - 1), kTypeValue,
  548. "value" + std::to_string(i), write_timestamps[i]);
  549. }
  550. ASSERT_OK(it->status());
  551. l += (kMaxKey / 100);
  552. r -= (kMaxKey / 100);
  553. }
  554. }
  555. Close();
  556. }
  557. TEST_F(DBBasicTestWithTimestamp, TrimHistoryTest) {
  558. Options options = CurrentOptions();
  559. options.env = env_;
  560. options.create_if_missing = true;
  561. const size_t kTimestampSize = Timestamp(0, 0).size();
  562. TestComparator test_cmp(kTimestampSize);
  563. options.comparator = &test_cmp;
  564. DestroyAndReopen(options);
  565. auto check_value_by_ts = [](DB* db, Slice key, std::string readTs,
  566. Status status, std::string checkValue,
  567. std::string expected_ts) {
  568. ReadOptions ropts;
  569. Slice ts = readTs;
  570. ropts.timestamp = &ts;
  571. std::string value;
  572. std::string key_ts;
  573. Status s = db->Get(ropts, key, &value, &key_ts);
  574. ASSERT_TRUE(s == status);
  575. if (s.ok()) {
  576. ASSERT_EQ(checkValue, value);
  577. }
  578. if (s.ok() || s.IsNotFound()) {
  579. ASSERT_EQ(expected_ts, key_ts);
  580. }
  581. };
  582. // Construct data of different versions with different ts
  583. ASSERT_OK(db_->Put(WriteOptions(), "k1", Timestamp(2, 0), "v1"));
  584. ASSERT_OK(db_->Put(WriteOptions(), "k1", Timestamp(4, 0), "v2"));
  585. ASSERT_OK(db_->Delete(WriteOptions(), "k1", Timestamp(5, 0)));
  586. ASSERT_OK(db_->Put(WriteOptions(), "k1", Timestamp(6, 0), "v3"));
  587. check_value_by_ts(db_, "k1", Timestamp(7, 0), Status::OK(), "v3",
  588. Timestamp(6, 0));
  589. ASSERT_OK(Flush());
  590. Close();
  591. ColumnFamilyOptions cf_options(options);
  592. std::vector<ColumnFamilyDescriptor> column_families;
  593. column_families.emplace_back(kDefaultColumnFamilyName, cf_options);
  594. DBOptions db_options(options);
  595. // Trim data whose version > Timestamp(5, 0), read(k1, ts(7)) <- NOT_FOUND.
  596. ASSERT_OK(DB::OpenAndTrimHistory(db_options, dbname_, column_families,
  597. &handles_, &db_, Timestamp(5, 0)));
  598. check_value_by_ts(db_, "k1", Timestamp(7, 0), Status::NotFound(), "",
  599. Timestamp(5, 0));
  600. Close();
  601. // Trim data whose timestamp > Timestamp(4, 0), read(k1, ts(7)) <- v2
  602. ASSERT_OK(DB::OpenAndTrimHistory(db_options, dbname_, column_families,
  603. &handles_, &db_, Timestamp(4, 0)));
  604. check_value_by_ts(db_, "k1", Timestamp(7, 0), Status::OK(), "v2",
  605. Timestamp(4, 0));
  606. Close();
  607. Reopen(options);
  608. ASSERT_OK(db_->DeleteRange(WriteOptions(), db_->DefaultColumnFamily(), "k1",
  609. "k3", Timestamp(7, 0)));
  610. check_value_by_ts(db_, "k1", Timestamp(8, 0), Status::NotFound(), "",
  611. Timestamp(7, 0));
  612. Close();
  613. // Trim data whose timestamp > Timestamp(6, 0), read(k1, ts(8)) <- v2
  614. ASSERT_OK(DB::OpenAndTrimHistory(db_options, dbname_, column_families,
  615. &handles_, &db_, Timestamp(6, 0)));
  616. check_value_by_ts(db_, "k1", Timestamp(8, 0), Status::OK(), "v2",
  617. Timestamp(4, 0));
  618. Close();
  619. }
  620. TEST_F(DBBasicTestWithTimestamp, OpenAndTrimHistoryInvalidOptionTest) {
  621. Destroy(last_options_);
  622. Options options = CurrentOptions();
  623. options.env = env_;
  624. options.create_if_missing = true;
  625. const size_t kTimestampSize = Timestamp(0, 0).size();
  626. TestComparator test_cmp(kTimestampSize);
  627. options.comparator = &test_cmp;
  628. ColumnFamilyOptions cf_options(options);
  629. std::vector<ColumnFamilyDescriptor> column_families;
  630. column_families.emplace_back(kDefaultColumnFamilyName, cf_options);
  631. DBOptions db_options(options);
  632. // OpenAndTrimHistory should not work with avoid_flush_during_recovery
  633. db_options.avoid_flush_during_recovery = true;
  634. ASSERT_TRUE(DB::OpenAndTrimHistory(db_options, dbname_, column_families,
  635. &handles_, &db_, Timestamp(0, 0))
  636. .IsInvalidArgument());
  637. }
  638. TEST_F(DBBasicTestWithTimestamp, GetTimestampTableProperties) {
  639. Options options = CurrentOptions();
  640. const size_t kTimestampSize = Timestamp(0, 0).size();
  641. TestComparator test_cmp(kTimestampSize);
  642. options.comparator = &test_cmp;
  643. DestroyAndReopen(options);
  644. // Create 2 tables
  645. for (int table = 0; table < 2; ++table) {
  646. for (int i = 0; i < 10; i++) {
  647. std::string ts = Timestamp(i, 0);
  648. ASSERT_OK(db_->Put(WriteOptions(), "key", ts, Key(i)));
  649. }
  650. ASSERT_OK(Flush());
  651. }
  652. TablePropertiesCollection props;
  653. ASSERT_OK(db_->GetPropertiesOfAllTables(&props));
  654. ASSERT_EQ(2U, props.size());
  655. for (const auto& item : props) {
  656. auto& user_collected = item.second->user_collected_properties;
  657. ASSERT_TRUE(user_collected.find("rocksdb.timestamp_min") !=
  658. user_collected.end());
  659. ASSERT_TRUE(user_collected.find("rocksdb.timestamp_max") !=
  660. user_collected.end());
  661. ASSERT_EQ(user_collected.at("rocksdb.timestamp_min"), Timestamp(0, 0));
  662. ASSERT_EQ(user_collected.at("rocksdb.timestamp_max"), Timestamp(9, 0));
  663. }
  664. Close();
  665. }
  666. class DBBasicTestWithTimestampTableOptions
  667. : public DBBasicTestWithTimestampBase,
  668. public testing::WithParamInterface<BlockBasedTableOptions::IndexType> {
  669. public:
  670. explicit DBBasicTestWithTimestampTableOptions()
  671. : DBBasicTestWithTimestampBase(
  672. "db_basic_test_with_timestamp_table_options") {}
  673. };
  674. INSTANTIATE_TEST_CASE_P(
  675. Timestamp, DBBasicTestWithTimestampTableOptions,
  676. testing::Values(
  677. BlockBasedTableOptions::IndexType::kBinarySearch,
  678. BlockBasedTableOptions::IndexType::kHashSearch,
  679. BlockBasedTableOptions::IndexType::kTwoLevelIndexSearch,
  680. BlockBasedTableOptions::IndexType::kBinarySearchWithFirstKey));
  681. TEST_P(DBBasicTestWithTimestampTableOptions, GetAndMultiGet) {
  682. Options options = GetDefaultOptions();
  683. options.create_if_missing = true;
  684. options.prefix_extractor.reset(NewFixedPrefixTransform(3));
  685. options.compression = kNoCompression;
  686. BlockBasedTableOptions bbto;
  687. bbto.index_type = GetParam();
  688. bbto.block_size = 100;
  689. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  690. const size_t kTimestampSize = Timestamp(0, 0).size();
  691. TestComparator cmp(kTimestampSize);
  692. options.comparator = &cmp;
  693. DestroyAndReopen(options);
  694. constexpr uint64_t kNumKeys = 1024;
  695. for (uint64_t k = 0; k < kNumKeys; ++k) {
  696. WriteOptions write_opts;
  697. ASSERT_OK(db_->Put(write_opts, Key1(k), Timestamp(1, 0),
  698. "value" + std::to_string(k)));
  699. }
  700. ASSERT_OK(Flush());
  701. {
  702. ReadOptions read_opts;
  703. read_opts.total_order_seek = true;
  704. std::string ts_str = Timestamp(2, 0);
  705. Slice ts = ts_str;
  706. read_opts.timestamp = &ts;
  707. std::unique_ptr<Iterator> it(db_->NewIterator(read_opts));
  708. // verify Get()
  709. for (it->SeekToFirst(); it->Valid(); it->Next()) {
  710. std::string value_from_get;
  711. std::string key_str(it->key().data(), it->key().size());
  712. std::string timestamp;
  713. ASSERT_OK(db_->Get(read_opts, key_str, &value_from_get, &timestamp));
  714. ASSERT_EQ(it->value(), value_from_get);
  715. ASSERT_EQ(Timestamp(1, 0), timestamp);
  716. }
  717. ASSERT_OK(it->status());
  718. // verify MultiGet()
  719. constexpr uint64_t step = 2;
  720. static_assert(0 == (kNumKeys % step),
  721. "kNumKeys must be a multiple of step");
  722. for (uint64_t k = 0; k < kNumKeys; k += 2) {
  723. std::vector<std::string> key_strs;
  724. std::vector<Slice> keys;
  725. for (size_t i = 0; i < step; ++i) {
  726. key_strs.push_back(Key1(k + i));
  727. }
  728. for (size_t i = 0; i < step; ++i) {
  729. keys.emplace_back(key_strs[i]);
  730. }
  731. std::vector<std::string> values;
  732. std::vector<std::string> timestamps;
  733. std::vector<Status> statuses =
  734. db_->MultiGet(read_opts, keys, &values, &timestamps);
  735. ASSERT_EQ(step, statuses.size());
  736. ASSERT_EQ(step, values.size());
  737. ASSERT_EQ(step, timestamps.size());
  738. for (uint64_t i = 0; i < step; ++i) {
  739. ASSERT_OK(statuses[i]);
  740. ASSERT_EQ("value" + std::to_string(k + i), values[i]);
  741. ASSERT_EQ(Timestamp(1, 0), timestamps[i]);
  742. }
  743. }
  744. }
  745. Close();
  746. }
  747. TEST_P(DBBasicTestWithTimestampTableOptions, SeekWithPrefixLessThanKey) {
  748. Options options = CurrentOptions();
  749. options.prefix_seek_opt_in_only = false; // Use legacy prefix seek
  750. options.env = env_;
  751. options.create_if_missing = true;
  752. options.prefix_extractor.reset(NewFixedPrefixTransform(3));
  753. options.memtable_whole_key_filtering = true;
  754. options.memtable_prefix_bloom_size_ratio = 0.1;
  755. BlockBasedTableOptions bbto;
  756. bbto.filter_policy.reset(NewBloomFilterPolicy(10, false));
  757. bbto.cache_index_and_filter_blocks = true;
  758. bbto.whole_key_filtering = true;
  759. bbto.index_type = GetParam();
  760. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  761. const size_t kTimestampSize = Timestamp(0, 0).size();
  762. TestComparator test_cmp(kTimestampSize);
  763. options.comparator = &test_cmp;
  764. DestroyAndReopen(options);
  765. WriteOptions write_opts;
  766. std::string ts = Timestamp(1, 0);
  767. ASSERT_OK(db_->Put(write_opts, "foo1", ts, "bar"));
  768. ASSERT_OK(Flush());
  769. ASSERT_OK(db_->Put(write_opts, "foo2", ts, "bar"));
  770. ASSERT_OK(Flush());
  771. // Move sst file to next level
  772. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  773. ASSERT_OK(db_->Put(write_opts, "foo3", ts, "bar"));
  774. ASSERT_OK(Flush());
  775. ReadOptions read_opts;
  776. Slice read_ts = ts;
  777. read_opts.timestamp = &read_ts;
  778. {
  779. std::unique_ptr<Iterator> iter(db_->NewIterator(read_opts));
  780. iter->Seek("foo");
  781. ASSERT_TRUE(iter->Valid());
  782. ASSERT_OK(iter->status());
  783. iter->Next();
  784. ASSERT_TRUE(iter->Valid());
  785. ASSERT_OK(iter->status());
  786. iter->Seek("bbb");
  787. ASSERT_FALSE(iter->Valid());
  788. ASSERT_OK(iter->status());
  789. }
  790. Close();
  791. }
  792. TEST_P(DBBasicTestWithTimestampTableOptions, SeekWithCappedPrefix) {
  793. Options options = CurrentOptions();
  794. options.env = env_;
  795. options.create_if_missing = true;
  796. // All of the keys or this test must be longer than 3 characters
  797. constexpr int kMinKeyLen = 3;
  798. options.prefix_extractor.reset(NewCappedPrefixTransform(kMinKeyLen));
  799. options.memtable_whole_key_filtering = true;
  800. options.memtable_prefix_bloom_size_ratio = 0.1;
  801. BlockBasedTableOptions bbto;
  802. bbto.filter_policy.reset(NewBloomFilterPolicy(10, false));
  803. bbto.cache_index_and_filter_blocks = true;
  804. bbto.whole_key_filtering = true;
  805. bbto.index_type = GetParam();
  806. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  807. const size_t kTimestampSize = Timestamp(0, 0).size();
  808. TestComparator test_cmp(kTimestampSize);
  809. options.comparator = &test_cmp;
  810. DestroyAndReopen(options);
  811. WriteOptions write_opts;
  812. std::string ts = Timestamp(1, 0);
  813. ASSERT_OK(db_->Put(write_opts, "foo1", ts, "bar"));
  814. ASSERT_OK(Flush());
  815. ASSERT_OK(db_->Put(write_opts, "foo2", ts, "bar"));
  816. ASSERT_OK(Flush());
  817. // Move sst file to next level
  818. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  819. ASSERT_OK(db_->Put(write_opts, "foo3", ts, "bar"));
  820. ASSERT_OK(Flush());
  821. ReadOptions read_opts;
  822. ts = Timestamp(2, 0);
  823. Slice read_ts = ts;
  824. read_opts.timestamp = &read_ts;
  825. {
  826. std::unique_ptr<Iterator> iter(db_->NewIterator(read_opts));
  827. // Make sure the prefix extractor doesn't include timestamp, otherwise it
  828. // may return invalid result.
  829. iter->Seek("foo");
  830. ASSERT_TRUE(iter->Valid());
  831. ASSERT_OK(iter->status());
  832. iter->Next();
  833. ASSERT_TRUE(iter->Valid());
  834. ASSERT_OK(iter->status());
  835. }
  836. Close();
  837. }
  838. TEST_P(DBBasicTestWithTimestampTableOptions, SeekWithBound) {
  839. Options options = CurrentOptions();
  840. options.env = env_;
  841. options.create_if_missing = true;
  842. options.prefix_extractor.reset(NewFixedPrefixTransform(2));
  843. BlockBasedTableOptions bbto;
  844. bbto.filter_policy.reset(NewBloomFilterPolicy(10, false));
  845. bbto.cache_index_and_filter_blocks = true;
  846. bbto.whole_key_filtering = true;
  847. bbto.index_type = GetParam();
  848. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  849. const size_t kTimestampSize = Timestamp(0, 0).size();
  850. TestComparator test_cmp(kTimestampSize);
  851. options.comparator = &test_cmp;
  852. DestroyAndReopen(options);
  853. WriteOptions write_opts;
  854. std::string ts = Timestamp(1, 0);
  855. ASSERT_OK(db_->Put(write_opts, "foo1", ts, "bar1"));
  856. ASSERT_OK(Flush());
  857. ASSERT_OK(db_->Put(write_opts, "foo2", ts, "bar2"));
  858. ASSERT_OK(Flush());
  859. // Move sst file to next level
  860. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  861. for (int i = 3; i < 9; ++i) {
  862. ASSERT_OK(db_->Put(write_opts, "foo" + std::to_string(i), ts,
  863. "bar" + std::to_string(i)));
  864. }
  865. ASSERT_OK(Flush());
  866. ReadOptions read_opts;
  867. ts = Timestamp(2, 0);
  868. Slice read_ts = ts;
  869. read_opts.timestamp = &read_ts;
  870. std::string up_bound = "foo5"; // exclusive
  871. Slice up_bound_slice = up_bound;
  872. std::string lo_bound = "foo2"; // inclusive
  873. Slice lo_bound_slice = lo_bound;
  874. read_opts.iterate_upper_bound = &up_bound_slice;
  875. read_opts.iterate_lower_bound = &lo_bound_slice;
  876. read_opts.auto_prefix_mode = true;
  877. {
  878. std::unique_ptr<Iterator> iter(db_->NewIterator(read_opts));
  879. // Make sure the prefix extractor doesn't include timestamp, otherwise it
  880. // may return invalid result.
  881. iter->Seek("foo");
  882. CheckIterUserEntry(iter.get(), lo_bound, kTypeValue, "bar2",
  883. Timestamp(1, 0));
  884. iter->SeekToFirst();
  885. CheckIterUserEntry(iter.get(), lo_bound, kTypeValue, "bar2",
  886. Timestamp(1, 0));
  887. iter->SeekForPrev("g");
  888. CheckIterUserEntry(iter.get(), "foo4", kTypeValue, "bar4", Timestamp(1, 0));
  889. iter->SeekToLast();
  890. CheckIterUserEntry(iter.get(), "foo4", kTypeValue, "bar4", Timestamp(1, 0));
  891. }
  892. Close();
  893. }
  894. TEST_F(DBBasicTestWithTimestamp, ChangeIterationDirection) {
  895. Options options = GetDefaultOptions();
  896. options.create_if_missing = true;
  897. options.env = env_;
  898. const size_t kTimestampSize = Timestamp(0, 0).size();
  899. TestComparator test_cmp(kTimestampSize);
  900. options.comparator = &test_cmp;
  901. options.prefix_extractor.reset(NewFixedPrefixTransform(1));
  902. options.prefix_seek_opt_in_only = false; // Use legacy prefix seek
  903. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  904. DestroyAndReopen(options);
  905. const std::vector<std::string> timestamps = {Timestamp(1, 1), Timestamp(0, 2),
  906. Timestamp(4, 3)};
  907. const std::vector<std::tuple<std::string, std::string>> kvs = {
  908. std::make_tuple("aa", "value1"), std::make_tuple("ab", "value2")};
  909. for (const auto& ts : timestamps) {
  910. WriteBatch wb(0, 0, 0, kTimestampSize);
  911. for (const auto& kv : kvs) {
  912. const std::string& key = std::get<0>(kv);
  913. const std::string& value = std::get<1>(kv);
  914. ASSERT_OK(wb.Put(key, value));
  915. }
  916. ASSERT_OK(wb.UpdateTimestamps(
  917. ts, [kTimestampSize](uint32_t) { return kTimestampSize; }));
  918. ASSERT_OK(db_->Write(WriteOptions(), &wb));
  919. }
  920. std::string read_ts_str = Timestamp(5, 3);
  921. Slice read_ts = read_ts_str;
  922. ReadOptions read_opts;
  923. read_opts.timestamp = &read_ts;
  924. std::unique_ptr<Iterator> it(db_->NewIterator(read_opts));
  925. it->SeekToFirst();
  926. ASSERT_TRUE(it->Valid());
  927. it->Prev();
  928. ASSERT_FALSE(it->Valid());
  929. it->SeekToLast();
  930. ASSERT_TRUE(it->Valid());
  931. uint64_t prev_reseek_count =
  932. options.statistics->getTickerCount(NUMBER_OF_RESEEKS_IN_ITERATION);
  933. ASSERT_EQ(0, prev_reseek_count);
  934. it->Next();
  935. ASSERT_FALSE(it->Valid());
  936. ASSERT_EQ(1 + prev_reseek_count,
  937. options.statistics->getTickerCount(NUMBER_OF_RESEEKS_IN_ITERATION));
  938. it->Seek(std::get<0>(kvs[0]));
  939. CheckIterUserEntry(it.get(), std::get<0>(kvs[0]), kTypeValue,
  940. std::get<1>(kvs[0]), Timestamp(4, 3));
  941. it->Next();
  942. CheckIterUserEntry(it.get(), std::get<0>(kvs[1]), kTypeValue,
  943. std::get<1>(kvs[1]), Timestamp(4, 3));
  944. it->Prev();
  945. CheckIterUserEntry(it.get(), std::get<0>(kvs[0]), kTypeValue,
  946. std::get<1>(kvs[0]), Timestamp(4, 3));
  947. prev_reseek_count =
  948. options.statistics->getTickerCount(NUMBER_OF_RESEEKS_IN_ITERATION);
  949. ASSERT_EQ(1, prev_reseek_count);
  950. it->Next();
  951. CheckIterUserEntry(it.get(), std::get<0>(kvs[1]), kTypeValue,
  952. std::get<1>(kvs[1]), Timestamp(4, 3));
  953. ASSERT_EQ(1 + prev_reseek_count,
  954. options.statistics->getTickerCount(NUMBER_OF_RESEEKS_IN_ITERATION));
  955. it->SeekForPrev(std::get<0>(kvs[1]));
  956. CheckIterUserEntry(it.get(), std::get<0>(kvs[1]), kTypeValue,
  957. std::get<1>(kvs[1]), Timestamp(4, 3));
  958. it->Prev();
  959. CheckIterUserEntry(it.get(), std::get<0>(kvs[0]), kTypeValue,
  960. std::get<1>(kvs[0]), Timestamp(4, 3));
  961. prev_reseek_count =
  962. options.statistics->getTickerCount(NUMBER_OF_RESEEKS_IN_ITERATION);
  963. it->Next();
  964. CheckIterUserEntry(it.get(), std::get<0>(kvs[1]), kTypeValue,
  965. std::get<1>(kvs[1]), Timestamp(4, 3));
  966. ASSERT_EQ(1 + prev_reseek_count,
  967. options.statistics->getTickerCount(NUMBER_OF_RESEEKS_IN_ITERATION));
  968. it.reset();
  969. Close();
  970. }
  971. TEST_F(DBBasicTestWithTimestamp, SimpleForwardIterateLowerTsBound) {
  972. constexpr int kNumKeysPerFile = 128;
  973. constexpr uint64_t kMaxKey = 1024;
  974. Options options = CurrentOptions();
  975. options.env = env_;
  976. options.create_if_missing = true;
  977. const size_t kTimestampSize = Timestamp(0, 0).size();
  978. TestComparator test_cmp(kTimestampSize);
  979. options.comparator = &test_cmp;
  980. options.memtable_factory.reset(
  981. test::NewSpecialSkipListFactory(kNumKeysPerFile));
  982. DestroyAndReopen(options);
  983. const std::vector<std::string> write_timestamps = {Timestamp(1, 0),
  984. Timestamp(3, 0)};
  985. const std::vector<std::string> read_timestamps = {Timestamp(2, 0),
  986. Timestamp(4, 0)};
  987. const std::vector<std::string> read_timestamps_lb = {Timestamp(1, 0),
  988. Timestamp(1, 0)};
  989. for (size_t i = 0; i < write_timestamps.size(); ++i) {
  990. WriteOptions write_opts;
  991. for (uint64_t key = 0; key <= kMaxKey; ++key) {
  992. Status s = db_->Put(write_opts, Key1(key), write_timestamps[i],
  993. "value" + std::to_string(i));
  994. ASSERT_OK(s);
  995. }
  996. }
  997. for (size_t i = 0; i < read_timestamps.size(); ++i) {
  998. ReadOptions read_opts;
  999. Slice read_ts = read_timestamps[i];
  1000. Slice read_ts_lb = read_timestamps_lb[i];
  1001. read_opts.timestamp = &read_ts;
  1002. read_opts.iter_start_ts = &read_ts_lb;
  1003. std::unique_ptr<Iterator> it(db_->NewIterator(read_opts));
  1004. int count = 0;
  1005. uint64_t key = 0;
  1006. for (it->Seek(Key1(0)), key = 0; it->Valid(); it->Next(), ++count, ++key) {
  1007. CheckIterEntry(it.get(), Key1(key), kTypeValue,
  1008. "value" + std::to_string(i), write_timestamps[i]);
  1009. if (i > 0) {
  1010. it->Next();
  1011. CheckIterEntry(it.get(), Key1(key), kTypeValue,
  1012. "value" + std::to_string(i - 1),
  1013. write_timestamps[i - 1]);
  1014. }
  1015. }
  1016. ASSERT_OK(it->status());
  1017. size_t expected_count = kMaxKey + 1;
  1018. ASSERT_EQ(expected_count, count);
  1019. }
  1020. // Delete all keys@ts=5 and check iteration result with start ts set
  1021. {
  1022. std::string write_timestamp = Timestamp(5, 0);
  1023. WriteOptions write_opts;
  1024. for (uint64_t key = 0; key < kMaxKey + 1; ++key) {
  1025. Status s = db_->Delete(write_opts, Key1(key), write_timestamp);
  1026. ASSERT_OK(s);
  1027. }
  1028. std::string read_timestamp = Timestamp(6, 0);
  1029. ReadOptions read_opts;
  1030. Slice read_ts = read_timestamp;
  1031. read_opts.timestamp = &read_ts;
  1032. std::string read_timestamp_lb = Timestamp(2, 0);
  1033. Slice read_ts_lb = read_timestamp_lb;
  1034. read_opts.iter_start_ts = &read_ts_lb;
  1035. std::unique_ptr<Iterator> it(db_->NewIterator(read_opts));
  1036. int count = 0;
  1037. uint64_t key = 0;
  1038. for (it->Seek(Key1(0)), key = 0; it->Valid(); it->Next(), ++count, ++key) {
  1039. CheckIterEntry(it.get(), Key1(key), kTypeDeletionWithTimestamp, Slice(),
  1040. write_timestamp);
  1041. // Skip key@ts=3 and land on tombstone key@ts=5
  1042. it->Next();
  1043. }
  1044. ASSERT_EQ(kMaxKey + 1, count);
  1045. }
  1046. Close();
  1047. }
  1048. TEST_F(DBBasicTestWithTimestamp, BackwardIterateLowerTsBound) {
  1049. constexpr int kNumKeysPerFile = 128;
  1050. constexpr uint64_t kMaxKey = 1024;
  1051. Options options = CurrentOptions();
  1052. options.env = env_;
  1053. options.create_if_missing = true;
  1054. const size_t kTimestampSize = Timestamp(0, 0).size();
  1055. TestComparator test_cmp(kTimestampSize);
  1056. options.comparator = &test_cmp;
  1057. options.memtable_factory.reset(
  1058. test::NewSpecialSkipListFactory(kNumKeysPerFile));
  1059. DestroyAndReopen(options);
  1060. const std::vector<std::string> write_timestamps = {Timestamp(1, 0),
  1061. Timestamp(3, 0)};
  1062. const std::vector<std::string> read_timestamps = {Timestamp(2, 0),
  1063. Timestamp(4, 0)};
  1064. const std::vector<std::string> read_timestamps_lb = {Timestamp(1, 0),
  1065. Timestamp(1, 0)};
  1066. for (size_t i = 0; i < write_timestamps.size(); ++i) {
  1067. WriteOptions write_opts;
  1068. for (uint64_t key = 0; key <= kMaxKey; ++key) {
  1069. Status s = db_->Put(write_opts, Key1(key), write_timestamps[i],
  1070. "value" + std::to_string(i));
  1071. ASSERT_OK(s);
  1072. }
  1073. }
  1074. for (size_t i = 0; i < read_timestamps.size(); ++i) {
  1075. ReadOptions read_opts;
  1076. Slice read_ts = read_timestamps[i];
  1077. Slice read_ts_lb = read_timestamps_lb[i];
  1078. read_opts.timestamp = &read_ts;
  1079. read_opts.iter_start_ts = &read_ts_lb;
  1080. std::unique_ptr<Iterator> it(db_->NewIterator(read_opts));
  1081. int count = 0;
  1082. uint64_t key = 0;
  1083. for (it->SeekForPrev(Key1(kMaxKey)), key = kMaxKey; it->Valid();
  1084. it->Prev(), ++count, --key) {
  1085. CheckIterEntry(it.get(), Key1(key), kTypeValue, "value0",
  1086. write_timestamps[0]);
  1087. if (i > 0) {
  1088. it->Prev();
  1089. CheckIterEntry(it.get(), Key1(key), kTypeValue, "value1",
  1090. write_timestamps[1]);
  1091. }
  1092. }
  1093. ASSERT_OK(it->status());
  1094. size_t expected_count = kMaxKey + 1;
  1095. ASSERT_EQ(expected_count, count);
  1096. }
  1097. // Delete all keys@ts=5 and check iteration result with start ts set
  1098. {
  1099. std::string write_timestamp = Timestamp(5, 0);
  1100. WriteOptions write_opts;
  1101. for (uint64_t key = 0; key < kMaxKey + 1; ++key) {
  1102. Status s = db_->Delete(write_opts, Key1(key), write_timestamp);
  1103. ASSERT_OK(s);
  1104. }
  1105. std::string read_timestamp = Timestamp(6, 0);
  1106. ReadOptions read_opts;
  1107. Slice read_ts = read_timestamp;
  1108. read_opts.timestamp = &read_ts;
  1109. std::string read_timestamp_lb = Timestamp(2, 0);
  1110. Slice read_ts_lb = read_timestamp_lb;
  1111. read_opts.iter_start_ts = &read_ts_lb;
  1112. std::unique_ptr<Iterator> it(db_->NewIterator(read_opts));
  1113. int count = 0;
  1114. uint64_t key = kMaxKey;
  1115. for (it->SeekForPrev(Key1(key)), key = kMaxKey; it->Valid();
  1116. it->Prev(), ++count, --key) {
  1117. CheckIterEntry(it.get(), Key1(key), kTypeValue, "value1",
  1118. Timestamp(3, 0));
  1119. it->Prev();
  1120. CheckIterEntry(it.get(), Key1(key), kTypeDeletionWithTimestamp, Slice(),
  1121. write_timestamp);
  1122. }
  1123. ASSERT_OK(it->status());
  1124. ASSERT_EQ(kMaxKey + 1, count);
  1125. }
  1126. Close();
  1127. }
  1128. TEST_F(DBBasicTestWithTimestamp, SimpleBackwardIterateLowerTsBound) {
  1129. Options options = CurrentOptions();
  1130. options.env = env_;
  1131. options.create_if_missing = true;
  1132. const size_t kTimestampSize = Timestamp(0, 0).size();
  1133. TestComparator test_cmp(kTimestampSize);
  1134. options.comparator = &test_cmp;
  1135. DestroyAndReopen(options);
  1136. std::string ts_ub_buf = Timestamp(5, 0);
  1137. Slice ts_ub = ts_ub_buf;
  1138. std::string ts_lb_buf = Timestamp(1, 0);
  1139. Slice ts_lb = ts_lb_buf;
  1140. {
  1141. ReadOptions read_opts;
  1142. read_opts.timestamp = &ts_ub;
  1143. read_opts.iter_start_ts = &ts_lb;
  1144. std::unique_ptr<Iterator> it(db_->NewIterator(read_opts));
  1145. it->SeekToLast();
  1146. ASSERT_FALSE(it->Valid());
  1147. ASSERT_OK(it->status());
  1148. it->SeekForPrev("foo");
  1149. ASSERT_FALSE(it->Valid());
  1150. ASSERT_OK(it->status());
  1151. }
  1152. // Test iterate_upper_bound
  1153. ASSERT_OK(db_->Put(WriteOptions(), "a", Timestamp(0, 0), "v0"));
  1154. ASSERT_OK(db_->SingleDelete(WriteOptions(), "a", Timestamp(1, 0)));
  1155. for (int i = 0; i < 5; ++i) {
  1156. ASSERT_OK(db_->Put(WriteOptions(), "b", Timestamp(i, 0),
  1157. "v" + std::to_string(i)));
  1158. }
  1159. {
  1160. ReadOptions read_opts;
  1161. read_opts.timestamp = &ts_ub;
  1162. read_opts.iter_start_ts = &ts_lb;
  1163. std::string key_ub_str = "b"; // exclusive
  1164. Slice key_ub = key_ub_str;
  1165. read_opts.iterate_upper_bound = &key_ub;
  1166. std::unique_ptr<Iterator> it(db_->NewIterator(read_opts));
  1167. it->SeekToLast();
  1168. CheckIterEntry(it.get(), "a", kTypeSingleDeletion, Slice(),
  1169. Timestamp(1, 0));
  1170. key_ub_str = "a"; // exclusive
  1171. key_ub = key_ub_str;
  1172. read_opts.iterate_upper_bound = &key_ub;
  1173. it.reset(db_->NewIterator(read_opts));
  1174. it->SeekToLast();
  1175. ASSERT_FALSE(it->Valid());
  1176. ASSERT_OK(it->status());
  1177. }
  1178. Close();
  1179. }
  1180. TEST_F(DBBasicTestWithTimestamp, BackwardIterateLowerTsBound_Reseek) {
  1181. Options options = CurrentOptions();
  1182. options.env = env_;
  1183. options.create_if_missing = true;
  1184. options.max_sequential_skip_in_iterations = 2;
  1185. const size_t kTimestampSize = Timestamp(0, 0).size();
  1186. TestComparator test_cmp(kTimestampSize);
  1187. options.comparator = &test_cmp;
  1188. DestroyAndReopen(options);
  1189. for (int i = 0; i < 10; ++i) {
  1190. ASSERT_OK(db_->Put(WriteOptions(), "a", Timestamp(i, 0),
  1191. "v" + std::to_string(i)));
  1192. }
  1193. for (int i = 0; i < 10; ++i) {
  1194. ASSERT_OK(db_->Put(WriteOptions(), "b", Timestamp(i, 0),
  1195. "v" + std::to_string(i)));
  1196. }
  1197. {
  1198. std::string ts_ub_buf = Timestamp(6, 0);
  1199. Slice ts_ub = ts_ub_buf;
  1200. std::string ts_lb_buf = Timestamp(4, 0);
  1201. Slice ts_lb = ts_lb_buf;
  1202. ReadOptions read_opts;
  1203. read_opts.timestamp = &ts_ub;
  1204. read_opts.iter_start_ts = &ts_lb;
  1205. std::unique_ptr<Iterator> it(db_->NewIterator(read_opts));
  1206. it->SeekToLast();
  1207. for (int i = 0; i < 3 && it->Valid(); it->Prev(), ++i) {
  1208. CheckIterEntry(it.get(), "b", kTypeValue, "v" + std::to_string(4 + i),
  1209. Timestamp(4 + i, 0));
  1210. }
  1211. for (int i = 0; i < 3 && it->Valid(); it->Prev(), ++i) {
  1212. CheckIterEntry(it.get(), "a", kTypeValue, "v" + std::to_string(4 + i),
  1213. Timestamp(4 + i, 0));
  1214. }
  1215. ASSERT_OK(it->status());
  1216. }
  1217. Close();
  1218. }
  1219. TEST_F(DBBasicTestWithTimestamp, ReseekToTargetTimestamp) {
  1220. Options options = CurrentOptions();
  1221. options.env = env_;
  1222. options.create_if_missing = true;
  1223. constexpr size_t kNumKeys = 16;
  1224. options.max_sequential_skip_in_iterations = kNumKeys / 2;
  1225. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  1226. const size_t kTimestampSize = Timestamp(0, 0).size();
  1227. TestComparator test_cmp(kTimestampSize);
  1228. options.comparator = &test_cmp;
  1229. DestroyAndReopen(options);
  1230. // Insert kNumKeys
  1231. WriteOptions write_opts;
  1232. Status s;
  1233. for (size_t i = 0; i != kNumKeys; ++i) {
  1234. std::string ts = Timestamp(static_cast<uint64_t>(i + 1), 0);
  1235. s = db_->Put(write_opts, "foo", ts, "value" + std::to_string(i));
  1236. ASSERT_OK(s);
  1237. }
  1238. {
  1239. ReadOptions read_opts;
  1240. std::string ts_str = Timestamp(1, 0);
  1241. Slice ts = ts_str;
  1242. read_opts.timestamp = &ts;
  1243. std::unique_ptr<Iterator> iter(db_->NewIterator(read_opts));
  1244. iter->SeekToFirst();
  1245. CheckIterUserEntry(iter.get(), "foo", kTypeValue, "value0", ts_str);
  1246. ASSERT_EQ(
  1247. 1, options.statistics->getTickerCount(NUMBER_OF_RESEEKS_IN_ITERATION));
  1248. ts_str = Timestamp(kNumKeys, 0);
  1249. ts = ts_str;
  1250. read_opts.timestamp = &ts;
  1251. iter.reset(db_->NewIterator(read_opts));
  1252. iter->SeekToLast();
  1253. CheckIterUserEntry(iter.get(), "foo", kTypeValue,
  1254. "value" + std::to_string(kNumKeys - 1), ts_str);
  1255. ASSERT_EQ(
  1256. 2, options.statistics->getTickerCount(NUMBER_OF_RESEEKS_IN_ITERATION));
  1257. }
  1258. Close();
  1259. }
  1260. TEST_F(DBBasicTestWithTimestamp, ReseekToNextUserKey) {
  1261. Options options = CurrentOptions();
  1262. options.env = env_;
  1263. options.create_if_missing = true;
  1264. constexpr size_t kNumKeys = 16;
  1265. options.max_sequential_skip_in_iterations = kNumKeys / 2;
  1266. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  1267. const size_t kTimestampSize = Timestamp(0, 0).size();
  1268. TestComparator test_cmp(kTimestampSize);
  1269. options.comparator = &test_cmp;
  1270. DestroyAndReopen(options);
  1271. // Write kNumKeys + 1 keys
  1272. WriteOptions write_opts;
  1273. Status s;
  1274. for (size_t i = 0; i != kNumKeys; ++i) {
  1275. std::string ts = Timestamp(static_cast<uint64_t>(i + 1), 0);
  1276. s = db_->Put(write_opts, "a", ts, "value" + std::to_string(i));
  1277. ASSERT_OK(s);
  1278. }
  1279. {
  1280. std::string ts_str = Timestamp(static_cast<uint64_t>(kNumKeys + 1), 0);
  1281. WriteBatch batch(0, 0, 0, kTimestampSize);
  1282. { ASSERT_OK(batch.Put("a", "new_value")); }
  1283. { ASSERT_OK(batch.Put("b", "new_value")); }
  1284. s = batch.UpdateTimestamps(
  1285. ts_str, [kTimestampSize](uint32_t) { return kTimestampSize; });
  1286. ASSERT_OK(s);
  1287. s = db_->Write(write_opts, &batch);
  1288. ASSERT_OK(s);
  1289. }
  1290. {
  1291. ReadOptions read_opts;
  1292. std::string ts_str = Timestamp(static_cast<uint64_t>(kNumKeys + 1), 0);
  1293. Slice ts = ts_str;
  1294. read_opts.timestamp = &ts;
  1295. std::unique_ptr<Iterator> iter(db_->NewIterator(read_opts));
  1296. iter->Seek("a");
  1297. iter->Next();
  1298. CheckIterUserEntry(iter.get(), "b", kTypeValue, "new_value", ts_str);
  1299. ASSERT_EQ(
  1300. 1, options.statistics->getTickerCount(NUMBER_OF_RESEEKS_IN_ITERATION));
  1301. }
  1302. Close();
  1303. }
  1304. TEST_F(DBBasicTestWithTimestamp, ReseekToUserKeyBeforeSavedKey) {
  1305. Options options = GetDefaultOptions();
  1306. options.env = env_;
  1307. options.create_if_missing = true;
  1308. constexpr size_t kNumKeys = 16;
  1309. options.max_sequential_skip_in_iterations = kNumKeys / 2;
  1310. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  1311. const size_t kTimestampSize = Timestamp(0, 0).size();
  1312. TestComparator test_cmp(kTimestampSize);
  1313. options.comparator = &test_cmp;
  1314. DestroyAndReopen(options);
  1315. for (size_t i = 0; i < kNumKeys; ++i) {
  1316. std::string ts = Timestamp(static_cast<uint64_t>(i + 1), 0);
  1317. WriteOptions write_opts;
  1318. Status s = db_->Put(write_opts, "b", ts, "value" + std::to_string(i));
  1319. ASSERT_OK(s);
  1320. }
  1321. {
  1322. std::string ts = Timestamp(1, 0);
  1323. WriteOptions write_opts;
  1324. ASSERT_OK(db_->Put(write_opts, "a", ts, "value"));
  1325. }
  1326. {
  1327. ReadOptions read_opts;
  1328. std::string ts_str = Timestamp(1, 0);
  1329. Slice ts = ts_str;
  1330. read_opts.timestamp = &ts;
  1331. std::unique_ptr<Iterator> iter(db_->NewIterator(read_opts));
  1332. iter->SeekToLast();
  1333. iter->Prev();
  1334. CheckIterUserEntry(iter.get(), "a", kTypeValue, "value", ts_str);
  1335. ASSERT_EQ(
  1336. 1, options.statistics->getTickerCount(NUMBER_OF_RESEEKS_IN_ITERATION));
  1337. }
  1338. Close();
  1339. }
  1340. class ReverseIterationWithUnpreparedBlobTest
  1341. : public DBBasicTestWithTimestampBase,
  1342. public testing::WithParamInterface<std::tuple<bool, uint64_t>> {
  1343. public:
  1344. ReverseIterationWithUnpreparedBlobTest()
  1345. : DBBasicTestWithTimestampBase(
  1346. "db_basic_test_with_timestamp_reverse_with_unprepare") {}
  1347. };
  1348. INSTANTIATE_TEST_CASE_P(ReverseIterationWithUnpreparedBlobTest,
  1349. ReverseIterationWithUnpreparedBlobTest,
  1350. ::testing::Combine(::testing::Values(true, false),
  1351. ::testing::Values(0, 2)));
  1352. TEST_P(ReverseIterationWithUnpreparedBlobTest, Basic) {
  1353. Options options = CurrentOptions();
  1354. options.create_if_missing = true;
  1355. options.env = env_;
  1356. options.enable_blob_files = true;
  1357. options.max_sequential_skip_in_iterations = std::get<1>(GetParam());
  1358. const size_t kTimestampSize = Timestamp(0, 0).size();
  1359. TestComparator test_cmp(kTimestampSize);
  1360. options.comparator = &test_cmp;
  1361. DestroyAndReopen(options);
  1362. constexpr uint64_t kMaxKey = 1024;
  1363. const std::vector<std::string> write_timestamps = {Timestamp(1, 0),
  1364. Timestamp(3, 0)};
  1365. for (uint64_t key = 0; key <= kMaxKey; ++key) {
  1366. for (size_t i = 0; i < write_timestamps.size(); ++i) {
  1367. ASSERT_OK(db_->Put(WriteOptions(), Key1(key), write_timestamps[i],
  1368. Key1(key) + "value" + std::to_string(i)));
  1369. }
  1370. }
  1371. ASSERT_OK(Flush());
  1372. {
  1373. const std::string read_timestamp_str = Timestamp(4, 0);
  1374. const Slice read_timestamp(read_timestamp_str);
  1375. ReadOptions read_opts;
  1376. read_opts.timestamp = &read_timestamp;
  1377. read_opts.allow_unprepared_value = std::get<0>(GetParam());
  1378. std::unique_ptr<Iterator> it(db_->NewIterator(read_opts));
  1379. it->SeekForPrev(Key1(kMaxKey));
  1380. uint64_t key = kMaxKey;
  1381. int count = 0;
  1382. while (it->Valid()) {
  1383. ASSERT_OK(it->status());
  1384. ASSERT_TRUE(it->PrepareValue());
  1385. ASSERT_TRUE(it->Valid());
  1386. ASSERT_OK(it->status());
  1387. ASSERT_EQ(it->key(), Key1(key));
  1388. ASSERT_EQ(it->timestamp(), Timestamp(3, 0));
  1389. ASSERT_EQ(it->value(), Key1(key) + "value" + std::to_string(1));
  1390. key--;
  1391. count++;
  1392. it->Prev();
  1393. }
  1394. ASSERT_OK(it->status());
  1395. ASSERT_EQ(kMaxKey + 1, count);
  1396. }
  1397. Close();
  1398. }
  1399. TEST_F(DBBasicTestWithTimestamp, MultiGetWithFastLocalBloom) {
  1400. Options options = CurrentOptions();
  1401. options.env = env_;
  1402. options.create_if_missing = true;
  1403. BlockBasedTableOptions bbto;
  1404. bbto.filter_policy.reset(NewBloomFilterPolicy(10, false));
  1405. bbto.cache_index_and_filter_blocks = true;
  1406. bbto.whole_key_filtering = true;
  1407. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  1408. const size_t kTimestampSize = Timestamp(0, 0).size();
  1409. TestComparator test_cmp(kTimestampSize);
  1410. options.comparator = &test_cmp;
  1411. DestroyAndReopen(options);
  1412. // Write any value
  1413. WriteOptions write_opts;
  1414. std::string ts = Timestamp(1, 0);
  1415. ASSERT_OK(db_->Put(write_opts, "foo", ts, "bar"));
  1416. ASSERT_OK(Flush());
  1417. // Read with MultiGet
  1418. ReadOptions read_opts;
  1419. Slice read_ts = ts;
  1420. read_opts.timestamp = &read_ts;
  1421. size_t batch_size = 1;
  1422. std::vector<Slice> keys(batch_size);
  1423. std::vector<PinnableSlice> values(batch_size);
  1424. std::vector<Status> statuses(batch_size);
  1425. std::vector<std::string> timestamps(batch_size);
  1426. keys[0] = "foo";
  1427. ColumnFamilyHandle* cfh = db_->DefaultColumnFamily();
  1428. db_->MultiGet(read_opts, cfh, batch_size, keys.data(), values.data(),
  1429. timestamps.data(), statuses.data(), true);
  1430. ASSERT_OK(statuses[0]);
  1431. ASSERT_EQ(Timestamp(1, 0), timestamps[0]);
  1432. for (auto& elem : values) {
  1433. elem.Reset();
  1434. }
  1435. ASSERT_OK(db_->SingleDelete(WriteOptions(), "foo", Timestamp(2, 0)));
  1436. ts = Timestamp(3, 0);
  1437. read_ts = ts;
  1438. read_opts.timestamp = &read_ts;
  1439. db_->MultiGet(read_opts, cfh, batch_size, keys.data(), values.data(),
  1440. timestamps.data(), statuses.data(), true);
  1441. ASSERT_TRUE(statuses[0].IsNotFound());
  1442. ASSERT_EQ(Timestamp(2, 0), timestamps[0]);
  1443. Close();
  1444. }
  1445. TEST_P(DBBasicTestWithTimestampTableOptions, MultiGetWithPrefix) {
  1446. Options options = CurrentOptions();
  1447. options.env = env_;
  1448. options.create_if_missing = true;
  1449. options.prefix_extractor.reset(NewCappedPrefixTransform(5));
  1450. BlockBasedTableOptions bbto;
  1451. bbto.filter_policy.reset(NewBloomFilterPolicy(10, false));
  1452. bbto.cache_index_and_filter_blocks = true;
  1453. bbto.whole_key_filtering = false;
  1454. bbto.index_type = GetParam();
  1455. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  1456. const size_t kTimestampSize = Timestamp(0, 0).size();
  1457. TestComparator test_cmp(kTimestampSize);
  1458. options.comparator = &test_cmp;
  1459. DestroyAndReopen(options);
  1460. // Write any value
  1461. WriteOptions write_opts;
  1462. std::string ts = Timestamp(1, 0);
  1463. ASSERT_OK(db_->Put(write_opts, "foo", ts, "bar"));
  1464. ASSERT_OK(Flush());
  1465. // Read with MultiGet
  1466. ReadOptions read_opts;
  1467. Slice read_ts = ts;
  1468. read_opts.timestamp = &read_ts;
  1469. size_t batch_size = 1;
  1470. std::vector<Slice> keys(batch_size);
  1471. std::vector<PinnableSlice> values(batch_size);
  1472. std::vector<Status> statuses(batch_size);
  1473. std::vector<std::string> timestamps(batch_size);
  1474. keys[0] = "foo";
  1475. ColumnFamilyHandle* cfh = db_->DefaultColumnFamily();
  1476. db_->MultiGet(read_opts, cfh, batch_size, keys.data(), values.data(),
  1477. timestamps.data(), statuses.data(), true);
  1478. ASSERT_OK(statuses[0]);
  1479. ASSERT_EQ(Timestamp(1, 0), timestamps[0]);
  1480. for (auto& elem : values) {
  1481. elem.Reset();
  1482. }
  1483. ASSERT_OK(db_->SingleDelete(WriteOptions(), "foo", Timestamp(2, 0)));
  1484. // TODO re-enable after fixing a bug of kHashSearch
  1485. if (GetParam() != BlockBasedTableOptions::IndexType::kHashSearch) {
  1486. ASSERT_OK(Flush());
  1487. }
  1488. ts = Timestamp(3, 0);
  1489. read_ts = ts;
  1490. db_->MultiGet(read_opts, cfh, batch_size, keys.data(), values.data(),
  1491. timestamps.data(), statuses.data(), true);
  1492. ASSERT_TRUE(statuses[0].IsNotFound());
  1493. ASSERT_EQ(Timestamp(2, 0), timestamps[0]);
  1494. Close();
  1495. }
  1496. TEST_P(DBBasicTestWithTimestampTableOptions, MultiGetWithMemBloomFilter) {
  1497. Options options = CurrentOptions();
  1498. options.env = env_;
  1499. options.create_if_missing = true;
  1500. options.prefix_extractor.reset(NewCappedPrefixTransform(5));
  1501. BlockBasedTableOptions bbto;
  1502. bbto.filter_policy.reset(NewBloomFilterPolicy(10, false));
  1503. bbto.cache_index_and_filter_blocks = true;
  1504. bbto.whole_key_filtering = false;
  1505. bbto.index_type = GetParam();
  1506. options.memtable_prefix_bloom_size_ratio = 0.1;
  1507. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  1508. const size_t kTimestampSize = Timestamp(0, 0).size();
  1509. TestComparator test_cmp(kTimestampSize);
  1510. options.comparator = &test_cmp;
  1511. DestroyAndReopen(options);
  1512. // Write any value
  1513. WriteOptions write_opts;
  1514. std::string ts = Timestamp(1, 0);
  1515. ASSERT_OK(db_->Put(write_opts, "foo", ts, "bar"));
  1516. // Read with MultiGet
  1517. ts = Timestamp(2, 0);
  1518. Slice read_ts = ts;
  1519. ReadOptions read_opts;
  1520. read_opts.timestamp = &read_ts;
  1521. size_t batch_size = 1;
  1522. std::vector<Slice> keys(batch_size);
  1523. std::vector<PinnableSlice> values(batch_size);
  1524. std::vector<Status> statuses(batch_size);
  1525. keys[0] = "foo";
  1526. ColumnFamilyHandle* cfh = db_->DefaultColumnFamily();
  1527. db_->MultiGet(read_opts, cfh, batch_size, keys.data(), values.data(),
  1528. statuses.data());
  1529. ASSERT_OK(statuses[0]);
  1530. Close();
  1531. }
  1532. TEST_F(DBBasicTestWithTimestamp, MultiGetRangeFiltering) {
  1533. Options options = CurrentOptions();
  1534. options.env = env_;
  1535. options.create_if_missing = true;
  1536. BlockBasedTableOptions bbto;
  1537. bbto.filter_policy.reset(NewBloomFilterPolicy(10, false));
  1538. bbto.cache_index_and_filter_blocks = true;
  1539. bbto.whole_key_filtering = false;
  1540. options.memtable_prefix_bloom_size_ratio = 0.1;
  1541. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  1542. const size_t kTimestampSize = Timestamp(0, 0).size();
  1543. TestComparator test_cmp(kTimestampSize);
  1544. options.comparator = &test_cmp;
  1545. DestroyAndReopen(options);
  1546. // Write any value
  1547. WriteOptions write_opts;
  1548. std::string ts = Timestamp(1, 0);
  1549. // random data
  1550. for (int i = 0; i < 3; i++) {
  1551. auto key = std::to_string(i * 10);
  1552. auto value = std::to_string(i * 10);
  1553. Slice key_slice = key;
  1554. Slice value_slice = value;
  1555. ASSERT_OK(db_->Put(write_opts, key_slice, ts, value_slice));
  1556. ASSERT_OK(Flush());
  1557. }
  1558. // Make num_levels to 2 to do key range filtering of sst files
  1559. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  1560. ASSERT_OK(db_->Put(write_opts, "foo", ts, "bar"));
  1561. ASSERT_OK(Flush());
  1562. // Read with MultiGet
  1563. ts = Timestamp(2, 0);
  1564. Slice read_ts = ts;
  1565. ReadOptions read_opts;
  1566. read_opts.timestamp = &read_ts;
  1567. size_t batch_size = 1;
  1568. std::vector<Slice> keys(batch_size);
  1569. std::vector<PinnableSlice> values(batch_size);
  1570. std::vector<Status> statuses(batch_size);
  1571. keys[0] = "foo";
  1572. ColumnFamilyHandle* cfh = db_->DefaultColumnFamily();
  1573. db_->MultiGet(read_opts, cfh, batch_size, keys.data(), values.data(),
  1574. statuses.data());
  1575. ASSERT_OK(statuses[0]);
  1576. Close();
  1577. }
  1578. TEST_F(DBBasicTestWithTimestamp, GetWithRowCache) {
  1579. Options options = CurrentOptions();
  1580. options.env = env_;
  1581. options.create_if_missing = true;
  1582. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  1583. LRUCacheOptions cache_options;
  1584. cache_options.capacity = 8192;
  1585. options.row_cache = cache_options.MakeSharedRowCache();
  1586. const size_t kTimestampSize = Timestamp(0, 0).size();
  1587. TestComparator test_cmp(kTimestampSize);
  1588. options.comparator = &test_cmp;
  1589. DestroyAndReopen(options);
  1590. WriteOptions write_opts;
  1591. std::string ts_early = Timestamp(1, 0);
  1592. std::string ts_later = Timestamp(10, 0);
  1593. Slice ts_later_slice = ts_later;
  1594. const Snapshot* snap_with_nothing = db_->GetSnapshot();
  1595. ASSERT_OK(db_->Put(write_opts, "foo", ts_early, "bar"));
  1596. ASSERT_OK(db_->Put(write_opts, "foo2", ts_early, "bar2"));
  1597. ASSERT_OK(db_->Put(write_opts, "foo3", ts_early, "bar3"));
  1598. const Snapshot* snap_with_foo = db_->GetSnapshot();
  1599. ASSERT_OK(Flush());
  1600. ReadOptions read_opts;
  1601. read_opts.timestamp = &ts_later_slice;
  1602. std::string read_value;
  1603. std::string read_ts;
  1604. Status s;
  1605. int expected_hit_count = 0;
  1606. int expected_miss_count = 0;
  1607. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), expected_hit_count);
  1608. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), expected_miss_count);
  1609. {
  1610. read_opts.timestamp = nullptr;
  1611. s = db_->Get(read_opts, "foo", &read_value);
  1612. ASSERT_NOK(s);
  1613. ASSERT_TRUE(s.IsInvalidArgument());
  1614. }
  1615. // Mix use of Get
  1616. {
  1617. read_opts.timestamp = &ts_later_slice;
  1618. // Use Get without ts first, expect cache entry to store the correct ts
  1619. s = db_->Get(read_opts, "foo2", &read_value);
  1620. ASSERT_OK(s);
  1621. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), expected_hit_count);
  1622. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS),
  1623. ++expected_miss_count);
  1624. ASSERT_EQ(read_value, "bar2");
  1625. s = db_->Get(read_opts, "foo2", &read_value, &read_ts);
  1626. ASSERT_OK(s);
  1627. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), ++expected_hit_count);
  1628. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), expected_miss_count);
  1629. ASSERT_EQ(read_ts, ts_early);
  1630. ASSERT_EQ(read_value, "bar2");
  1631. // Use Get with ts first, expect the Get without ts can get correct record
  1632. s = db_->Get(read_opts, "foo3", &read_value, &read_ts);
  1633. ASSERT_OK(s);
  1634. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), expected_hit_count);
  1635. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS),
  1636. ++expected_miss_count);
  1637. ASSERT_EQ(read_ts, ts_early);
  1638. ASSERT_EQ(read_value, "bar3");
  1639. s = db_->Get(read_opts, "foo3", &read_value);
  1640. ASSERT_OK(s);
  1641. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), ++expected_hit_count);
  1642. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), expected_miss_count);
  1643. ASSERT_EQ(read_value, "bar3");
  1644. }
  1645. {
  1646. // Test with consecutive calls of Get with ts.
  1647. s = db_->Get(read_opts, "foo", &read_value, &read_ts);
  1648. ASSERT_OK(s);
  1649. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), expected_hit_count);
  1650. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS),
  1651. ++expected_miss_count);
  1652. ASSERT_EQ(read_ts, ts_early);
  1653. ASSERT_EQ(read_value, "bar");
  1654. // Test repeated get on cache entry
  1655. for (int i = 0; i < 3; i++) {
  1656. s = db_->Get(read_opts, "foo", &read_value, &read_ts);
  1657. ASSERT_OK(s);
  1658. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT),
  1659. ++expected_hit_count);
  1660. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS),
  1661. expected_miss_count);
  1662. ASSERT_EQ(read_ts, ts_early);
  1663. ASSERT_EQ(read_value, "bar");
  1664. }
  1665. }
  1666. {
  1667. std::string ts_nothing = Timestamp(0, 0);
  1668. Slice ts_nothing_slice = ts_nothing;
  1669. read_opts.timestamp = &ts_nothing_slice;
  1670. s = db_->Get(read_opts, "foo", &read_value, &read_ts);
  1671. ASSERT_TRUE(s.IsNotFound());
  1672. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), expected_hit_count);
  1673. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS),
  1674. ++expected_miss_count);
  1675. }
  1676. {
  1677. read_opts.snapshot = snap_with_foo;
  1678. read_opts.timestamp = &ts_later_slice;
  1679. s = db_->Get(read_opts, "foo", &read_value, &read_ts);
  1680. ASSERT_OK(s);
  1681. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), expected_hit_count);
  1682. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS),
  1683. ++expected_miss_count);
  1684. ASSERT_EQ(read_ts, ts_early);
  1685. ASSERT_EQ(read_value, "bar");
  1686. s = db_->Get(read_opts, "foo", &read_value, &read_ts);
  1687. ASSERT_OK(s);
  1688. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), ++expected_hit_count);
  1689. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), expected_miss_count);
  1690. ASSERT_EQ(read_ts, ts_early);
  1691. ASSERT_EQ(read_value, "bar");
  1692. }
  1693. {
  1694. read_opts.snapshot = snap_with_nothing;
  1695. s = db_->Get(read_opts, "foo", &read_value, &read_ts);
  1696. ASSERT_TRUE(s.IsNotFound());
  1697. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), expected_hit_count);
  1698. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS),
  1699. ++expected_miss_count);
  1700. s = db_->Get(read_opts, "foo", &read_value, &read_ts);
  1701. ASSERT_TRUE(s.IsNotFound());
  1702. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), expected_hit_count);
  1703. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS),
  1704. ++expected_miss_count);
  1705. }
  1706. db_->ReleaseSnapshot(snap_with_nothing);
  1707. db_->ReleaseSnapshot(snap_with_foo);
  1708. Close();
  1709. }
  1710. TEST_F(DBBasicTestWithTimestamp, GetWithRowCacheMultiSST) {
  1711. BlockBasedTableOptions table_options;
  1712. table_options.block_size = 1;
  1713. Options options = CurrentOptions();
  1714. options.env = env_;
  1715. options.create_if_missing = true;
  1716. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  1717. LRUCacheOptions cache_options;
  1718. cache_options.capacity = 8192;
  1719. options.row_cache = cache_options.MakeSharedRowCache();
  1720. const size_t kTimestampSize = Timestamp(0, 0).size();
  1721. TestComparator test_cmp(kTimestampSize);
  1722. options.comparator = &test_cmp;
  1723. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1724. options.merge_operator = MergeOperators::CreateStringAppendTESTOperator();
  1725. options.disable_auto_compactions = true;
  1726. DestroyAndReopen(options);
  1727. std::string ts_early = Timestamp(1, 0);
  1728. std::string ts_later = Timestamp(10, 0);
  1729. Slice ts_later_slice = ts_later;
  1730. ASSERT_OK(db_->Put(WriteOptions(), "foo", ts_early, "v1"));
  1731. ASSERT_OK(Flush());
  1732. ColumnFamilyHandle* default_cf = db_->DefaultColumnFamily();
  1733. ASSERT_OK(
  1734. db_->Merge(WriteOptions(), default_cf, "foo", Timestamp(2, 0), "v2"));
  1735. ASSERT_OK(
  1736. db_->Merge(WriteOptions(), default_cf, "foo", Timestamp(3, 0), "v3"));
  1737. ASSERT_OK(Flush());
  1738. ReadOptions read_opts;
  1739. read_opts.timestamp = &ts_later_slice;
  1740. std::string read_value;
  1741. std::string read_ts;
  1742. Status s;
  1743. {
  1744. // Since there are two SST files, will trigger the table lookup twice.
  1745. s = db_->Get(read_opts, "foo", &read_value, &read_ts);
  1746. ASSERT_OK(s);
  1747. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), 0);
  1748. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 2);
  1749. ASSERT_EQ(read_ts, Timestamp(3, 0));
  1750. ASSERT_EQ(read_value, "v1,v2,v3");
  1751. s = db_->Get(read_opts, "foo", &read_value, &read_ts);
  1752. ASSERT_OK(s);
  1753. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_HIT), 2);
  1754. ASSERT_EQ(TestGetTickerCount(options, ROW_CACHE_MISS), 2);
  1755. ASSERT_EQ(read_ts, Timestamp(3, 0));
  1756. ASSERT_EQ(read_value, "v1,v2,v3");
  1757. }
  1758. }
  1759. TEST_P(DBBasicTestWithTimestampTableOptions, MultiGetPrefixFilter) {
  1760. Options options = CurrentOptions();
  1761. options.env = env_;
  1762. options.create_if_missing = true;
  1763. options.prefix_extractor.reset(NewCappedPrefixTransform(3));
  1764. BlockBasedTableOptions bbto;
  1765. bbto.filter_policy.reset(NewBloomFilterPolicy(10, false));
  1766. bbto.cache_index_and_filter_blocks = true;
  1767. bbto.whole_key_filtering = false;
  1768. bbto.index_type = GetParam();
  1769. options.memtable_prefix_bloom_size_ratio = 0.1;
  1770. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  1771. const size_t kTimestampSize = Timestamp(0, 0).size();
  1772. TestComparator test_cmp(kTimestampSize);
  1773. options.comparator = &test_cmp;
  1774. DestroyAndReopen(options);
  1775. WriteOptions write_opts;
  1776. std::string ts = Timestamp(1, 0);
  1777. ASSERT_OK(db_->Put(write_opts, "foo", ts, "bar"));
  1778. ASSERT_OK(Flush());
  1779. // Read with MultiGet
  1780. ts = Timestamp(2, 0);
  1781. Slice read_ts = ts;
  1782. ReadOptions read_opts;
  1783. read_opts.timestamp = &read_ts;
  1784. size_t batch_size = 1;
  1785. std::vector<Slice> keys(batch_size);
  1786. std::vector<std::string> values(batch_size);
  1787. std::vector<std::string> timestamps(batch_size);
  1788. keys[0] = "foo";
  1789. ColumnFamilyHandle* cfh = db_->DefaultColumnFamily();
  1790. std::vector<ColumnFamilyHandle*> cfhs(keys.size(), cfh);
  1791. std::vector<Status> statuses =
  1792. db_->MultiGet(read_opts, cfhs, keys, &values, &timestamps);
  1793. ASSERT_OK(statuses[0]);
  1794. Close();
  1795. }
  1796. TEST_F(DBBasicTestWithTimestamp, MaxKeysSkippedDuringNext) {
  1797. Options options = CurrentOptions();
  1798. options.env = env_;
  1799. options.create_if_missing = true;
  1800. const size_t kTimestampSize = Timestamp(0, 0).size();
  1801. TestComparator test_cmp(kTimestampSize);
  1802. options.comparator = &test_cmp;
  1803. DestroyAndReopen(options);
  1804. constexpr size_t max_skippable_internal_keys = 2;
  1805. const size_t kNumKeys = max_skippable_internal_keys + 2;
  1806. WriteOptions write_opts;
  1807. Status s;
  1808. {
  1809. std::string ts = Timestamp(1, 0);
  1810. ASSERT_OK(db_->Put(write_opts, "a", ts, "value"));
  1811. }
  1812. for (size_t i = 0; i < kNumKeys; ++i) {
  1813. std::string ts = Timestamp(static_cast<uint64_t>(i + 1), 0);
  1814. s = db_->Put(write_opts, "b", ts, "value" + std::to_string(i));
  1815. ASSERT_OK(s);
  1816. }
  1817. {
  1818. ReadOptions read_opts;
  1819. read_opts.max_skippable_internal_keys = max_skippable_internal_keys;
  1820. std::string ts_str = Timestamp(1, 0);
  1821. Slice ts = ts_str;
  1822. read_opts.timestamp = &ts;
  1823. std::unique_ptr<Iterator> iter(db_->NewIterator(read_opts));
  1824. iter->SeekToFirst();
  1825. iter->Next();
  1826. ASSERT_TRUE(iter->status().IsIncomplete());
  1827. }
  1828. Close();
  1829. }
  1830. TEST_F(DBBasicTestWithTimestamp, MaxKeysSkippedDuringPrev) {
  1831. Options options = GetDefaultOptions();
  1832. options.env = env_;
  1833. options.create_if_missing = true;
  1834. const size_t kTimestampSize = Timestamp(0, 0).size();
  1835. TestComparator test_cmp(kTimestampSize);
  1836. options.comparator = &test_cmp;
  1837. DestroyAndReopen(options);
  1838. constexpr size_t max_skippable_internal_keys = 2;
  1839. const size_t kNumKeys = max_skippable_internal_keys + 2;
  1840. WriteOptions write_opts;
  1841. Status s;
  1842. {
  1843. std::string ts = Timestamp(1, 0);
  1844. ASSERT_OK(db_->Put(write_opts, "b", ts, "value"));
  1845. }
  1846. for (size_t i = 0; i < kNumKeys; ++i) {
  1847. std::string ts = Timestamp(static_cast<uint64_t>(i + 1), 0);
  1848. s = db_->Put(write_opts, "a", ts, "value" + std::to_string(i));
  1849. ASSERT_OK(s);
  1850. }
  1851. {
  1852. ReadOptions read_opts;
  1853. read_opts.max_skippable_internal_keys = max_skippable_internal_keys;
  1854. std::string ts_str = Timestamp(1, 0);
  1855. Slice ts = ts_str;
  1856. read_opts.timestamp = &ts;
  1857. std::unique_ptr<Iterator> iter(db_->NewIterator(read_opts));
  1858. iter->SeekToLast();
  1859. iter->Prev();
  1860. ASSERT_TRUE(iter->status().IsIncomplete());
  1861. }
  1862. Close();
  1863. }
  1864. // Create two L0, and compact them to a new L1. In this test, L1 is L_bottom.
  1865. // Two L0s:
  1866. // f1 f2
  1867. // <a, 1, kTypeValue> <a, 3, kTypeDeletionWithTimestamp>...<b, 2, kTypeValue>
  1868. // Since f2.smallest < f1.largest < f2.largest
  1869. // f1 and f2 will be the inputs of a real compaction instead of trivial move.
  1870. TEST_F(DBBasicTestWithTimestamp, CompactDeletionWithTimestampMarkerToBottom) {
  1871. Options options = CurrentOptions();
  1872. options.env = env_;
  1873. options.create_if_missing = true;
  1874. const size_t kTimestampSize = Timestamp(0, 0).size();
  1875. TestComparator test_cmp(kTimestampSize);
  1876. options.comparator = &test_cmp;
  1877. options.num_levels = 2;
  1878. options.level0_file_num_compaction_trigger = 2;
  1879. DestroyAndReopen(options);
  1880. WriteOptions write_opts;
  1881. std::string ts = Timestamp(1, 0);
  1882. ASSERT_OK(db_->Put(write_opts, "a", ts, "value0"));
  1883. ASSERT_OK(Flush());
  1884. ts = Timestamp(2, 0);
  1885. ASSERT_OK(db_->Put(write_opts, "b", ts, "value0"));
  1886. ts = Timestamp(3, 0);
  1887. ASSERT_OK(db_->Delete(write_opts, "a", ts));
  1888. ASSERT_OK(Flush());
  1889. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  1890. ReadOptions read_opts;
  1891. ts = Timestamp(1, 0);
  1892. Slice read_ts = ts;
  1893. read_opts.timestamp = &read_ts;
  1894. std::string value;
  1895. Status s = db_->Get(read_opts, "a", &value);
  1896. ASSERT_OK(s);
  1897. ASSERT_EQ("value0", value);
  1898. ts = Timestamp(3, 0);
  1899. read_ts = ts;
  1900. read_opts.timestamp = &read_ts;
  1901. std::string key_ts;
  1902. s = db_->Get(read_opts, "a", &value, &key_ts);
  1903. ASSERT_TRUE(s.IsNotFound());
  1904. ASSERT_EQ(Timestamp(3, 0), key_ts);
  1905. // Time-travel to the past before deletion
  1906. ts = Timestamp(2, 0);
  1907. read_ts = ts;
  1908. read_opts.timestamp = &read_ts;
  1909. s = db_->Get(read_opts, "a", &value);
  1910. ASSERT_OK(s);
  1911. ASSERT_EQ("value0", value);
  1912. Close();
  1913. }
  1914. #if !defined(ROCKSDB_VALGRIND_RUN) || defined(ROCKSDB_FULL_VALGRIND_RUN)
  1915. class DBBasicTestWithTimestampFilterPrefixSettings
  1916. : public DBBasicTestWithTimestampBase,
  1917. public testing::WithParamInterface<
  1918. std::tuple<std::shared_ptr<const FilterPolicy>, bool, bool,
  1919. std::shared_ptr<const SliceTransform>, bool, double,
  1920. BlockBasedTableOptions::IndexType>> {
  1921. public:
  1922. DBBasicTestWithTimestampFilterPrefixSettings()
  1923. : DBBasicTestWithTimestampBase(
  1924. "db_basic_test_with_timestamp_filter_prefix") {}
  1925. };
  1926. TEST_P(DBBasicTestWithTimestampFilterPrefixSettings, GetAndMultiGet) {
  1927. Options options = CurrentOptions();
  1928. options.env = env_;
  1929. options.create_if_missing = true;
  1930. BlockBasedTableOptions bbto;
  1931. bbto.filter_policy = std::get<0>(GetParam());
  1932. bbto.whole_key_filtering = std::get<1>(GetParam());
  1933. bbto.cache_index_and_filter_blocks = std::get<2>(GetParam());
  1934. bbto.index_type = std::get<6>(GetParam());
  1935. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  1936. options.prefix_extractor = std::get<3>(GetParam());
  1937. options.memtable_whole_key_filtering = std::get<4>(GetParam());
  1938. options.memtable_prefix_bloom_size_ratio = std::get<5>(GetParam());
  1939. const size_t kTimestampSize = Timestamp(0, 0).size();
  1940. TestComparator test_cmp(kTimestampSize);
  1941. options.comparator = &test_cmp;
  1942. DestroyAndReopen(options);
  1943. const int kMaxKey = 1000;
  1944. // Write any value
  1945. WriteOptions write_opts;
  1946. std::string ts = Timestamp(1, 0);
  1947. int idx = 0;
  1948. for (; idx < kMaxKey / 4; idx++) {
  1949. ASSERT_OK(db_->Put(write_opts, Key1(idx), ts, "bar"));
  1950. ASSERT_OK(db_->Put(write_opts, KeyWithPrefix("foo", idx), ts, "bar"));
  1951. }
  1952. ASSERT_OK(Flush());
  1953. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  1954. for (; idx < kMaxKey / 2; idx++) {
  1955. ASSERT_OK(db_->Put(write_opts, Key1(idx), ts, "bar"));
  1956. ASSERT_OK(db_->Put(write_opts, KeyWithPrefix("foo", idx), ts, "bar"));
  1957. }
  1958. ASSERT_OK(Flush());
  1959. for (; idx < kMaxKey; idx++) {
  1960. ASSERT_OK(db_->Put(write_opts, Key1(idx), ts, "bar"));
  1961. ASSERT_OK(db_->Put(write_opts, KeyWithPrefix("foo", idx), ts, "bar"));
  1962. }
  1963. // Read with MultiGet
  1964. ReadOptions read_opts;
  1965. Slice read_ts = ts;
  1966. read_opts.timestamp = &read_ts;
  1967. for (idx = 0; idx < kMaxKey; idx++) {
  1968. size_t batch_size = 4;
  1969. std::vector<std::string> keys_str(batch_size);
  1970. std::vector<PinnableSlice> values(batch_size);
  1971. std::vector<Status> statuses(batch_size);
  1972. ColumnFamilyHandle* cfh = db_->DefaultColumnFamily();
  1973. keys_str[0] = Key1(idx);
  1974. keys_str[1] = KeyWithPrefix("foo", idx);
  1975. keys_str[2] = Key1(kMaxKey + idx);
  1976. keys_str[3] = KeyWithPrefix("foo", kMaxKey + idx);
  1977. auto keys = ConvertStrToSlice(keys_str);
  1978. db_->MultiGet(read_opts, cfh, batch_size, keys.data(), values.data(),
  1979. statuses.data());
  1980. for (int i = 0; i < 2; i++) {
  1981. ASSERT_OK(statuses[i]);
  1982. }
  1983. for (int i = 2; i < 4; i++) {
  1984. ASSERT_TRUE(statuses[i].IsNotFound());
  1985. }
  1986. for (int i = 0; i < 2; i++) {
  1987. std::string value;
  1988. ASSERT_OK(db_->Get(read_opts, keys[i], &value));
  1989. std::unique_ptr<Iterator> it1(db_->NewIterator(read_opts));
  1990. ASSERT_NE(nullptr, it1);
  1991. ASSERT_OK(it1->status());
  1992. it1->Seek(keys[i]);
  1993. ASSERT_TRUE(it1->Valid());
  1994. }
  1995. for (int i = 2; i < 4; i++) {
  1996. std::string value;
  1997. Status s = db_->Get(read_opts, keys[i], &value);
  1998. ASSERT_TRUE(s.IsNotFound());
  1999. }
  2000. }
  2001. Close();
  2002. }
  2003. INSTANTIATE_TEST_CASE_P(
  2004. Timestamp, DBBasicTestWithTimestampFilterPrefixSettings,
  2005. ::testing::Combine(
  2006. ::testing::Values(
  2007. std::shared_ptr<const FilterPolicy>(nullptr),
  2008. std::shared_ptr<const FilterPolicy>(NewBloomFilterPolicy(10, true)),
  2009. std::shared_ptr<const FilterPolicy>(NewBloomFilterPolicy(10,
  2010. false))),
  2011. ::testing::Bool(), ::testing::Bool(),
  2012. ::testing::Values(
  2013. std::shared_ptr<const SliceTransform>(NewFixedPrefixTransform(1)),
  2014. std::shared_ptr<const SliceTransform>(NewFixedPrefixTransform(4)),
  2015. std::shared_ptr<const SliceTransform>(NewFixedPrefixTransform(7)),
  2016. std::shared_ptr<const SliceTransform>(NewFixedPrefixTransform(8))),
  2017. ::testing::Bool(), ::testing::Values(0, 0.1),
  2018. ::testing::Values(
  2019. BlockBasedTableOptions::IndexType::kBinarySearch,
  2020. BlockBasedTableOptions::IndexType::kHashSearch,
  2021. BlockBasedTableOptions::IndexType::kTwoLevelIndexSearch,
  2022. BlockBasedTableOptions::IndexType::kBinarySearchWithFirstKey)));
  2023. #endif // !defined(ROCKSDB_VALGRIND_RUN) || defined(ROCKSDB_FULL_VALGRIND_RUN)
  2024. class DataVisibilityTest : public DBBasicTestWithTimestampBase {
  2025. public:
  2026. DataVisibilityTest() : DBBasicTestWithTimestampBase("data_visibility_test") {
  2027. // Initialize test data
  2028. for (int i = 0; i < kTestDataSize; i++) {
  2029. test_data_[i].key = "key" + std::to_string(i);
  2030. test_data_[i].value = "value" + std::to_string(i);
  2031. test_data_[i].timestamp = Timestamp(i, 0);
  2032. test_data_[i].ts = i;
  2033. test_data_[i].seq_num = kMaxSequenceNumber;
  2034. }
  2035. }
  2036. protected:
  2037. struct TestData {
  2038. std::string key;
  2039. std::string value;
  2040. int ts;
  2041. std::string timestamp;
  2042. SequenceNumber seq_num;
  2043. };
  2044. constexpr static int kTestDataSize = 3;
  2045. TestData test_data_[kTestDataSize];
  2046. void PutTestData(int index, ColumnFamilyHandle* cfh = nullptr) {
  2047. ASSERT_LE(index, kTestDataSize);
  2048. WriteOptions write_opts;
  2049. if (cfh == nullptr) {
  2050. ASSERT_OK(db_->Put(write_opts, test_data_[index].key,
  2051. test_data_[index].timestamp, test_data_[index].value));
  2052. const Snapshot* snap = db_->GetSnapshot();
  2053. test_data_[index].seq_num = snap->GetSequenceNumber();
  2054. if (index > 0) {
  2055. ASSERT_GT(test_data_[index].seq_num, test_data_[index - 1].seq_num);
  2056. }
  2057. db_->ReleaseSnapshot(snap);
  2058. } else {
  2059. ASSERT_OK(db_->Put(write_opts, cfh, test_data_[index].key,
  2060. test_data_[index].timestamp, test_data_[index].value));
  2061. }
  2062. }
  2063. void AssertVisibility(int ts, SequenceNumber seq,
  2064. std::vector<Status> statuses) {
  2065. ASSERT_EQ(kTestDataSize, statuses.size());
  2066. for (int i = 0; i < kTestDataSize; i++) {
  2067. if (test_data_[i].seq_num <= seq && test_data_[i].ts <= ts) {
  2068. ASSERT_OK(statuses[i]);
  2069. } else {
  2070. ASSERT_TRUE(statuses[i].IsNotFound());
  2071. }
  2072. }
  2073. }
  2074. std::vector<Slice> GetKeys() {
  2075. std::vector<Slice> ret(kTestDataSize);
  2076. for (int i = 0; i < kTestDataSize; i++) {
  2077. ret[i] = test_data_[i].key;
  2078. }
  2079. return ret;
  2080. }
  2081. void VerifyDefaultCF(int ts, const Snapshot* snap = nullptr) {
  2082. ReadOptions read_opts;
  2083. std::string read_ts = Timestamp(ts, 0);
  2084. Slice read_ts_slice = read_ts;
  2085. read_opts.timestamp = &read_ts_slice;
  2086. read_opts.snapshot = snap;
  2087. ColumnFamilyHandle* cfh = db_->DefaultColumnFamily();
  2088. std::vector<ColumnFamilyHandle*> cfs(kTestDataSize, cfh);
  2089. SequenceNumber seq =
  2090. snap ? snap->GetSequenceNumber() : kMaxSequenceNumber - 1;
  2091. // There're several MultiGet interfaces with not exactly the same
  2092. // implementations, query data with all of them.
  2093. auto keys = GetKeys();
  2094. std::vector<std::string> values;
  2095. auto s1 = db_->MultiGet(read_opts, cfs, keys, &values);
  2096. AssertVisibility(ts, seq, s1);
  2097. auto s2 = db_->MultiGet(read_opts, keys, &values);
  2098. AssertVisibility(ts, seq, s2);
  2099. std::vector<std::string> timestamps;
  2100. auto s3 = db_->MultiGet(read_opts, cfs, keys, &values, &timestamps);
  2101. AssertVisibility(ts, seq, s3);
  2102. auto s4 = db_->MultiGet(read_opts, keys, &values, &timestamps);
  2103. AssertVisibility(ts, seq, s4);
  2104. std::vector<PinnableSlice> values_ps5(kTestDataSize);
  2105. std::vector<Status> s5(kTestDataSize);
  2106. db_->MultiGet(read_opts, cfh, kTestDataSize, keys.data(), values_ps5.data(),
  2107. s5.data());
  2108. AssertVisibility(ts, seq, s5);
  2109. std::vector<PinnableSlice> values_ps6(kTestDataSize);
  2110. std::vector<Status> s6(kTestDataSize);
  2111. std::vector<std::string> timestamps_array(kTestDataSize);
  2112. db_->MultiGet(read_opts, cfh, kTestDataSize, keys.data(), values_ps6.data(),
  2113. timestamps_array.data(), s6.data());
  2114. AssertVisibility(ts, seq, s6);
  2115. std::vector<PinnableSlice> values_ps7(kTestDataSize);
  2116. std::vector<Status> s7(kTestDataSize);
  2117. db_->MultiGet(read_opts, kTestDataSize, cfs.data(), keys.data(),
  2118. values_ps7.data(), s7.data());
  2119. AssertVisibility(ts, seq, s7);
  2120. std::vector<PinnableSlice> values_ps8(kTestDataSize);
  2121. std::vector<Status> s8(kTestDataSize);
  2122. db_->MultiGet(read_opts, kTestDataSize, cfs.data(), keys.data(),
  2123. values_ps8.data(), timestamps_array.data(), s8.data());
  2124. AssertVisibility(ts, seq, s8);
  2125. }
  2126. void VerifyDefaultCF(const Snapshot* snap = nullptr) {
  2127. for (int i = 0; i <= kTestDataSize; i++) {
  2128. VerifyDefaultCF(i, snap);
  2129. }
  2130. }
  2131. };
  2132. // Application specifies timestamp but not snapshot.
  2133. // reader writer
  2134. // ts'=90
  2135. // ts=100
  2136. // seq=10
  2137. // seq'=11
  2138. // write finishes
  2139. // GetImpl(ts,seq)
  2140. // It is OK to return <k, t1, s1> if ts>=t1 AND seq>=s1. If ts>=t1 but seq<s1,
  2141. // the key should not be returned.
  2142. TEST_F(DataVisibilityTest, PointLookupWithoutSnapshot1) {
  2143. Options options = CurrentOptions();
  2144. const size_t kTimestampSize = Timestamp(0, 0).size();
  2145. TestComparator test_cmp(kTimestampSize);
  2146. options.comparator = &test_cmp;
  2147. DestroyAndReopen(options);
  2148. SyncPoint::GetInstance()->DisableProcessing();
  2149. SyncPoint::GetInstance()->LoadDependency({
  2150. {"DBImpl::GetImpl:3",
  2151. "DataVisibilityTest::PointLookupWithoutSnapshot1:BeforePut"},
  2152. {"DataVisibilityTest::PointLookupWithoutSnapshot1:AfterPut",
  2153. "DBImpl::GetImpl:4"},
  2154. });
  2155. SyncPoint::GetInstance()->EnableProcessing();
  2156. port::Thread writer_thread([this]() {
  2157. std::string write_ts = Timestamp(1, 0);
  2158. WriteOptions write_opts;
  2159. TEST_SYNC_POINT(
  2160. "DataVisibilityTest::PointLookupWithoutSnapshot1:BeforePut");
  2161. Status s = db_->Put(write_opts, "foo", write_ts, "value");
  2162. ASSERT_OK(s);
  2163. TEST_SYNC_POINT("DataVisibilityTest::PointLookupWithoutSnapshot1:AfterPut");
  2164. });
  2165. ReadOptions read_opts;
  2166. std::string read_ts_str = Timestamp(3, 0);
  2167. Slice read_ts = read_ts_str;
  2168. read_opts.timestamp = &read_ts;
  2169. std::string value;
  2170. Status s = db_->Get(read_opts, "foo", &value);
  2171. writer_thread.join();
  2172. ASSERT_TRUE(s.IsNotFound());
  2173. Close();
  2174. }
  2175. // Application specifies timestamp but not snapshot.
  2176. // reader writer
  2177. // ts'=90
  2178. // ts=100
  2179. // seq=10
  2180. // seq'=11
  2181. // write finishes
  2182. // Flush
  2183. // GetImpl(ts,seq)
  2184. // It is OK to return <k, t1, s1> if ts>=t1 AND seq>=s1. If ts>=t1 but seq<s1,
  2185. // the key should not be returned.
  2186. TEST_F(DataVisibilityTest, PointLookupWithoutSnapshot2) {
  2187. Options options = CurrentOptions();
  2188. const size_t kTimestampSize = Timestamp(0, 0).size();
  2189. TestComparator test_cmp(kTimestampSize);
  2190. options.comparator = &test_cmp;
  2191. DestroyAndReopen(options);
  2192. SyncPoint::GetInstance()->DisableProcessing();
  2193. SyncPoint::GetInstance()->LoadDependency({
  2194. {"DBImpl::GetImpl:3",
  2195. "DataVisibilityTest::PointLookupWithoutSnapshot2:BeforePut"},
  2196. {"DataVisibilityTest::PointLookupWithoutSnapshot2:AfterPut",
  2197. "DBImpl::GetImpl:4"},
  2198. });
  2199. SyncPoint::GetInstance()->EnableProcessing();
  2200. port::Thread writer_thread([this]() {
  2201. std::string write_ts = Timestamp(1, 0);
  2202. WriteOptions write_opts;
  2203. TEST_SYNC_POINT(
  2204. "DataVisibilityTest::PointLookupWithoutSnapshot2:BeforePut");
  2205. Status s = db_->Put(write_opts, "foo", write_ts, "value");
  2206. ASSERT_OK(s);
  2207. ASSERT_OK(Flush());
  2208. write_ts = Timestamp(2, 0);
  2209. s = db_->Put(write_opts, "bar", write_ts, "value");
  2210. ASSERT_OK(s);
  2211. TEST_SYNC_POINT("DataVisibilityTest::PointLookupWithoutSnapshot2:AfterPut");
  2212. });
  2213. ReadOptions read_opts;
  2214. std::string read_ts_str = Timestamp(3, 0);
  2215. Slice read_ts = read_ts_str;
  2216. read_opts.timestamp = &read_ts;
  2217. std::string value;
  2218. Status s = db_->Get(read_opts, "foo", &value);
  2219. writer_thread.join();
  2220. ASSERT_TRUE(s.IsNotFound());
  2221. Close();
  2222. }
  2223. // Application specifies both timestamp and snapshot.
  2224. // reader writer
  2225. // seq=10
  2226. // ts'=90
  2227. // ts=100
  2228. // seq'=11
  2229. // write finishes
  2230. // GetImpl(ts,seq)
  2231. // Since application specifies both timestamp and snapshot, application expects
  2232. // to see data that visible in BOTH timestamp and sequence number. Therefore,
  2233. // <k, t1, s1> can be returned only if t1<=ts AND s1<=seq.
  2234. TEST_F(DataVisibilityTest, PointLookupWithSnapshot1) {
  2235. Options options = CurrentOptions();
  2236. const size_t kTimestampSize = Timestamp(0, 0).size();
  2237. TestComparator test_cmp(kTimestampSize);
  2238. options.comparator = &test_cmp;
  2239. DestroyAndReopen(options);
  2240. SyncPoint::GetInstance()->DisableProcessing();
  2241. SyncPoint::GetInstance()->LoadDependency({
  2242. {"DataVisibilityTest::PointLookupWithSnapshot1:AfterTakingSnap",
  2243. "DataVisibilityTest::PointLookupWithSnapshot1:BeforePut"},
  2244. {"DataVisibilityTest::PointLookupWithSnapshot1:AfterPut",
  2245. "DBImpl::GetImpl:1"},
  2246. });
  2247. SyncPoint::GetInstance()->EnableProcessing();
  2248. port::Thread writer_thread([this]() {
  2249. std::string write_ts = Timestamp(1, 0);
  2250. WriteOptions write_opts;
  2251. TEST_SYNC_POINT("DataVisibilityTest::PointLookupWithSnapshot1:BeforePut");
  2252. Status s = db_->Put(write_opts, "foo", write_ts, "value");
  2253. TEST_SYNC_POINT("DataVisibilityTest::PointLookupWithSnapshot1:AfterPut");
  2254. ASSERT_OK(s);
  2255. });
  2256. ReadOptions read_opts;
  2257. const Snapshot* snap = db_->GetSnapshot();
  2258. TEST_SYNC_POINT(
  2259. "DataVisibilityTest::PointLookupWithSnapshot1:AfterTakingSnap");
  2260. read_opts.snapshot = snap;
  2261. std::string read_ts_str = Timestamp(3, 0);
  2262. Slice read_ts = read_ts_str;
  2263. read_opts.timestamp = &read_ts;
  2264. std::string value;
  2265. Status s = db_->Get(read_opts, "foo", &value);
  2266. writer_thread.join();
  2267. ASSERT_TRUE(s.IsNotFound());
  2268. db_->ReleaseSnapshot(snap);
  2269. Close();
  2270. }
  2271. // Application specifies both timestamp and snapshot.
  2272. // reader writer
  2273. // seq=10
  2274. // ts'=90
  2275. // ts=100
  2276. // seq'=11
  2277. // write finishes
  2278. // Flush
  2279. // GetImpl(ts,seq)
  2280. // Since application specifies both timestamp and snapshot, application expects
  2281. // to see data that visible in BOTH timestamp and sequence number. Therefore,
  2282. // <k, t1, s1> can be returned only if t1<=ts AND s1<=seq.
  2283. TEST_F(DataVisibilityTest, PointLookupWithSnapshot2) {
  2284. Options options = CurrentOptions();
  2285. const size_t kTimestampSize = Timestamp(0, 0).size();
  2286. TestComparator test_cmp(kTimestampSize);
  2287. options.comparator = &test_cmp;
  2288. DestroyAndReopen(options);
  2289. SyncPoint::GetInstance()->DisableProcessing();
  2290. SyncPoint::GetInstance()->LoadDependency({
  2291. {"DataVisibilityTest::PointLookupWithSnapshot2:AfterTakingSnap",
  2292. "DataVisibilityTest::PointLookupWithSnapshot2:BeforePut"},
  2293. });
  2294. SyncPoint::GetInstance()->EnableProcessing();
  2295. port::Thread writer_thread([this]() {
  2296. std::string write_ts = Timestamp(1, 0);
  2297. WriteOptions write_opts;
  2298. TEST_SYNC_POINT("DataVisibilityTest::PointLookupWithSnapshot2:BeforePut");
  2299. Status s = db_->Put(write_opts, "foo", write_ts, "value1");
  2300. ASSERT_OK(s);
  2301. ASSERT_OK(Flush());
  2302. write_ts = Timestamp(2, 0);
  2303. s = db_->Put(write_opts, "bar", write_ts, "value2");
  2304. ASSERT_OK(s);
  2305. });
  2306. const Snapshot* snap = db_->GetSnapshot();
  2307. TEST_SYNC_POINT(
  2308. "DataVisibilityTest::PointLookupWithSnapshot2:AfterTakingSnap");
  2309. writer_thread.join();
  2310. std::string read_ts_str = Timestamp(3, 0);
  2311. Slice read_ts = read_ts_str;
  2312. ReadOptions read_opts;
  2313. read_opts.snapshot = snap;
  2314. read_opts.timestamp = &read_ts;
  2315. std::string value;
  2316. Status s = db_->Get(read_opts, "foo", &value);
  2317. ASSERT_TRUE(s.IsNotFound());
  2318. db_->ReleaseSnapshot(snap);
  2319. Close();
  2320. }
  2321. // Application specifies timestamp but not snapshot.
  2322. // reader writer
  2323. // ts'=90
  2324. // ts=100
  2325. // seq=10
  2326. // seq'=11
  2327. // write finishes
  2328. // scan(ts,seq)
  2329. // <k, t1, s1> can be seen in scan as long as ts>=t1 AND seq>=s1. If ts>=t1 but
  2330. // seq<s1, then the key should not be returned.
  2331. TEST_F(DataVisibilityTest, RangeScanWithoutSnapshot) {
  2332. Options options = CurrentOptions();
  2333. const size_t kTimestampSize = Timestamp(0, 0).size();
  2334. TestComparator test_cmp(kTimestampSize);
  2335. options.comparator = &test_cmp;
  2336. DestroyAndReopen(options);
  2337. SyncPoint::GetInstance()->DisableProcessing();
  2338. SyncPoint::GetInstance()->LoadDependency({
  2339. {"DBImpl::NewIterator:3",
  2340. "DataVisibilityTest::RangeScanWithoutSnapshot:BeforePut"},
  2341. });
  2342. SyncPoint::GetInstance()->EnableProcessing();
  2343. port::Thread writer_thread([this]() {
  2344. WriteOptions write_opts;
  2345. TEST_SYNC_POINT("DataVisibilityTest::RangeScanWithoutSnapshot:BeforePut");
  2346. for (int i = 0; i < 3; ++i) {
  2347. std::string write_ts = Timestamp(i + 1, 0);
  2348. Status s = db_->Put(write_opts, "key" + std::to_string(i), write_ts,
  2349. "value" + std::to_string(i));
  2350. ASSERT_OK(s);
  2351. }
  2352. });
  2353. std::string read_ts_str = Timestamp(10, 0);
  2354. Slice read_ts = read_ts_str;
  2355. ReadOptions read_opts;
  2356. read_opts.total_order_seek = true;
  2357. read_opts.timestamp = &read_ts;
  2358. Iterator* it = db_->NewIterator(read_opts);
  2359. ASSERT_NE(nullptr, it);
  2360. writer_thread.join();
  2361. it->SeekToFirst();
  2362. ASSERT_FALSE(it->Valid());
  2363. delete it;
  2364. Close();
  2365. }
  2366. // Application specifies both timestamp and snapshot.
  2367. // reader writer
  2368. // seq=10
  2369. // ts'=90
  2370. // ts=100 seq'=11
  2371. // write finishes
  2372. // scan(ts,seq)
  2373. // <k, t1, s1> can be seen by the scan only if t1<=ts AND s1<=seq. If t1<=ts
  2374. // but s1>seq, then the key should not be returned.
  2375. TEST_F(DataVisibilityTest, RangeScanWithSnapshot) {
  2376. Options options = CurrentOptions();
  2377. const size_t kTimestampSize = Timestamp(0, 0).size();
  2378. TestComparator test_cmp(kTimestampSize);
  2379. options.comparator = &test_cmp;
  2380. DestroyAndReopen(options);
  2381. SyncPoint::GetInstance()->DisableProcessing();
  2382. SyncPoint::GetInstance()->LoadDependency({
  2383. {"DataVisibilityTest::RangeScanWithSnapshot:AfterTakingSnapshot",
  2384. "DataVisibilityTest::RangeScanWithSnapshot:BeforePut"},
  2385. });
  2386. SyncPoint::GetInstance()->EnableProcessing();
  2387. port::Thread writer_thread([this]() {
  2388. WriteOptions write_opts;
  2389. TEST_SYNC_POINT("DataVisibilityTest::RangeScanWithSnapshot:BeforePut");
  2390. for (int i = 0; i < 3; ++i) {
  2391. std::string write_ts = Timestamp(i + 1, 0);
  2392. Status s = db_->Put(write_opts, "key" + std::to_string(i), write_ts,
  2393. "value" + std::to_string(i));
  2394. ASSERT_OK(s);
  2395. }
  2396. });
  2397. const Snapshot* snap = db_->GetSnapshot();
  2398. TEST_SYNC_POINT(
  2399. "DataVisibilityTest::RangeScanWithSnapshot:AfterTakingSnapshot");
  2400. writer_thread.join();
  2401. std::string read_ts_str = Timestamp(10, 0);
  2402. Slice read_ts = read_ts_str;
  2403. ReadOptions read_opts;
  2404. read_opts.snapshot = snap;
  2405. read_opts.total_order_seek = true;
  2406. read_opts.timestamp = &read_ts;
  2407. Iterator* it = db_->NewIterator(read_opts);
  2408. ASSERT_NE(nullptr, it);
  2409. it->Seek("key0");
  2410. ASSERT_FALSE(it->Valid());
  2411. delete it;
  2412. db_->ReleaseSnapshot(snap);
  2413. Close();
  2414. }
  2415. // Application specifies both timestamp and snapshot.
  2416. // Query each combination and make sure for MultiGet key <k, t1, s1>, only
  2417. // return keys that ts>=t1 AND seq>=s1.
  2418. TEST_F(DataVisibilityTest, MultiGetWithTimestamp) {
  2419. Options options = CurrentOptions();
  2420. const size_t kTimestampSize = Timestamp(0, 0).size();
  2421. TestComparator test_cmp(kTimestampSize);
  2422. options.comparator = &test_cmp;
  2423. DestroyAndReopen(options);
  2424. const Snapshot* snap0 = db_->GetSnapshot();
  2425. PutTestData(0);
  2426. VerifyDefaultCF();
  2427. VerifyDefaultCF(snap0);
  2428. const Snapshot* snap1 = db_->GetSnapshot();
  2429. PutTestData(1);
  2430. VerifyDefaultCF();
  2431. VerifyDefaultCF(snap0);
  2432. VerifyDefaultCF(snap1);
  2433. ASSERT_OK(Flush());
  2434. const Snapshot* snap2 = db_->GetSnapshot();
  2435. PutTestData(2);
  2436. VerifyDefaultCF();
  2437. VerifyDefaultCF(snap0);
  2438. VerifyDefaultCF(snap1);
  2439. VerifyDefaultCF(snap2);
  2440. db_->ReleaseSnapshot(snap0);
  2441. db_->ReleaseSnapshot(snap1);
  2442. db_->ReleaseSnapshot(snap2);
  2443. Close();
  2444. }
  2445. // Application specifies timestamp but not snapshot.
  2446. // reader writer
  2447. // ts'=0, 1
  2448. // ts=3
  2449. // seq=10
  2450. // seq'=11, 12
  2451. // write finishes
  2452. // MultiGet(ts,seq)
  2453. // For MultiGet <k, t1, s1>, only return keys that ts>=t1 AND seq>=s1.
  2454. TEST_F(DataVisibilityTest, MultiGetWithoutSnapshot) {
  2455. Options options = CurrentOptions();
  2456. const size_t kTimestampSize = Timestamp(0, 0).size();
  2457. TestComparator test_cmp(kTimestampSize);
  2458. options.comparator = &test_cmp;
  2459. DestroyAndReopen(options);
  2460. SyncPoint::GetInstance()->DisableProcessing();
  2461. SyncPoint::GetInstance()->LoadDependency({
  2462. {"DBImpl::MultiCFSnapshot:AfterGetSeqNum1",
  2463. "DataVisibilityTest::MultiGetWithoutSnapshot:BeforePut"},
  2464. {"DataVisibilityTest::MultiGetWithoutSnapshot:AfterPut",
  2465. "DBImpl::MultiCFSnapshot:AfterGetSeqNum2"},
  2466. });
  2467. SyncPoint::GetInstance()->EnableProcessing();
  2468. port::Thread writer_thread([this]() {
  2469. TEST_SYNC_POINT("DataVisibilityTest::MultiGetWithoutSnapshot:BeforePut");
  2470. PutTestData(0);
  2471. PutTestData(1);
  2472. TEST_SYNC_POINT("DataVisibilityTest::MultiGetWithoutSnapshot:AfterPut");
  2473. });
  2474. ReadOptions read_opts;
  2475. std::string read_ts = Timestamp(kTestDataSize, 0);
  2476. Slice read_ts_slice = read_ts;
  2477. read_opts.timestamp = &read_ts_slice;
  2478. auto keys = GetKeys();
  2479. std::vector<std::string> values;
  2480. auto ss = db_->MultiGet(read_opts, keys, &values);
  2481. writer_thread.join();
  2482. for (const auto& s : ss) {
  2483. ASSERT_TRUE(s.IsNotFound());
  2484. }
  2485. VerifyDefaultCF();
  2486. Close();
  2487. }
  2488. TEST_F(DataVisibilityTest, MultiGetCrossCF) {
  2489. Options options = CurrentOptions();
  2490. const size_t kTimestampSize = Timestamp(0, 0).size();
  2491. TestComparator test_cmp(kTimestampSize);
  2492. options.comparator = &test_cmp;
  2493. DestroyAndReopen(options);
  2494. CreateAndReopenWithCF({"second"}, options);
  2495. ColumnFamilyHandle* second_cf = handles_[1];
  2496. const Snapshot* snap0 = db_->GetSnapshot();
  2497. PutTestData(0);
  2498. PutTestData(0, second_cf);
  2499. VerifyDefaultCF();
  2500. VerifyDefaultCF(snap0);
  2501. const Snapshot* snap1 = db_->GetSnapshot();
  2502. PutTestData(1);
  2503. PutTestData(1, second_cf);
  2504. VerifyDefaultCF();
  2505. VerifyDefaultCF(snap0);
  2506. VerifyDefaultCF(snap1);
  2507. ASSERT_OK(Flush());
  2508. const Snapshot* snap2 = db_->GetSnapshot();
  2509. PutTestData(2);
  2510. PutTestData(2, second_cf);
  2511. VerifyDefaultCF();
  2512. VerifyDefaultCF(snap0);
  2513. VerifyDefaultCF(snap1);
  2514. VerifyDefaultCF(snap2);
  2515. ReadOptions read_opts;
  2516. std::string read_ts = Timestamp(kTestDataSize, 0);
  2517. Slice read_ts_slice = read_ts;
  2518. read_opts.timestamp = &read_ts_slice;
  2519. read_opts.snapshot = snap1;
  2520. auto keys = GetKeys();
  2521. auto keys2 = GetKeys();
  2522. keys.insert(keys.end(), keys2.begin(), keys2.end());
  2523. std::vector<ColumnFamilyHandle*> cfs(kTestDataSize,
  2524. db_->DefaultColumnFamily());
  2525. std::vector<ColumnFamilyHandle*> cfs2(kTestDataSize, second_cf);
  2526. cfs.insert(cfs.end(), cfs2.begin(), cfs2.end());
  2527. std::vector<std::string> values;
  2528. auto ss = db_->MultiGet(read_opts, cfs, keys, &values);
  2529. for (int i = 0; i < 2 * kTestDataSize; i++) {
  2530. if (i % 3 == 0) {
  2531. // only the first key for each column family should be returned
  2532. ASSERT_OK(ss[i]);
  2533. } else {
  2534. ASSERT_TRUE(ss[i].IsNotFound());
  2535. }
  2536. }
  2537. db_->ReleaseSnapshot(snap0);
  2538. db_->ReleaseSnapshot(snap1);
  2539. db_->ReleaseSnapshot(snap2);
  2540. Close();
  2541. }
  2542. #if !defined(ROCKSDB_VALGRIND_RUN) || defined(ROCKSDB_FULL_VALGRIND_RUN)
  2543. class DBBasicTestWithTimestampCompressionSettings
  2544. : public DBBasicTestWithTimestampBase,
  2545. public testing::WithParamInterface<
  2546. std::tuple<std::shared_ptr<const FilterPolicy>, CompressionType,
  2547. uint32_t, uint32_t>> {
  2548. public:
  2549. DBBasicTestWithTimestampCompressionSettings()
  2550. : DBBasicTestWithTimestampBase(
  2551. "db_basic_test_with_timestamp_compression") {}
  2552. };
  2553. TEST_P(DBBasicTestWithTimestampCompressionSettings, PutAndGet) {
  2554. const int kNumKeysPerFile = 1024;
  2555. const size_t kNumTimestamps = 4;
  2556. Options options = CurrentOptions();
  2557. options.create_if_missing = true;
  2558. options.env = env_;
  2559. options.memtable_factory.reset(
  2560. test::NewSpecialSkipListFactory(kNumKeysPerFile));
  2561. size_t ts_sz = Timestamp(0, 0).size();
  2562. TestComparator test_cmp(ts_sz);
  2563. options.comparator = &test_cmp;
  2564. BlockBasedTableOptions bbto;
  2565. bbto.filter_policy = std::get<0>(GetParam());
  2566. bbto.whole_key_filtering = true;
  2567. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  2568. const CompressionType comp_type = std::get<1>(GetParam());
  2569. #if LZ4_VERSION_NUMBER < 10400 // r124+
  2570. if (comp_type == kLZ4Compression || comp_type == kLZ4HCCompression) {
  2571. return;
  2572. }
  2573. #endif // LZ4_VERSION_NUMBER >= 10400
  2574. if (!ZSTD_Supported() && comp_type == kZSTD) {
  2575. return;
  2576. }
  2577. if (!Zlib_Supported() && comp_type == kZlibCompression) {
  2578. return;
  2579. }
  2580. options.compression = comp_type;
  2581. options.compression_opts.max_dict_bytes = std::get<2>(GetParam());
  2582. if (comp_type == kZSTD) {
  2583. options.compression_opts.zstd_max_train_bytes = std::get<2>(GetParam());
  2584. }
  2585. options.compression_opts.parallel_threads = std::get<3>(GetParam());
  2586. options.target_file_size_base = 1 << 26; // 64MB
  2587. DestroyAndReopen(options);
  2588. CreateAndReopenWithCF({"pikachu"}, options);
  2589. size_t num_cfs = handles_.size();
  2590. ASSERT_EQ(2, num_cfs);
  2591. std::vector<std::string> write_ts_list;
  2592. std::vector<std::string> read_ts_list;
  2593. for (size_t i = 0; i != kNumTimestamps; ++i) {
  2594. write_ts_list.push_back(Timestamp(i * 2, 0));
  2595. read_ts_list.push_back(Timestamp(1 + i * 2, 0));
  2596. const Slice write_ts = write_ts_list.back();
  2597. WriteOptions wopts;
  2598. for (int cf = 0; cf != static_cast<int>(num_cfs); ++cf) {
  2599. for (size_t j = 0; j != (kNumKeysPerFile - 1) / kNumTimestamps; ++j) {
  2600. ASSERT_OK(
  2601. db_->Put(wopts, handles_[cf], Key1(j), write_ts,
  2602. "value_" + std::to_string(j) + "_" + std::to_string(i)));
  2603. }
  2604. }
  2605. }
  2606. const auto& verify_db_func = [&]() {
  2607. for (size_t i = 0; i != kNumTimestamps; ++i) {
  2608. ReadOptions ropts;
  2609. const Slice read_ts = read_ts_list[i];
  2610. ropts.timestamp = &read_ts;
  2611. for (int cf = 0; cf != static_cast<int>(num_cfs); ++cf) {
  2612. ColumnFamilyHandle* cfh = handles_[cf];
  2613. for (size_t j = 0; j != (kNumKeysPerFile - 1) / kNumTimestamps; ++j) {
  2614. std::string value;
  2615. ASSERT_OK(db_->Get(ropts, cfh, Key1(j), &value));
  2616. ASSERT_EQ("value_" + std::to_string(j) + "_" + std::to_string(i),
  2617. value);
  2618. }
  2619. }
  2620. }
  2621. };
  2622. verify_db_func();
  2623. Close();
  2624. }
  2625. TEST_P(DBBasicTestWithTimestampCompressionSettings, PutDeleteGet) {
  2626. Options options = CurrentOptions();
  2627. options.env = env_;
  2628. options.create_if_missing = true;
  2629. const size_t kTimestampSize = Timestamp(0, 0).size();
  2630. TestComparator test_cmp(kTimestampSize);
  2631. options.comparator = &test_cmp;
  2632. const int kNumKeysPerFile = 1024;
  2633. options.memtable_factory.reset(
  2634. test::NewSpecialSkipListFactory(kNumKeysPerFile));
  2635. BlockBasedTableOptions bbto;
  2636. bbto.filter_policy = std::get<0>(GetParam());
  2637. bbto.whole_key_filtering = true;
  2638. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  2639. const CompressionType comp_type = std::get<1>(GetParam());
  2640. #if LZ4_VERSION_NUMBER < 10400 // r124+
  2641. if (comp_type == kLZ4Compression || comp_type == kLZ4HCCompression) {
  2642. return;
  2643. }
  2644. #endif // LZ4_VERSION_NUMBER >= 10400
  2645. if (!ZSTD_Supported() && comp_type == kZSTD) {
  2646. return;
  2647. }
  2648. if (!Zlib_Supported() && comp_type == kZlibCompression) {
  2649. return;
  2650. }
  2651. options.compression = comp_type;
  2652. options.compression_opts.max_dict_bytes = std::get<2>(GetParam());
  2653. if (comp_type == kZSTD) {
  2654. options.compression_opts.zstd_max_train_bytes = std::get<2>(GetParam());
  2655. }
  2656. options.compression_opts.parallel_threads = std::get<3>(GetParam());
  2657. options.target_file_size_base = 1 << 26; // 64MB
  2658. DestroyAndReopen(options);
  2659. const size_t kNumL0Files =
  2660. static_cast<size_t>(Options().level0_file_num_compaction_trigger);
  2661. {
  2662. // Half of the keys will go through Deletion and remaining half with
  2663. // SingleDeletion. Generate enough L0 files with ts=1 to trigger compaction
  2664. // to L1
  2665. std::string ts = Timestamp(1, 0);
  2666. WriteOptions wopts;
  2667. for (size_t i = 0; i < kNumL0Files; ++i) {
  2668. for (int j = 0; j < kNumKeysPerFile; ++j) {
  2669. ASSERT_OK(db_->Put(wopts, Key1(j), ts, "value" + std::to_string(i)));
  2670. }
  2671. ASSERT_OK(db_->Flush(FlushOptions()));
  2672. }
  2673. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  2674. // Generate another L0 at ts=3
  2675. ts = Timestamp(3, 0);
  2676. for (int i = 0; i < kNumKeysPerFile; ++i) {
  2677. std::string key_str = Key1(i);
  2678. Slice key(key_str);
  2679. if ((i % 3) == 0) {
  2680. if (i < kNumKeysPerFile / 2) {
  2681. ASSERT_OK(db_->Delete(wopts, key, ts));
  2682. } else {
  2683. ASSERT_OK(db_->SingleDelete(wopts, key, ts));
  2684. }
  2685. } else {
  2686. ASSERT_OK(db_->Put(wopts, key, ts, "new_value"));
  2687. }
  2688. }
  2689. ASSERT_OK(db_->Flush(FlushOptions()));
  2690. // Populate memtable at ts=5
  2691. ts = Timestamp(5, 0);
  2692. for (int i = 0; i != kNumKeysPerFile; ++i) {
  2693. std::string key_str = Key1(i);
  2694. Slice key(key_str);
  2695. if ((i % 3) == 1) {
  2696. if (i < kNumKeysPerFile / 2) {
  2697. ASSERT_OK(db_->Delete(wopts, key, ts));
  2698. } else {
  2699. ASSERT_OK(db_->SingleDelete(wopts, key, ts));
  2700. }
  2701. } else if ((i % 3) == 2) {
  2702. ASSERT_OK(db_->Put(wopts, key, ts, "new_value_2"));
  2703. }
  2704. }
  2705. }
  2706. {
  2707. std::string ts_str = Timestamp(6, 0);
  2708. Slice ts = ts_str;
  2709. ReadOptions ropts;
  2710. ropts.timestamp = &ts;
  2711. for (uint64_t i = 0; i != static_cast<uint64_t>(kNumKeysPerFile); ++i) {
  2712. std::string value;
  2713. std::string key_ts;
  2714. Status s = db_->Get(ropts, Key1(i), &value, &key_ts);
  2715. if ((i % 3) == 2) {
  2716. ASSERT_OK(s);
  2717. ASSERT_EQ("new_value_2", value);
  2718. ASSERT_EQ(Timestamp(5, 0), key_ts);
  2719. } else if ((i % 3) == 1) {
  2720. ASSERT_TRUE(s.IsNotFound());
  2721. ASSERT_EQ(Timestamp(5, 0), key_ts);
  2722. } else {
  2723. ASSERT_TRUE(s.IsNotFound());
  2724. ASSERT_EQ(Timestamp(3, 0), key_ts);
  2725. }
  2726. }
  2727. }
  2728. }
  2729. // A class which remembers the name of each flushed file.
  2730. class FlushedFileCollector : public EventListener {
  2731. public:
  2732. FlushedFileCollector() = default;
  2733. ~FlushedFileCollector() override = default;
  2734. void OnFlushCompleted(DB* /*db*/, const FlushJobInfo& info) override {
  2735. InstrumentedMutexLock lock(&mutex_);
  2736. flushed_files_.push_back(info.file_path);
  2737. }
  2738. std::vector<std::string> GetFlushedFiles() {
  2739. std::vector<std::string> result;
  2740. {
  2741. InstrumentedMutexLock lock(&mutex_);
  2742. result = flushed_files_;
  2743. }
  2744. return result;
  2745. }
  2746. void ClearFlushedFiles() {
  2747. InstrumentedMutexLock lock(&mutex_);
  2748. flushed_files_.clear();
  2749. }
  2750. private:
  2751. std::vector<std::string> flushed_files_;
  2752. InstrumentedMutex mutex_;
  2753. };
  2754. TEST_P(DBBasicTestWithTimestampCompressionSettings, PutAndGetWithCompaction) {
  2755. const int kNumKeysPerFile = 1024;
  2756. const size_t kNumTimestamps = 2;
  2757. const size_t kNumKeysPerTimestamp = (kNumKeysPerFile - 1) / kNumTimestamps;
  2758. const size_t kSplitPosBase = kNumKeysPerTimestamp / 2;
  2759. Options options = CurrentOptions();
  2760. options.create_if_missing = true;
  2761. options.env = env_;
  2762. options.memtable_factory.reset(
  2763. test::NewSpecialSkipListFactory(kNumKeysPerFile));
  2764. FlushedFileCollector* collector = new FlushedFileCollector();
  2765. options.listeners.emplace_back(collector);
  2766. size_t ts_sz = Timestamp(0, 0).size();
  2767. TestComparator test_cmp(ts_sz);
  2768. options.comparator = &test_cmp;
  2769. BlockBasedTableOptions bbto;
  2770. bbto.filter_policy = std::get<0>(GetParam());
  2771. bbto.whole_key_filtering = true;
  2772. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  2773. const CompressionType comp_type = std::get<1>(GetParam());
  2774. #if LZ4_VERSION_NUMBER < 10400 // r124+
  2775. if (comp_type == kLZ4Compression || comp_type == kLZ4HCCompression) {
  2776. return;
  2777. }
  2778. #endif // LZ4_VERSION_NUMBER >= 10400
  2779. if (!ZSTD_Supported() && comp_type == kZSTD) {
  2780. return;
  2781. }
  2782. if (!Zlib_Supported() && comp_type == kZlibCompression) {
  2783. return;
  2784. }
  2785. options.compression = comp_type;
  2786. options.compression_opts.max_dict_bytes = std::get<2>(GetParam());
  2787. if (comp_type == kZSTD) {
  2788. options.compression_opts.zstd_max_train_bytes = std::get<2>(GetParam());
  2789. }
  2790. options.compression_opts.parallel_threads = std::get<3>(GetParam());
  2791. DestroyAndReopen(options);
  2792. CreateAndReopenWithCF({"pikachu"}, options);
  2793. size_t num_cfs = handles_.size();
  2794. ASSERT_EQ(2, num_cfs);
  2795. std::vector<std::string> write_ts_list;
  2796. std::vector<std::string> read_ts_list;
  2797. const auto& verify_records_func = [&](size_t i, size_t begin, size_t end,
  2798. ColumnFamilyHandle* cfh) {
  2799. std::string value;
  2800. std::string timestamp;
  2801. ReadOptions ropts;
  2802. const Slice read_ts = read_ts_list[i];
  2803. ropts.timestamp = &read_ts;
  2804. std::string expected_timestamp =
  2805. std::string(write_ts_list[i].data(), write_ts_list[i].size());
  2806. for (size_t j = begin; j <= end; ++j) {
  2807. ASSERT_OK(db_->Get(ropts, cfh, Key1(j), &value, &timestamp));
  2808. ASSERT_EQ("value_" + std::to_string(j) + "_" + std::to_string(i), value);
  2809. ASSERT_EQ(expected_timestamp, timestamp);
  2810. }
  2811. };
  2812. for (size_t i = 0; i != kNumTimestamps; ++i) {
  2813. write_ts_list.push_back(Timestamp(i * 2, 0));
  2814. read_ts_list.push_back(Timestamp(1 + i * 2, 0));
  2815. const Slice write_ts = write_ts_list.back();
  2816. WriteOptions wopts;
  2817. for (int cf = 0; cf != static_cast<int>(num_cfs); ++cf) {
  2818. size_t memtable_get_start = 0;
  2819. for (size_t j = 0; j != kNumKeysPerTimestamp; ++j) {
  2820. ASSERT_OK(
  2821. db_->Put(wopts, handles_[cf], Key1(j), write_ts,
  2822. "value_" + std::to_string(j) + "_" + std::to_string(i)));
  2823. if (j == kSplitPosBase + i || j == kNumKeysPerTimestamp - 1) {
  2824. verify_records_func(i, memtable_get_start, j, handles_[cf]);
  2825. memtable_get_start = j + 1;
  2826. // flush all keys with the same timestamp to two sst files, split at
  2827. // incremental positions such that lowerlevel[1].smallest.userkey ==
  2828. // higherlevel[0].largest.userkey
  2829. ASSERT_OK(Flush(cf));
  2830. ASSERT_OK(dbfull()->TEST_WaitForCompact()); // wait for flush (which
  2831. // is also a compaction)
  2832. // compact files (2 at each level) to a lower level such that all
  2833. // keys with the same timestamp is at one level, with newer versions
  2834. // at higher levels.
  2835. CompactionOptions compact_opt;
  2836. compact_opt.compression = kNoCompression;
  2837. ASSERT_OK(db_->CompactFiles(compact_opt, handles_[cf],
  2838. collector->GetFlushedFiles(),
  2839. static_cast<int>(kNumTimestamps - i)));
  2840. collector->ClearFlushedFiles();
  2841. }
  2842. }
  2843. }
  2844. }
  2845. const auto& verify_db_func = [&]() {
  2846. for (size_t i = 0; i != kNumTimestamps; ++i) {
  2847. ReadOptions ropts;
  2848. const Slice read_ts = read_ts_list[i];
  2849. ropts.timestamp = &read_ts;
  2850. std::string expected_timestamp(write_ts_list[i].data(),
  2851. write_ts_list[i].size());
  2852. for (int cf = 0; cf != static_cast<int>(num_cfs); ++cf) {
  2853. ColumnFamilyHandle* cfh = handles_[cf];
  2854. verify_records_func(i, 0, kNumKeysPerTimestamp - 1, cfh);
  2855. }
  2856. }
  2857. };
  2858. verify_db_func();
  2859. Close();
  2860. }
  2861. TEST_F(DBBasicTestWithTimestamp, BatchWriteAndMultiGet) {
  2862. const int kNumKeysPerFile = 8192;
  2863. const size_t kNumTimestamps = 2;
  2864. const size_t kNumKeysPerTimestamp = (kNumKeysPerFile - 1) / kNumTimestamps;
  2865. Options options = CurrentOptions();
  2866. options.create_if_missing = true;
  2867. options.env = env_;
  2868. options.memtable_factory.reset(
  2869. test::NewSpecialSkipListFactory(kNumKeysPerFile));
  2870. options.memtable_prefix_bloom_size_ratio = 0.1;
  2871. options.memtable_whole_key_filtering = true;
  2872. size_t ts_sz = Timestamp(0, 0).size();
  2873. TestComparator test_cmp(ts_sz);
  2874. options.comparator = &test_cmp;
  2875. BlockBasedTableOptions bbto;
  2876. bbto.filter_policy.reset(NewBloomFilterPolicy(
  2877. 10 /*bits_per_key*/, false /*use_block_based_builder*/));
  2878. bbto.whole_key_filtering = true;
  2879. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  2880. DestroyAndReopen(options);
  2881. CreateAndReopenWithCF({"pikachu"}, options);
  2882. size_t num_cfs = handles_.size();
  2883. ASSERT_EQ(2, num_cfs);
  2884. std::vector<std::string> write_ts_list;
  2885. std::vector<std::string> read_ts_list;
  2886. const auto& verify_records_func = [&](size_t i, ColumnFamilyHandle* cfh) {
  2887. std::vector<Slice> keys;
  2888. std::vector<std::string> key_vals;
  2889. std::vector<std::string> values;
  2890. std::vector<std::string> timestamps;
  2891. for (size_t j = 0; j != kNumKeysPerTimestamp; ++j) {
  2892. key_vals.push_back(Key1(j));
  2893. }
  2894. for (size_t j = 0; j != kNumKeysPerTimestamp; ++j) {
  2895. keys.emplace_back(key_vals[j]);
  2896. }
  2897. ReadOptions ropts;
  2898. const Slice read_ts = read_ts_list[i];
  2899. ropts.timestamp = &read_ts;
  2900. std::string expected_timestamp(write_ts_list[i].data(),
  2901. write_ts_list[i].size());
  2902. std::vector<ColumnFamilyHandle*> cfhs(keys.size(), cfh);
  2903. std::vector<Status> statuses =
  2904. db_->MultiGet(ropts, cfhs, keys, &values, &timestamps);
  2905. for (size_t j = 0; j != kNumKeysPerTimestamp; ++j) {
  2906. ASSERT_OK(statuses[j]);
  2907. ASSERT_EQ("value_" + std::to_string(j) + "_" + std::to_string(i),
  2908. values[j]);
  2909. ASSERT_EQ(expected_timestamp, timestamps[j]);
  2910. }
  2911. };
  2912. const std::string dummy_ts(ts_sz, '\0');
  2913. for (size_t i = 0; i != kNumTimestamps; ++i) {
  2914. write_ts_list.push_back(Timestamp(i * 2, 0));
  2915. read_ts_list.push_back(Timestamp(1 + i * 2, 0));
  2916. const Slice& write_ts = write_ts_list.back();
  2917. for (int cf = 0; cf != static_cast<int>(num_cfs); ++cf) {
  2918. WriteOptions wopts;
  2919. WriteBatch batch(0, 0, 0, ts_sz);
  2920. for (size_t j = 0; j != kNumKeysPerTimestamp; ++j) {
  2921. const std::string key = Key1(j);
  2922. const std::string value =
  2923. "value_" + std::to_string(j) + "_" + std::to_string(i);
  2924. ASSERT_OK(batch.Put(handles_[cf], key, value));
  2925. }
  2926. ASSERT_OK(batch.UpdateTimestamps(write_ts,
  2927. [ts_sz](uint32_t) { return ts_sz; }));
  2928. ASSERT_OK(db_->Write(wopts, &batch));
  2929. verify_records_func(i, handles_[cf]);
  2930. ASSERT_OK(Flush(cf));
  2931. }
  2932. }
  2933. const auto& verify_db_func = [&]() {
  2934. for (size_t i = 0; i != kNumTimestamps; ++i) {
  2935. ReadOptions ropts;
  2936. const Slice read_ts = read_ts_list[i];
  2937. ropts.timestamp = &read_ts;
  2938. for (int cf = 0; cf != static_cast<int>(num_cfs); ++cf) {
  2939. ColumnFamilyHandle* cfh = handles_[cf];
  2940. verify_records_func(i, cfh);
  2941. }
  2942. }
  2943. };
  2944. verify_db_func();
  2945. Close();
  2946. }
  2947. TEST_F(DBBasicTestWithTimestamp, MultiGetNoReturnTs) {
  2948. Options options = CurrentOptions();
  2949. options.env = env_;
  2950. const size_t kTimestampSize = Timestamp(0, 0).size();
  2951. TestComparator test_cmp(kTimestampSize);
  2952. options.comparator = &test_cmp;
  2953. DestroyAndReopen(options);
  2954. WriteOptions write_opts;
  2955. std::string ts = Timestamp(1, 0);
  2956. ASSERT_OK(db_->Put(write_opts, "foo", ts, "value"));
  2957. ASSERT_OK(db_->Put(write_opts, "bar", ts, "value"));
  2958. ASSERT_OK(db_->Put(write_opts, "fooxxxxxxxxxxxxxxxx", ts, "value"));
  2959. ASSERT_OK(db_->Put(write_opts, "barxxxxxxxxxxxxxxxx", ts, "value"));
  2960. ColumnFamilyHandle* cfh = dbfull()->DefaultColumnFamily();
  2961. ts = Timestamp(2, 0);
  2962. Slice read_ts = ts;
  2963. ReadOptions read_opts;
  2964. read_opts.timestamp = &read_ts;
  2965. {
  2966. ColumnFamilyHandle* column_families[] = {cfh, cfh};
  2967. Slice keys[] = {"foo", "bar"};
  2968. PinnableSlice values[] = {PinnableSlice(), PinnableSlice()};
  2969. Status statuses[] = {Status::OK(), Status::OK()};
  2970. dbfull()->MultiGet(read_opts, /*num_keys=*/2, &column_families[0], &keys[0],
  2971. &values[0], &statuses[0], /*sorted_input=*/false);
  2972. for (const auto& s : statuses) {
  2973. ASSERT_OK(s);
  2974. }
  2975. }
  2976. {
  2977. ColumnFamilyHandle* column_families[] = {cfh, cfh, cfh, cfh};
  2978. // Make user keys longer than configured timestamp size (16 bytes) to
  2979. // verify RocksDB does not use the trailing bytes 'x' as timestamp.
  2980. Slice keys[] = {"fooxxxxxxxxxxxxxxxx", "barxxxxxxxxxxxxxxxx", "foo", "bar"};
  2981. PinnableSlice values[] = {PinnableSlice(), PinnableSlice(), PinnableSlice(),
  2982. PinnableSlice()};
  2983. Status statuses[] = {Status::OK(), Status::OK(), Status::OK(),
  2984. Status::OK()};
  2985. dbfull()->MultiGet(read_opts, /*num_keys=*/4, &column_families[0], &keys[0],
  2986. &values[0], &statuses[0], /*sorted_input=*/false);
  2987. for (const auto& s : statuses) {
  2988. ASSERT_OK(s);
  2989. }
  2990. }
  2991. Close();
  2992. }
  2993. INSTANTIATE_TEST_CASE_P(
  2994. Timestamp, DBBasicTestWithTimestampCompressionSettings,
  2995. ::testing::Combine(
  2996. ::testing::Values(std::shared_ptr<const FilterPolicy>(nullptr),
  2997. std::shared_ptr<const FilterPolicy>(
  2998. NewBloomFilterPolicy(10, false))),
  2999. ::testing::Values(kNoCompression, kZlibCompression, kLZ4Compression,
  3000. kLZ4HCCompression, kZSTD),
  3001. ::testing::Values(0, 1 << 14), ::testing::Values(1, 4)));
  3002. class DBBasicTestWithTimestampPrefixSeek
  3003. : public DBBasicTestWithTimestampBase,
  3004. public testing::WithParamInterface<
  3005. std::tuple<std::shared_ptr<const SliceTransform>,
  3006. std::shared_ptr<const FilterPolicy>, bool,
  3007. BlockBasedTableOptions::IndexType>> {
  3008. public:
  3009. DBBasicTestWithTimestampPrefixSeek()
  3010. : DBBasicTestWithTimestampBase(
  3011. "/db_basic_test_with_timestamp_prefix_seek") {}
  3012. };
  3013. TEST_P(DBBasicTestWithTimestampPrefixSeek, IterateWithPrefix) {
  3014. const size_t kNumKeysPerFile = 128;
  3015. Options options = CurrentOptions();
  3016. options.env = env_;
  3017. options.create_if_missing = true;
  3018. const size_t kTimestampSize = Timestamp(0, 0).size();
  3019. TestComparator test_cmp(kTimestampSize);
  3020. options.comparator = &test_cmp;
  3021. options.prefix_extractor = std::get<0>(GetParam());
  3022. options.memtable_factory.reset(
  3023. test::NewSpecialSkipListFactory(kNumKeysPerFile));
  3024. BlockBasedTableOptions bbto;
  3025. bbto.filter_policy = std::get<1>(GetParam());
  3026. bbto.index_type = std::get<3>(GetParam());
  3027. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  3028. DestroyAndReopen(options);
  3029. const uint64_t kMaxKey = 0xffffffffffffffff;
  3030. const uint64_t kMinKey = 0xfffffffffffff000;
  3031. const std::vector<std::string> write_ts_list = {Timestamp(3, 0xffffffff),
  3032. Timestamp(6, 0xffffffff)};
  3033. WriteOptions write_opts;
  3034. {
  3035. for (size_t i = 0; i != write_ts_list.size(); ++i) {
  3036. for (uint64_t key = kMaxKey; key >= kMinKey; --key) {
  3037. Status s = db_->Put(write_opts, Key1(key), write_ts_list[i],
  3038. "value" + std::to_string(i));
  3039. ASSERT_OK(s);
  3040. }
  3041. }
  3042. }
  3043. const std::vector<std::string> read_ts_list = {Timestamp(5, 0xffffffff),
  3044. Timestamp(9, 0xffffffff)};
  3045. {
  3046. ReadOptions read_opts;
  3047. read_opts.total_order_seek = false;
  3048. read_opts.prefix_same_as_start = std::get<2>(GetParam());
  3049. fprintf(stdout, "%s %s %d\n", options.prefix_extractor->Name(),
  3050. bbto.filter_policy ? bbto.filter_policy->Name() : "null",
  3051. static_cast<int>(read_opts.prefix_same_as_start));
  3052. for (size_t i = 0; i != read_ts_list.size(); ++i) {
  3053. Slice read_ts = read_ts_list[i];
  3054. read_opts.timestamp = &read_ts;
  3055. std::unique_ptr<Iterator> iter(db_->NewIterator(read_opts));
  3056. // Seek to kMaxKey
  3057. iter->Seek(Key1(kMaxKey));
  3058. CheckIterUserEntry(iter.get(), Key1(kMaxKey), kTypeValue,
  3059. "value" + std::to_string(i), write_ts_list[i]);
  3060. iter->Next();
  3061. ASSERT_FALSE(iter->Valid());
  3062. ASSERT_OK(iter->status());
  3063. // Seek to kMinKey
  3064. iter->Seek(Key1(kMinKey));
  3065. CheckIterUserEntry(iter.get(), Key1(kMinKey), kTypeValue,
  3066. "value" + std::to_string(i), write_ts_list[i]);
  3067. iter->Prev();
  3068. ASSERT_FALSE(iter->Valid());
  3069. ASSERT_OK(iter->status());
  3070. }
  3071. const std::vector<uint64_t> targets = {kMinKey, kMinKey + 0x10,
  3072. kMinKey + 0x100, kMaxKey};
  3073. const SliceTransform* const pe = options.prefix_extractor.get();
  3074. ASSERT_NE(nullptr, pe);
  3075. const size_t kPrefixShift =
  3076. 8 * (Key1(0).size() - pe->Transform(Key1(0)).size());
  3077. const uint64_t kPrefixMask =
  3078. ~((static_cast<uint64_t>(1) << kPrefixShift) - 1);
  3079. const uint64_t kNumKeysWithinPrefix =
  3080. (static_cast<uint64_t>(1) << kPrefixShift);
  3081. for (size_t i = 0; i != read_ts_list.size(); ++i) {
  3082. Slice read_ts = read_ts_list[i];
  3083. read_opts.timestamp = &read_ts;
  3084. std::unique_ptr<Iterator> it(db_->NewIterator(read_opts));
  3085. // Forward and backward iterate.
  3086. for (size_t j = 0; j != targets.size(); ++j) {
  3087. std::string start_key = Key1(targets[j]);
  3088. uint64_t expected_ub =
  3089. (targets[j] & kPrefixMask) - 1 + kNumKeysWithinPrefix;
  3090. uint64_t expected_key = targets[j];
  3091. size_t count = 0;
  3092. it->Seek(Key1(targets[j]));
  3093. while (it->Valid()) {
  3094. std::string saved_prev_key;
  3095. saved_prev_key.assign(it->key().data(), it->key().size());
  3096. // Out of prefix
  3097. if (!read_opts.prefix_same_as_start &&
  3098. pe->Transform(saved_prev_key) != pe->Transform(start_key)) {
  3099. break;
  3100. }
  3101. CheckIterUserEntry(it.get(), Key1(expected_key), kTypeValue,
  3102. "value" + std::to_string(i), write_ts_list[i]);
  3103. ++count;
  3104. ++expected_key;
  3105. it->Next();
  3106. }
  3107. ASSERT_OK(it->status());
  3108. ASSERT_EQ(expected_ub - targets[j] + 1, count);
  3109. count = 0;
  3110. expected_key = targets[j];
  3111. it->SeekForPrev(start_key);
  3112. uint64_t expected_lb = (targets[j] & kPrefixMask);
  3113. while (it->Valid()) {
  3114. // Out of prefix
  3115. if (!read_opts.prefix_same_as_start &&
  3116. pe->Transform(it->key()) != pe->Transform(start_key)) {
  3117. break;
  3118. }
  3119. CheckIterUserEntry(it.get(), Key1(expected_key), kTypeValue,
  3120. "value" + std::to_string(i), write_ts_list[i]);
  3121. ++count;
  3122. --expected_key;
  3123. it->Prev();
  3124. }
  3125. ASSERT_OK(it->status());
  3126. ASSERT_EQ(targets[j] - std::max(expected_lb, kMinKey) + 1, count);
  3127. }
  3128. }
  3129. }
  3130. Close();
  3131. }
  3132. // TODO(yanqin): consider handling non-fixed-length prefix extractors, e.g.
  3133. // NoopTransform.
  3134. INSTANTIATE_TEST_CASE_P(
  3135. Timestamp, DBBasicTestWithTimestampPrefixSeek,
  3136. ::testing::Combine(
  3137. ::testing::Values(
  3138. std::shared_ptr<const SliceTransform>(NewFixedPrefixTransform(1)),
  3139. std::shared_ptr<const SliceTransform>(NewFixedPrefixTransform(4)),
  3140. std::shared_ptr<const SliceTransform>(NewFixedPrefixTransform(7)),
  3141. std::shared_ptr<const SliceTransform>(NewFixedPrefixTransform(8))),
  3142. ::testing::Values(std::shared_ptr<const FilterPolicy>(nullptr),
  3143. std::shared_ptr<const FilterPolicy>(
  3144. NewBloomFilterPolicy(10 /*bits_per_key*/, false)),
  3145. std::shared_ptr<const FilterPolicy>(
  3146. NewBloomFilterPolicy(20 /*bits_per_key*/,
  3147. false))),
  3148. ::testing::Bool(),
  3149. ::testing::Values(
  3150. BlockBasedTableOptions::IndexType::kBinarySearch,
  3151. BlockBasedTableOptions::IndexType::kHashSearch,
  3152. BlockBasedTableOptions::IndexType::kTwoLevelIndexSearch,
  3153. BlockBasedTableOptions::IndexType::kBinarySearchWithFirstKey)));
  3154. class DBBasicTestWithTsIterTombstones
  3155. : public DBBasicTestWithTimestampBase,
  3156. public testing::WithParamInterface<
  3157. std::tuple<std::shared_ptr<const SliceTransform>,
  3158. std::shared_ptr<const FilterPolicy>, int,
  3159. BlockBasedTableOptions::IndexType>> {
  3160. public:
  3161. DBBasicTestWithTsIterTombstones()
  3162. : DBBasicTestWithTimestampBase("/db_basic_ts_iter_tombstones") {}
  3163. };
  3164. TEST_P(DBBasicTestWithTsIterTombstones, IterWithDelete) {
  3165. constexpr size_t kNumKeysPerFile = 128;
  3166. Options options = CurrentOptions();
  3167. options.env = env_;
  3168. const size_t kTimestampSize = Timestamp(0, 0).size();
  3169. TestComparator test_cmp(kTimestampSize);
  3170. options.comparator = &test_cmp;
  3171. options.prefix_extractor = std::get<0>(GetParam());
  3172. options.memtable_factory.reset(
  3173. test::NewSpecialSkipListFactory(kNumKeysPerFile));
  3174. BlockBasedTableOptions bbto;
  3175. bbto.filter_policy = std::get<1>(GetParam());
  3176. bbto.index_type = std::get<3>(GetParam());
  3177. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  3178. options.num_levels = std::get<2>(GetParam());
  3179. DestroyAndReopen(options);
  3180. std::vector<std::string> write_ts_strs = {Timestamp(2, 0), Timestamp(4, 0)};
  3181. constexpr uint64_t kMaxKey = 0xffffffffffffffff;
  3182. constexpr uint64_t kMinKey = 0xfffffffffffff000;
  3183. // Insert kMinKey...kMaxKey
  3184. uint64_t key = kMinKey;
  3185. WriteOptions write_opts;
  3186. Slice ts = write_ts_strs[0];
  3187. do {
  3188. Status s = db_->Put(write_opts, Key1(key), write_ts_strs[0],
  3189. "value" + std::to_string(key));
  3190. ASSERT_OK(s);
  3191. if (kMaxKey == key) {
  3192. break;
  3193. }
  3194. ++key;
  3195. } while (true);
  3196. for (key = kMaxKey; key >= kMinKey; --key) {
  3197. Status s;
  3198. if (0 != (key % 2)) {
  3199. s = db_->Put(write_opts, Key1(key), write_ts_strs[1],
  3200. "value1" + std::to_string(key));
  3201. } else {
  3202. s = db_->Delete(write_opts, Key1(key), write_ts_strs[1]);
  3203. }
  3204. ASSERT_OK(s);
  3205. }
  3206. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  3207. {
  3208. std::string read_ts = Timestamp(4, 0);
  3209. ts = read_ts;
  3210. ReadOptions read_opts;
  3211. read_opts.total_order_seek = true;
  3212. read_opts.timestamp = &ts;
  3213. std::unique_ptr<Iterator> iter(db_->NewIterator(read_opts));
  3214. size_t count = 0;
  3215. key = kMinKey + 1;
  3216. for (iter->SeekToFirst(); iter->Valid(); iter->Next(), ++count, key += 2) {
  3217. ASSERT_EQ(Key1(key), iter->key());
  3218. ASSERT_EQ("value1" + std::to_string(key), iter->value());
  3219. }
  3220. ASSERT_EQ((kMaxKey - kMinKey + 1) / 2, count);
  3221. for (iter->SeekToLast(), count = 0, key = kMaxKey; iter->Valid();
  3222. key -= 2, ++count, iter->Prev()) {
  3223. ASSERT_EQ(Key1(key), iter->key());
  3224. ASSERT_EQ("value1" + std::to_string(key), iter->value());
  3225. }
  3226. ASSERT_OK(iter->status());
  3227. ASSERT_EQ((kMaxKey - kMinKey + 1) / 2, count);
  3228. }
  3229. Close();
  3230. }
  3231. INSTANTIATE_TEST_CASE_P(
  3232. Timestamp, DBBasicTestWithTsIterTombstones,
  3233. ::testing::Combine(
  3234. ::testing::Values(
  3235. std::shared_ptr<const SliceTransform>(NewFixedPrefixTransform(7)),
  3236. std::shared_ptr<const SliceTransform>(NewFixedPrefixTransform(8))),
  3237. ::testing::Values(std::shared_ptr<const FilterPolicy>(nullptr),
  3238. std::shared_ptr<const FilterPolicy>(
  3239. NewBloomFilterPolicy(10, false)),
  3240. std::shared_ptr<const FilterPolicy>(
  3241. NewBloomFilterPolicy(20, false))),
  3242. ::testing::Values(2, 6),
  3243. ::testing::Values(
  3244. BlockBasedTableOptions::IndexType::kBinarySearch,
  3245. BlockBasedTableOptions::IndexType::kHashSearch,
  3246. BlockBasedTableOptions::IndexType::kTwoLevelIndexSearch,
  3247. BlockBasedTableOptions::IndexType::kBinarySearchWithFirstKey)));
  3248. #endif // !defined(ROCKSDB_VALGRIND_RUN) || defined(ROCKSDB_FULL_VALGRIND_RUN)
  3249. class UpdateFullHistoryTsLowTest : public DBBasicTestWithTimestampBase {
  3250. public:
  3251. UpdateFullHistoryTsLowTest()
  3252. : DBBasicTestWithTimestampBase("/update_full_history_ts_low_test") {}
  3253. };
  3254. TEST_F(UpdateFullHistoryTsLowTest, ConcurrentUpdate) {
  3255. Options options = CurrentOptions();
  3256. options.env = env_;
  3257. options.create_if_missing = true;
  3258. std::string lower_ts_low = Timestamp(10, 0);
  3259. std::string higher_ts_low = Timestamp(25, 0);
  3260. const size_t kTimestampSize = lower_ts_low.size();
  3261. TestComparator test_cmp(kTimestampSize);
  3262. options.comparator = &test_cmp;
  3263. DestroyAndReopen(options);
  3264. SyncPoint::GetInstance()->DisableProcessing();
  3265. SyncPoint::GetInstance()->ClearAllCallBacks();
  3266. // This workaround swaps `lower_ts_low` originally used for update by the
  3267. // caller to `higher_ts_low` after its writer is queued to make sure
  3268. // the caller will always get a TryAgain error.
  3269. // It mimics cases where two threads update full_history_ts_low concurrently
  3270. // with one thread writing a higher ts_low and one thread writing a lower
  3271. // ts_low.
  3272. VersionEdit* version_edit;
  3273. SyncPoint::GetInstance()->SetCallBack(
  3274. "DBImpl::IncreaseFullHistoryTsLowImpl:BeforeEdit",
  3275. [&](void* arg) { version_edit = static_cast<VersionEdit*>(arg); });
  3276. SyncPoint::GetInstance()->SetCallBack(
  3277. "VersionSet::LogAndApply:BeforeWriterWaiting",
  3278. [&](void* /*arg*/) { version_edit->SetFullHistoryTsLow(higher_ts_low); });
  3279. SyncPoint::GetInstance()->EnableProcessing();
  3280. ASSERT_TRUE(
  3281. db_->IncreaseFullHistoryTsLow(db_->DefaultColumnFamily(), lower_ts_low)
  3282. .IsTryAgain());
  3283. SyncPoint::GetInstance()->DisableProcessing();
  3284. SyncPoint::GetInstance()->ClearAllCallBacks();
  3285. Close();
  3286. }
  3287. // Tests the effect of flag `persist_user_defined_timestamps` on the file
  3288. // boundaries contained in the Manifest, a.k.a FileMetaData.smallest,
  3289. // FileMetaData.largest.
  3290. class HandleFileBoundariesTest
  3291. : public DBBasicTestWithTimestampBase,
  3292. public testing::WithParamInterface<test::UserDefinedTimestampTestMode> {
  3293. public:
  3294. HandleFileBoundariesTest()
  3295. : DBBasicTestWithTimestampBase("/handle_file_boundaries") {}
  3296. };
  3297. TEST_P(HandleFileBoundariesTest, ConfigurePersistUdtWithPut) {
  3298. Options options = CurrentOptions();
  3299. options.env = env_;
  3300. // Write a timestamp that is not the min timestamp to help test the behavior
  3301. // of flag `persist_user_defined_timestamps`.
  3302. std::string write_ts;
  3303. std::string min_ts;
  3304. PutFixed64(&write_ts, 1);
  3305. PutFixed64(&min_ts, 0);
  3306. std::string smallest_ukey_without_ts = "bar";
  3307. std::string largest_ukey_without_ts = "foo";
  3308. options.comparator = test::BytewiseComparatorWithU64TsWrapper();
  3309. bool persist_udt = test::ShouldPersistUDT(GetParam());
  3310. options.persist_user_defined_timestamps = persist_udt;
  3311. if (!persist_udt) {
  3312. options.allow_concurrent_memtable_write = false;
  3313. }
  3314. DestroyAndReopen(options);
  3315. ASSERT_OK(
  3316. db_->Put(WriteOptions(), smallest_ukey_without_ts, write_ts, "val1"));
  3317. ASSERT_OK(
  3318. db_->Put(WriteOptions(), largest_ukey_without_ts, write_ts, "val2"));
  3319. // Create a L0 SST file and its record is added to the Manifest.
  3320. ASSERT_OK(Flush());
  3321. Close();
  3322. options.create_if_missing = false;
  3323. // Reopen the DB and process manifest file.
  3324. Reopen(options);
  3325. std::vector<std::vector<FileMetaData>> level_to_files;
  3326. dbfull()->TEST_GetFilesMetaData(dbfull()->DefaultColumnFamily(),
  3327. &level_to_files);
  3328. ASSERT_GT(level_to_files.size(), 1);
  3329. // L0 only has one SST file.
  3330. ASSERT_EQ(level_to_files[0].size(), 1);
  3331. auto file_meta = level_to_files[0][0];
  3332. if (persist_udt) {
  3333. ASSERT_EQ(smallest_ukey_without_ts + write_ts,
  3334. file_meta.smallest.user_key());
  3335. ASSERT_EQ(largest_ukey_without_ts + write_ts, file_meta.largest.user_key());
  3336. } else {
  3337. // If `persist_user_defined_timestamps` is false, the file boundaries should
  3338. // have the min timestamp. Behind the scenes, when file boundaries in
  3339. // FileMetaData is persisted to Manifest, the original user-defined
  3340. // timestamps in user key are stripped. When manifest is read and processed
  3341. // during DB open, a min timestamp is padded to the file boundaries. This
  3342. // test's writes contain non min timestamp to verify this logic end-to-end.
  3343. ASSERT_EQ(smallest_ukey_without_ts + min_ts, file_meta.smallest.user_key());
  3344. ASSERT_EQ(largest_ukey_without_ts + min_ts, file_meta.largest.user_key());
  3345. }
  3346. Close();
  3347. }
  3348. TEST_P(HandleFileBoundariesTest, ConfigurePersistUdtWithRangeDelete) {
  3349. Options options = CurrentOptions();
  3350. options.env = env_;
  3351. // Write a timestamp that is not the min/max timestamp to help test the
  3352. // behavior of flag `persist_user_defined_timestamps`.
  3353. std::string write_ts;
  3354. std::string min_ts;
  3355. std::string max_ts;
  3356. PutFixed64(&write_ts, 1);
  3357. PutFixed64(&min_ts, 0);
  3358. PutFixed64(&max_ts, std::numeric_limits<uint64_t>::max());
  3359. std::string smallest_ukey_without_ts = "bar";
  3360. std::string largest_ukey_without_ts = "foo";
  3361. options.comparator = test::BytewiseComparatorWithU64TsWrapper();
  3362. bool persist_udt = test::ShouldPersistUDT(GetParam());
  3363. options.persist_user_defined_timestamps = persist_udt;
  3364. if (!persist_udt) {
  3365. options.allow_concurrent_memtable_write = false;
  3366. }
  3367. DestroyAndReopen(options);
  3368. ASSERT_OK(db_->DeleteRange(WriteOptions(), db_->DefaultColumnFamily(),
  3369. smallest_ukey_without_ts, largest_ukey_without_ts,
  3370. write_ts));
  3371. // Create a L0 SST file and its record is added to the Manifest.
  3372. ASSERT_OK(Flush());
  3373. Close();
  3374. options.create_if_missing = false;
  3375. // Reopen the DB and process manifest file.
  3376. Reopen(options);
  3377. std::vector<std::vector<FileMetaData>> level_to_files;
  3378. dbfull()->TEST_GetFilesMetaData(dbfull()->DefaultColumnFamily(),
  3379. &level_to_files);
  3380. ASSERT_GT(level_to_files.size(), 1);
  3381. // L0 only has one SST file.
  3382. ASSERT_EQ(level_to_files[0].size(), 1);
  3383. auto file_meta = level_to_files[0][0];
  3384. if (persist_udt) {
  3385. ASSERT_EQ(smallest_ukey_without_ts + write_ts,
  3386. file_meta.smallest.user_key());
  3387. } else {
  3388. ASSERT_EQ(smallest_ukey_without_ts + min_ts, file_meta.smallest.user_key());
  3389. }
  3390. // When right file boundary comes from range deletion, it uses max timestamp
  3391. // and a range deletion sentinel that uses the max sequence number to mark the
  3392. // end key exclusive. This is regardless of whether timestamp is persisted.
  3393. ASSERT_EQ(largest_ukey_without_ts + max_ts, file_meta.largest.user_key());
  3394. auto largest_footer = ExtractInternalKeyFooter(file_meta.largest.Encode());
  3395. ASSERT_EQ(largest_footer, kRangeTombstoneSentinel);
  3396. Close();
  3397. }
  3398. INSTANTIATE_TEST_CASE_P(
  3399. ConfigurePersistUdt, HandleFileBoundariesTest,
  3400. ::testing::Values(
  3401. test::UserDefinedTimestampTestMode::kStripUserDefinedTimestamp,
  3402. test::UserDefinedTimestampTestMode::kNormal));
  3403. // Test params:
  3404. // 1) whether to flush before close
  3405. class EnableDisableUDTTest : public DBBasicTestWithTimestampBase,
  3406. public testing::WithParamInterface<bool> {
  3407. public:
  3408. EnableDisableUDTTest()
  3409. : DBBasicTestWithTimestampBase("/enable_disable_udt") {}
  3410. };
  3411. INSTANTIATE_TEST_CASE_P(EnableDisableUDTTest, EnableDisableUDTTest,
  3412. ::testing::Values(true, false));
  3413. TEST_P(EnableDisableUDTTest, Basic) {
  3414. Options options = CurrentOptions();
  3415. // Un-flushed data before close will involve a WAL replay on DB reopen.
  3416. bool flush_before_close = GetParam();
  3417. options.env = env_;
  3418. options.comparator = BytewiseComparator();
  3419. options.persist_user_defined_timestamps = true;
  3420. DestroyAndReopen(options);
  3421. ReadOptions ropts;
  3422. std::string read_ts;
  3423. std::string value;
  3424. std::string key_ts;
  3425. // Create one SST file, its user keys have no user-defined timestamps.
  3426. ASSERT_OK(db_->Put(WriteOptions(), "foo", "val0"));
  3427. ASSERT_OK(db_->Put(WriteOptions(), "bar", "val0"));
  3428. ASSERT_OK(db_->DeleteRange(WriteOptions(), "bar", "baz"));
  3429. ASSERT_OK(db_->Get(ReadOptions(), "foo", &value));
  3430. ASSERT_EQ("val0", value);
  3431. ASSERT_TRUE(db_->Get(ReadOptions(), "bar", &value).IsNotFound());
  3432. if (flush_before_close) {
  3433. ASSERT_OK(Flush(0));
  3434. }
  3435. Close();
  3436. // Reopen the existing column family and enable user-defined timestamps
  3437. // feature for it.
  3438. options.comparator = test::BytewiseComparatorWithU64TsWrapper();
  3439. options.persist_user_defined_timestamps = false;
  3440. options.allow_concurrent_memtable_write = false;
  3441. Reopen(options);
  3442. // Read data from previous session before and after compaction.
  3443. read_ts = EncodeAsUint64(1);
  3444. Slice read_ts_slice = read_ts;
  3445. ropts.timestamp = &read_ts_slice;
  3446. for (int i = 0; i < 2; i++) {
  3447. ASSERT_TRUE(db_->Get(ReadOptions(), "foo", &value).IsInvalidArgument());
  3448. // Entries in pre-existing SST files are treated as if they have minimum
  3449. // user-defined timestamps.
  3450. ASSERT_OK(db_->Get(ropts, "foo", &value, &key_ts));
  3451. ASSERT_EQ("val0", value);
  3452. ASSERT_EQ(EncodeAsUint64(0), key_ts);
  3453. ASSERT_TRUE(db_->Get(ropts, "bar", &value, &key_ts).IsNotFound());
  3454. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  3455. }
  3456. // Do timestamped read / write.
  3457. ASSERT_OK(db_->Put(WriteOptions(), "foo", EncodeAsUint64(1), "val1"));
  3458. ASSERT_OK(db_->Put(WriteOptions(), "bar", EncodeAsUint64(1), "val1"));
  3459. ASSERT_OK(db_->DeleteRange(WriteOptions(), "bar", "baz", EncodeAsUint64(2)));
  3460. ASSERT_OK(db_->Get(ropts, "foo", &value, &key_ts));
  3461. ASSERT_EQ("val1", value);
  3462. ASSERT_EQ(EncodeAsUint64(1), key_ts);
  3463. ASSERT_OK(db_->Get(ropts, "bar", &value, &key_ts));
  3464. ASSERT_EQ("val1", value);
  3465. ASSERT_EQ(EncodeAsUint64(1), key_ts);
  3466. read_ts = EncodeAsUint64(2);
  3467. ASSERT_TRUE(db_->Get(ropts, "bar", &value, &key_ts).IsNotFound());
  3468. // The user keys in this SST file don't have user-defined timestamps either,
  3469. // because `persist_user_defined_timestamps` flag is set to false.
  3470. if (flush_before_close) {
  3471. ASSERT_OK(Flush(0));
  3472. }
  3473. Close();
  3474. // Reopen the existing column family while disabling user-defined timestamps.
  3475. options.comparator = BytewiseComparator();
  3476. Reopen(options);
  3477. // Read data from previous session before and after compaction.
  3478. for (int i = 0; i < 2; i++) {
  3479. ASSERT_TRUE(db_->Get(ropts, "foo", &value).IsInvalidArgument());
  3480. ASSERT_OK(db_->Get(ReadOptions(), "foo", &value));
  3481. ASSERT_EQ("val1", value);
  3482. ASSERT_TRUE(db_->Get(ReadOptions(), "bar", &value).IsNotFound());
  3483. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  3484. }
  3485. // Continue to write / read the column family without user-defined timestamps.
  3486. ASSERT_OK(db_->Put(WriteOptions(), "foo", "val2"));
  3487. ASSERT_OK(db_->Put(WriteOptions(), "bar", "val2"));
  3488. ASSERT_OK(db_->DeleteRange(WriteOptions(), "bar", "baz"));
  3489. ASSERT_OK(db_->Get(ReadOptions(), "foo", &value));
  3490. ASSERT_EQ("val2", value);
  3491. ASSERT_TRUE(db_->Get(ReadOptions(), "bar", &value).IsNotFound());
  3492. if (flush_before_close) {
  3493. ASSERT_OK(Flush(0));
  3494. }
  3495. Close();
  3496. }
  3497. // Tests that as long as the
  3498. // `ReadOptions.timestamp >= SuperVersion.full_history_ts_low` sanity check
  3499. // passes. The read will be consistent even if the column family's
  3500. // full_history_ts_low is concurrently increased and collapsed some history
  3501. // above `ReadOptions.timestamp`.
  3502. TEST_F(DBBasicTestWithTimestamp,
  3503. FullHistoryTsLowSanityCheckPassReadIsConsistent) {
  3504. Options options = CurrentOptions();
  3505. options.env = env_;
  3506. options.comparator = test::BytewiseComparatorWithU64TsWrapper();
  3507. // Use UDT in memtable only feature for this test, so we can control that
  3508. // newly set `full_history_ts_low` collapse history when Flush happens.
  3509. options.persist_user_defined_timestamps = false;
  3510. options.allow_concurrent_memtable_write = false;
  3511. DestroyAndReopen(options);
  3512. std::string min_ts;
  3513. PutFixed64(&min_ts, 0);
  3514. // Write two versions of the key (1, v1), (3, v3), and always read with
  3515. // timestamp 2.
  3516. std::string write_ts;
  3517. PutFixed64(&write_ts, 1);
  3518. ASSERT_OK(db_->Put(WriteOptions(), "foo", write_ts, "val1"));
  3519. std::string read_ts;
  3520. PutFixed64(&read_ts, 2);
  3521. Slice read_ts_slice = read_ts;
  3522. ReadOptions read_opts;
  3523. read_opts.timestamp = &read_ts_slice;
  3524. // First read, no full_history_ts_low set, sanity check pass.
  3525. std::string value;
  3526. std::string timestamp;
  3527. ASSERT_OK(db_->Get(read_opts, "foo", &value, &timestamp));
  3528. ASSERT_EQ("val1", value);
  3529. ASSERT_EQ(write_ts, timestamp);
  3530. std::string full_history_ts_low;
  3531. std::string marked_ts_low;
  3532. PutFixed64(&full_history_ts_low, 2);
  3533. marked_ts_low = full_history_ts_low;
  3534. ASSERT_OK(db_->IncreaseFullHistoryTsLow(db_->DefaultColumnFamily(),
  3535. full_history_ts_low));
  3536. ASSERT_OK(Flush(0));
  3537. // Write the (3, v3) entry after flush, otherwise with UDT in memtable only
  3538. // the previous Flush(0) with full_history_ts_low = 2 will be postponed
  3539. // waiting for (3, v3) to expire too.
  3540. write_ts.clear();
  3541. PutFixed64(&write_ts, 3);
  3542. ASSERT_OK(db_->Put(WriteOptions(), "foo", write_ts, "val3"));
  3543. // Second read:
  3544. // ReadOptions.timestamp(2) >= SuperVersion.full_history_ts_low(2),
  3545. // and ReadOptions.timestamp(2) >= ColumnFamilyData.full_history_ts_low(2).
  3546. // history below 2 is collapsed. Reading at 2 or above 2 is ok.
  3547. // Sanity check pass. Read return consistent value, but timestamp is already
  3548. // collapsed.
  3549. ASSERT_OK(db_->Get(read_opts, "foo", &value, &timestamp));
  3550. ASSERT_EQ("val1", value);
  3551. ASSERT_EQ(min_ts, timestamp);
  3552. SyncPoint::GetInstance()->SetCallBack(
  3553. "DBImpl::GetImpl:AfterAcquireSv", [&](void* /*arg*/) {
  3554. // Concurrently increasing full_history_ts_low and flush to create a
  3555. // new SuperVersion
  3556. std::string current_ts_low;
  3557. ASSERT_OK(db_->GetFullHistoryTsLow(db_->DefaultColumnFamily(),
  3558. &current_ts_low));
  3559. if (current_ts_low.empty() || current_ts_low != marked_ts_low) {
  3560. return;
  3561. }
  3562. full_history_ts_low.clear();
  3563. PutFixed64(&full_history_ts_low, 4);
  3564. ASSERT_OK(db_->IncreaseFullHistoryTsLow(db_->DefaultColumnFamily(),
  3565. full_history_ts_low));
  3566. ASSERT_OK(Flush(0));
  3567. });
  3568. SyncPoint::GetInstance()->EnableProcessing();
  3569. // Third read:
  3570. // ReadOptions.timestamp(2) >= SuperVersion.full_history_ts_low(2),
  3571. // but ReadOptions.timestamp(2) < ColumnFamilyData.full_history_ts_low(4).
  3572. // History below 4 is collapsed in the newly installed SuperVersion. But the
  3573. // SuperVersion attached to this read still has the history below 4 available.
  3574. // Sanity check pass. Read return consistent value, timestamp is collapsed.
  3575. ASSERT_OK(db_->Get(read_opts, "foo", &value, &timestamp));
  3576. ASSERT_EQ("val1", value);
  3577. ASSERT_EQ(min_ts, timestamp);
  3578. // Fourth read:
  3579. // ReadOptions.timestamp(2) < SuperVersion.full_history_ts_low(4).
  3580. // Sanity check fails. Had it succeeded, the read would return "v3",
  3581. // which is inconsistent.
  3582. ASSERT_TRUE(
  3583. db_->Get(read_opts, "foo", &value, &timestamp).IsInvalidArgument());
  3584. Close();
  3585. SyncPoint::GetInstance()->DisableProcessing();
  3586. SyncPoint::GetInstance()->ClearAllCallBacks();
  3587. }
  3588. // Tests that in cases when
  3589. // `ReadOptions.timestamp >= SuperVersion.full_history_ts_low` sanity check
  3590. // fails. The referenced SuperVersion is dereferenced and cleaned up properly
  3591. // for all read APIs that involves this sanity check.
  3592. TEST_F(DBBasicTestWithTimestamp, FullHistoryTsLowSanityCheckFail) {
  3593. Options options = CurrentOptions();
  3594. options.env = env_;
  3595. options.comparator = test::BytewiseComparatorWithU64TsWrapper();
  3596. // Use UDT in memtable only feature for this test, so we can control that
  3597. // newly set `full_history_ts_low` collapse history when Flush happens.
  3598. options.persist_user_defined_timestamps = false;
  3599. options.allow_concurrent_memtable_write = false;
  3600. DestroyAndReopen(options);
  3601. ColumnFamilyHandle* handle2 = nullptr;
  3602. Status s = db_->CreateColumnFamily(options, "data", &handle2);
  3603. ASSERT_OK(s);
  3604. std::string write_ts;
  3605. PutFixed64(&write_ts, 1);
  3606. ASSERT_OK(db_->Put(WriteOptions(), "foo", write_ts, "val1"));
  3607. ASSERT_OK(db_->Put(WriteOptions(), handle2, "foo", write_ts, "val1"));
  3608. std::string full_history_ts_low;
  3609. PutFixed64(&full_history_ts_low, 3);
  3610. ASSERT_OK(db_->IncreaseFullHistoryTsLow(db_->DefaultColumnFamily(),
  3611. full_history_ts_low));
  3612. ASSERT_OK(db_->IncreaseFullHistoryTsLow(handle2, full_history_ts_low));
  3613. ASSERT_OK(Flush(0));
  3614. ASSERT_OK(db_->Flush(FlushOptions(), handle2));
  3615. std::string read_ts;
  3616. PutFixed64(&read_ts, 2);
  3617. Slice read_ts_slice = read_ts;
  3618. ReadOptions read_opts;
  3619. read_opts.timestamp = &read_ts_slice;
  3620. // Get()
  3621. std::string value;
  3622. ASSERT_TRUE(db_->Get(read_opts, "foo", &value).IsInvalidArgument());
  3623. // MultiGet()
  3624. std::vector<ColumnFamilyHandle*> cfhs = {db_->DefaultColumnFamily(), handle2};
  3625. {
  3626. std::vector<std::string> key_vals = {"foo", "foo"};
  3627. std::vector<Slice> keys;
  3628. std::vector<std::string> values;
  3629. for (size_t j = 0; j < 2; ++j) {
  3630. keys.emplace_back(key_vals[j]);
  3631. }
  3632. std::vector<Status> statuses =
  3633. db_->MultiGet(read_opts, cfhs, keys, &values);
  3634. for (const auto& status : statuses) {
  3635. ASSERT_TRUE(status.IsInvalidArgument());
  3636. }
  3637. }
  3638. // MultiGet with only one column family
  3639. {
  3640. std::vector<ColumnFamilyHandle*> one_cfh = {db_->DefaultColumnFamily()};
  3641. std::vector<std::string> key_vals = {"foo"};
  3642. std::vector<Slice> keys;
  3643. std::vector<std::string> values;
  3644. for (size_t j = 0; j < 1; ++j) {
  3645. keys.emplace_back(key_vals[j]);
  3646. }
  3647. std::vector<Status> statuses =
  3648. db_->MultiGet(read_opts, one_cfh, keys, &values);
  3649. for (const auto& status : statuses) {
  3650. ASSERT_TRUE(status.IsInvalidArgument());
  3651. }
  3652. }
  3653. // Overloaded version of MultiGet
  3654. ColumnFamilyHandle* column_families[] = {db_->DefaultColumnFamily(), handle2};
  3655. {
  3656. Slice keys[] = {"foo", "foo"};
  3657. PinnableSlice values[] = {PinnableSlice(), PinnableSlice()};
  3658. Status statuses[] = {Status::OK(), Status::OK()};
  3659. db_->MultiGet(read_opts, /*num_keys=*/2, &column_families[0], &keys[0],
  3660. &values[0], &statuses[0], /*sorted_input=*/false);
  3661. for (const auto& status : statuses) {
  3662. ASSERT_TRUE(status.IsInvalidArgument());
  3663. }
  3664. }
  3665. // Overloaded versions of MultiGet with one column family
  3666. {
  3667. ColumnFamilyHandle* one_column_family[] = {db_->DefaultColumnFamily()};
  3668. Slice keys[] = {"foo"};
  3669. PinnableSlice values[] = {PinnableSlice()};
  3670. Status statuses[] = {Status::OK()};
  3671. db_->MultiGet(read_opts, /*num_keys=*/1, &one_column_family[0], &keys[0],
  3672. &values[0], &statuses[0], /*sorted_input=*/false);
  3673. for (const auto& status : statuses) {
  3674. ASSERT_TRUE(status.IsInvalidArgument());
  3675. }
  3676. }
  3677. // NewIterator()
  3678. std::unique_ptr<Iterator> iter(
  3679. db_->NewIterator(read_opts, db_->DefaultColumnFamily()));
  3680. ASSERT_TRUE(iter->status().IsInvalidArgument());
  3681. std::unique_ptr<Iterator> iter2(db_->NewIterator(read_opts, handle2));
  3682. ASSERT_TRUE(iter2->status().IsInvalidArgument());
  3683. // NewIterators()
  3684. std::vector<Iterator*> iterators;
  3685. ASSERT_TRUE(
  3686. db_->NewIterators(read_opts, cfhs, &iterators).IsInvalidArgument());
  3687. delete handle2;
  3688. Close();
  3689. }
  3690. TEST_F(DBBasicTestWithTimestamp,
  3691. GCPreserveRangeTombstoneWhenNoOrSmallFullHistoryLow) {
  3692. Options options = CurrentOptions();
  3693. options.env = env_;
  3694. options.create_if_missing = true;
  3695. const size_t kTimestampSize = Timestamp(0, 0).size();
  3696. TestComparator test_cmp(kTimestampSize);
  3697. options.comparator = &test_cmp;
  3698. DestroyAndReopen(options);
  3699. std::string ts_str = Timestamp(1, 0);
  3700. WriteOptions wopts;
  3701. ASSERT_OK(db_->Put(wopts, "k1", ts_str, "v1"));
  3702. ASSERT_OK(db_->Put(wopts, "k2", ts_str, "v2"));
  3703. ASSERT_OK(db_->Put(wopts, "k3", ts_str, "v3"));
  3704. ts_str = Timestamp(2, 0);
  3705. ASSERT_OK(
  3706. db_->DeleteRange(wopts, db_->DefaultColumnFamily(), "k1", "k3", ts_str));
  3707. ts_str = Timestamp(3, 0);
  3708. Slice ts = ts_str;
  3709. ReadOptions ropts;
  3710. ropts.timestamp = &ts;
  3711. CompactRangeOptions cro;
  3712. cro.full_history_ts_low = nullptr;
  3713. std::string value, key_ts;
  3714. Status s;
  3715. auto verify = [&] {
  3716. s = db_->Get(ropts, "k1", &value);
  3717. ASSERT_TRUE(s.IsNotFound());
  3718. s = db_->Get(ropts, "k2", &value, &key_ts);
  3719. ASSERT_TRUE(s.IsNotFound());
  3720. ASSERT_EQ(key_ts, Timestamp(2, 0));
  3721. ASSERT_OK(db_->Get(ropts, "k3", &value, &key_ts));
  3722. ASSERT_EQ(value, "v3");
  3723. ASSERT_EQ(Timestamp(1, 0), key_ts);
  3724. size_t batch_size = 3;
  3725. std::vector<std::string> key_strs = {"k1", "k2", "k3"};
  3726. std::vector<Slice> keys{key_strs.begin(), key_strs.end()};
  3727. std::vector<PinnableSlice> values(batch_size);
  3728. std::vector<Status> statuses(batch_size);
  3729. db_->MultiGet(ropts, db_->DefaultColumnFamily(), batch_size, keys.data(),
  3730. values.data(), statuses.data(), true /* sorted_input */);
  3731. ASSERT_TRUE(statuses[0].IsNotFound());
  3732. ASSERT_TRUE(statuses[1].IsNotFound());
  3733. ASSERT_OK(statuses[2]);
  3734. ;
  3735. ASSERT_EQ(values[2], "v3");
  3736. };
  3737. verify();
  3738. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  3739. verify();
  3740. std::string lb = Timestamp(0, 0);
  3741. Slice lb_slice = lb;
  3742. cro.full_history_ts_low = &lb_slice;
  3743. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  3744. verify();
  3745. Close();
  3746. }
  3747. TEST_F(DBBasicTestWithTimestamp,
  3748. GCRangeTombstonesAndCoveredKeysRespectingTslow) {
  3749. Options options = CurrentOptions();
  3750. options.env = env_;
  3751. options.create_if_missing = true;
  3752. BlockBasedTableOptions bbto;
  3753. bbto.filter_policy.reset(NewBloomFilterPolicy(10, false));
  3754. bbto.cache_index_and_filter_blocks = true;
  3755. bbto.whole_key_filtering = true;
  3756. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  3757. const size_t kTimestampSize = Timestamp(0, 0).size();
  3758. TestComparator test_cmp(kTimestampSize);
  3759. options.comparator = &test_cmp;
  3760. options.num_levels = 2;
  3761. DestroyAndReopen(options);
  3762. WriteOptions wopts;
  3763. ASSERT_OK(db_->Put(wopts, "k1", Timestamp(1, 0), "v1"));
  3764. ASSERT_OK(db_->Delete(wopts, "k2", Timestamp(2, 0)));
  3765. ASSERT_OK(db_->DeleteRange(wopts, db_->DefaultColumnFamily(), "k1", "k3",
  3766. Timestamp(3, 0)));
  3767. ASSERT_OK(db_->Put(wopts, "k3", Timestamp(4, 0), "v3"));
  3768. ReadOptions ropts;
  3769. std::string read_ts = Timestamp(5, 0);
  3770. Slice read_ts_slice = read_ts;
  3771. ropts.timestamp = &read_ts_slice;
  3772. size_t batch_size = 3;
  3773. std::vector<std::string> key_strs = {"k1", "k2", "k3"};
  3774. std::vector<Slice> keys = {key_strs.begin(), key_strs.end()};
  3775. std::vector<PinnableSlice> values(batch_size);
  3776. std::vector<Status> statuses(batch_size);
  3777. std::vector<std::string> timestamps(batch_size);
  3778. db_->MultiGet(ropts, db_->DefaultColumnFamily(), batch_size, keys.data(),
  3779. values.data(), timestamps.data(), statuses.data(),
  3780. true /* sorted_input */);
  3781. ASSERT_TRUE(statuses[0].IsNotFound());
  3782. ASSERT_EQ(timestamps[0], Timestamp(3, 0));
  3783. ASSERT_TRUE(statuses[1].IsNotFound());
  3784. // DeleteRange has a higher timestamp than Delete for "k2"
  3785. ASSERT_EQ(timestamps[1], Timestamp(3, 0));
  3786. ASSERT_OK(statuses[2]);
  3787. ASSERT_EQ(values[2], "v3");
  3788. ASSERT_EQ(timestamps[2], Timestamp(4, 0));
  3789. CompactRangeOptions cro;
  3790. // Range tombstone has timestamp >= full_history_ts_low, covered keys
  3791. // are not dropped.
  3792. std::string compaction_ts_str = Timestamp(2, 0);
  3793. Slice compaction_ts = compaction_ts_str;
  3794. cro.full_history_ts_low = &compaction_ts;
  3795. cro.bottommost_level_compaction = BottommostLevelCompaction::kForce;
  3796. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  3797. ropts.timestamp = &compaction_ts;
  3798. std::string value, ts;
  3799. ASSERT_OK(db_->Get(ropts, "k1", &value, &ts));
  3800. ASSERT_EQ(value, "v1");
  3801. // timestamp is below full_history_ts_low, zeroed out as the key goes into
  3802. // bottommost level
  3803. ASSERT_EQ(ts, Timestamp(0, 0));
  3804. ASSERT_TRUE(db_->Get(ropts, "k2", &value, &ts).IsNotFound());
  3805. ASSERT_EQ(ts, Timestamp(2, 0));
  3806. compaction_ts_str = Timestamp(4, 0);
  3807. compaction_ts = compaction_ts_str;
  3808. cro.full_history_ts_low = &compaction_ts;
  3809. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  3810. ropts.timestamp = &read_ts_slice;
  3811. // k1, k2 and the range tombstone should be dropped
  3812. // k3 should still exist
  3813. db_->MultiGet(ropts, db_->DefaultColumnFamily(), batch_size, keys.data(),
  3814. values.data(), timestamps.data(), statuses.data(),
  3815. true /* sorted_input */);
  3816. ASSERT_TRUE(statuses[0].IsNotFound());
  3817. ASSERT_TRUE(timestamps[0].empty());
  3818. ASSERT_TRUE(statuses[1].IsNotFound());
  3819. ASSERT_TRUE(timestamps[1].empty());
  3820. ASSERT_OK(statuses[2]);
  3821. ASSERT_EQ(values[2], "v3");
  3822. ASSERT_EQ(timestamps[2], Timestamp(4, 0));
  3823. Close();
  3824. }
  3825. class DeleteRangeWithTimestampTableOptions
  3826. : public DBBasicTestWithTimestampBase,
  3827. public testing::WithParamInterface<
  3828. std::tuple<BlockBasedTableOptions::IndexType,
  3829. test::UserDefinedTimestampTestMode>> {
  3830. public:
  3831. explicit DeleteRangeWithTimestampTableOptions()
  3832. : DBBasicTestWithTimestampBase(
  3833. "delete_range_with_timestamp_table_options") {}
  3834. };
  3835. INSTANTIATE_TEST_CASE_P(
  3836. Timestamp, DeleteRangeWithTimestampTableOptions,
  3837. testing::Combine(
  3838. testing::Values(
  3839. BlockBasedTableOptions::IndexType::kBinarySearch,
  3840. BlockBasedTableOptions::IndexType::kHashSearch,
  3841. BlockBasedTableOptions::IndexType::kTwoLevelIndexSearch,
  3842. BlockBasedTableOptions::IndexType::kBinarySearchWithFirstKey),
  3843. testing::Values(
  3844. test::UserDefinedTimestampTestMode::kNormal,
  3845. test::UserDefinedTimestampTestMode::kStripUserDefinedTimestamp)));
  3846. TEST_P(DeleteRangeWithTimestampTableOptions, BasicReadAndIterate) {
  3847. const int kNum = 200, kRangeBegin = 50, kRangeEnd = 150, kNumPerFile = 25;
  3848. Options options = CurrentOptions();
  3849. options.disable_auto_compactions = true;
  3850. options.prefix_extractor.reset(NewFixedPrefixTransform(3));
  3851. options.compression = kNoCompression;
  3852. BlockBasedTableOptions bbto;
  3853. bbto.index_type = std::get<0>(GetParam());
  3854. bbto.block_size = 100;
  3855. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  3856. options.env = env_;
  3857. options.create_if_missing = true;
  3858. bool persist_udt = test::ShouldPersistUDT(std::get<1>(GetParam()));
  3859. options.comparator = test::BytewiseComparatorWithU64TsWrapper();
  3860. options.persist_user_defined_timestamps = persist_udt;
  3861. // UDT in memtables only not compatible with concurrent memtable writes.
  3862. options.allow_concurrent_memtable_write = persist_udt;
  3863. options.memtable_factory.reset(test::NewSpecialSkipListFactory(kNumPerFile));
  3864. DestroyAndReopen(options);
  3865. // Write half of the keys before the tombstone and half after the tombstone.
  3866. // Only covered keys (i.e., within the range and older than the tombstone)
  3867. // should be deleted.
  3868. std::string full_history_ts_low;
  3869. int cutoff_ts = 0;
  3870. for (int i = 0; i < kNum; ++i) {
  3871. std::string write_ts;
  3872. PutFixed64(&write_ts, i);
  3873. if (i == kNum / 2) {
  3874. ASSERT_OK(db_->DeleteRange(WriteOptions(), db_->DefaultColumnFamily(),
  3875. Key1(kRangeBegin), Key1(kRangeEnd), write_ts));
  3876. }
  3877. ASSERT_OK(
  3878. db_->Put(WriteOptions(), Key1(i), write_ts, "val" + std::to_string(i)));
  3879. if (i == kNum - kNumPerFile) {
  3880. if (!persist_udt) {
  3881. // When UDTs are not persisted, mark the timestamps in the Memtables as
  3882. // all expired so the followed flush can go through.
  3883. cutoff_ts = i + 1;
  3884. PutFixed64(&full_history_ts_low, cutoff_ts);
  3885. ASSERT_OK(db_->IncreaseFullHistoryTsLow(db_->DefaultColumnFamily(),
  3886. full_history_ts_low));
  3887. }
  3888. ASSERT_OK(Flush());
  3889. }
  3890. }
  3891. ReadOptions read_opts;
  3892. read_opts.total_order_seek = true;
  3893. std::string read_ts;
  3894. PutFixed64(&read_ts, kNum);
  3895. Slice read_ts_slice = read_ts;
  3896. read_opts.timestamp = &read_ts_slice;
  3897. {
  3898. std::unique_ptr<Iterator> iter(db_->NewIterator(read_opts));
  3899. ASSERT_OK(iter->status());
  3900. int expected = 0;
  3901. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  3902. ASSERT_EQ(Key1(expected), iter->key());
  3903. if (expected == kRangeBegin - 1) {
  3904. expected = kNum / 2;
  3905. } else {
  3906. ++expected;
  3907. }
  3908. }
  3909. ASSERT_OK(iter->status());
  3910. ASSERT_EQ(kNum, expected);
  3911. expected = kNum / 2;
  3912. for (iter->Seek(Key1(kNum / 2)); iter->Valid(); iter->Next()) {
  3913. ASSERT_EQ(Key1(expected), iter->key());
  3914. ++expected;
  3915. }
  3916. ASSERT_OK(iter->status());
  3917. ASSERT_EQ(kNum, expected);
  3918. expected = kRangeBegin - 1;
  3919. for (iter->SeekForPrev(Key1(kNum / 2 - 1)); iter->Valid(); iter->Prev()) {
  3920. ASSERT_EQ(Key1(expected), iter->key());
  3921. --expected;
  3922. }
  3923. ASSERT_OK(iter->status());
  3924. ASSERT_EQ(-1, expected);
  3925. // Cannot read below the cutoff timestamp when timestamps are not persisted.
  3926. if (persist_udt) {
  3927. read_ts.clear();
  3928. PutFixed64(&read_ts, 0);
  3929. read_ts_slice = read_ts;
  3930. read_opts.timestamp = &read_ts_slice;
  3931. iter.reset(db_->NewIterator(read_opts));
  3932. iter->SeekToFirst();
  3933. ASSERT_TRUE(iter->Valid());
  3934. ASSERT_EQ(iter->key(), Key1(0));
  3935. iter->Next();
  3936. ASSERT_FALSE(iter->Valid());
  3937. ASSERT_OK(iter->status());
  3938. }
  3939. }
  3940. read_ts.clear();
  3941. PutFixed64(&read_ts, kNum);
  3942. read_ts_slice = read_ts;
  3943. read_opts.timestamp = &read_ts_slice;
  3944. std::string value, timestamp;
  3945. Status s;
  3946. std::string expected_ts;
  3947. int int_expected_ts;
  3948. for (int i = 0; i < kNum; ++i) {
  3949. s = db_->Get(read_opts, Key1(i), &value, &timestamp);
  3950. if (i >= kRangeBegin && i < kNum / 2) {
  3951. ASSERT_TRUE(s.IsNotFound());
  3952. int_expected_ts = (persist_udt || kNum / 2 >= cutoff_ts) ? kNum / 2 : 0;
  3953. } else {
  3954. ASSERT_OK(s);
  3955. ASSERT_EQ(value, "val" + std::to_string(i));
  3956. int_expected_ts = (persist_udt || i >= cutoff_ts) ? i : 0;
  3957. }
  3958. expected_ts.clear();
  3959. PutFixed64(&expected_ts, int_expected_ts);
  3960. ASSERT_EQ(timestamp, expected_ts);
  3961. }
  3962. size_t batch_size = kNum;
  3963. std::vector<std::string> key_strs(batch_size);
  3964. std::vector<Slice> keys(batch_size);
  3965. std::vector<PinnableSlice> values(batch_size);
  3966. std::vector<Status> statuses(batch_size);
  3967. std::vector<std::string> timestamps(batch_size);
  3968. for (int i = 0; i < kNum; ++i) {
  3969. key_strs[i] = Key1(i);
  3970. keys[i] = key_strs[i];
  3971. }
  3972. db_->MultiGet(read_opts, db_->DefaultColumnFamily(), batch_size, keys.data(),
  3973. values.data(), timestamps.data(), statuses.data(),
  3974. true /* sorted_input */);
  3975. for (int i = 0; i < kNum; ++i) {
  3976. if (i >= kRangeBegin && i < kNum / 2) {
  3977. ASSERT_TRUE(statuses[i].IsNotFound());
  3978. int_expected_ts = (persist_udt || kNum / 2 >= cutoff_ts) ? kNum / 2 : 0;
  3979. } else {
  3980. ASSERT_OK(statuses[i]);
  3981. ASSERT_EQ(values[i], "val" + std::to_string(i));
  3982. int_expected_ts = (persist_udt || i >= cutoff_ts) ? i : 0;
  3983. }
  3984. expected_ts.clear();
  3985. PutFixed64(&expected_ts, int_expected_ts);
  3986. ASSERT_EQ(timestamps[i], expected_ts);
  3987. }
  3988. CompactRangeOptions cro;
  3989. cro.bottommost_level_compaction = BottommostLevelCompaction::kForce;
  3990. if (!persist_udt) {
  3991. // Mark everything expired so manual compaction can go through
  3992. full_history_ts_low.clear();
  3993. PutFixed64(&full_history_ts_low, kNum);
  3994. ASSERT_OK(db_->IncreaseFullHistoryTsLow(db_->DefaultColumnFamily(),
  3995. full_history_ts_low));
  3996. }
  3997. Slice compaction_ts = full_history_ts_low;
  3998. cro.full_history_ts_low = &compaction_ts;
  3999. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  4000. for (int i = kRangeBegin; i < kNum / 2; ++i) {
  4001. s = db_->Get(read_opts, Key1(i), &value, &timestamp);
  4002. ASSERT_TRUE(s.IsNotFound());
  4003. if (persist_udt) {
  4004. expected_ts.clear();
  4005. PutFixed64(&expected_ts, kNum / 2);
  4006. ASSERT_EQ(timestamp, expected_ts);
  4007. } else {
  4008. // When timestamps are not persisted, data in SST files all logically have
  4009. // min timestamp. A compaction to the last level will drop the range
  4010. // tombstone.
  4011. ASSERT_TRUE(timestamp.empty());
  4012. }
  4013. }
  4014. Close();
  4015. }
  4016. TEST_F(DBBasicTestWithTimestamp, DeleteRangeGetIteratorWithSnapshot) {
  4017. // 4 keys 0, 1, 2, 3 at timestamps 0, 1, 2, 3 respectively.
  4018. // A range tombstone [1, 3) at timestamp 1 and has a sequence number between
  4019. // key 1 and 2.
  4020. Options options = CurrentOptions();
  4021. const size_t kTimestampSize = Timestamp(0, 0).size();
  4022. TestComparator test_cmp(kTimestampSize);
  4023. options.comparator = &test_cmp;
  4024. DestroyAndReopen(options);
  4025. WriteOptions write_opts;
  4026. std::string put_ts = Timestamp(0, 0);
  4027. const int kNum = 4, kNumPerFile = 1, kRangeBegin = 1, kRangeEnd = 3;
  4028. options.memtable_factory.reset(test::NewSpecialSkipListFactory(kNumPerFile));
  4029. const Snapshot* before_tombstone = nullptr;
  4030. const Snapshot* after_tombstone = nullptr;
  4031. for (int i = 0; i < kNum; ++i) {
  4032. ASSERT_OK(db_->Put(WriteOptions(), Key1(i), Timestamp(i, 0),
  4033. "val" + std::to_string(i)));
  4034. if (i == kRangeBegin) {
  4035. before_tombstone = db_->GetSnapshot();
  4036. ASSERT_OK(db_->DeleteRange(WriteOptions(), db_->DefaultColumnFamily(),
  4037. Key1(kRangeBegin), Key1(kRangeEnd),
  4038. Timestamp(kRangeBegin, 0)));
  4039. }
  4040. if (i == kNum / 2) {
  4041. ASSERT_OK(Flush());
  4042. }
  4043. }
  4044. assert(before_tombstone);
  4045. after_tombstone = db_->GetSnapshot();
  4046. // snapshot and ts before tombstone
  4047. std::string read_ts_str = Timestamp(kRangeBegin - 1, 0); // (0, 0)
  4048. Slice read_ts = read_ts_str;
  4049. ReadOptions read_opts;
  4050. read_opts.timestamp = &read_ts;
  4051. read_opts.snapshot = before_tombstone;
  4052. std::vector<Status> expected_status = {
  4053. Status::OK(), Status::NotFound(), Status::NotFound(), Status::NotFound()};
  4054. std::vector<std::string> expected_values(kNum);
  4055. expected_values[0] = "val" + std::to_string(0);
  4056. std::vector<std::string> expected_timestamps(kNum);
  4057. expected_timestamps[0] = Timestamp(0, 0);
  4058. size_t batch_size = kNum;
  4059. std::vector<std::string> key_strs(batch_size);
  4060. std::vector<Slice> keys(batch_size);
  4061. std::vector<PinnableSlice> values(batch_size);
  4062. std::vector<Status> statuses(batch_size);
  4063. std::vector<std::string> timestamps(batch_size);
  4064. for (int i = 0; i < kNum; ++i) {
  4065. key_strs[i] = Key1(i);
  4066. keys[i] = key_strs[i];
  4067. }
  4068. auto verify = [&] {
  4069. db_->MultiGet(read_opts, db_->DefaultColumnFamily(), batch_size,
  4070. keys.data(), values.data(), timestamps.data(),
  4071. statuses.data(), true /* sorted_input */);
  4072. std::string value, timestamp;
  4073. Status s;
  4074. for (int i = 0; i < kNum; ++i) {
  4075. s = db_->Get(read_opts, Key1(i), &value, &timestamp);
  4076. ASSERT_EQ(s, expected_status[i]);
  4077. ASSERT_EQ(statuses[i], expected_status[i]);
  4078. if (s.ok()) {
  4079. ASSERT_EQ(value, expected_values[i]);
  4080. ASSERT_EQ(values[i], expected_values[i]);
  4081. }
  4082. if (!timestamp.empty()) {
  4083. ASSERT_EQ(timestamp, expected_timestamps[i]);
  4084. ASSERT_EQ(timestamps[i], expected_timestamps[i]);
  4085. } else {
  4086. ASSERT_TRUE(timestamps[i].empty());
  4087. }
  4088. }
  4089. std::unique_ptr<Iterator> iter(db_->NewIterator(read_opts));
  4090. std::unique_ptr<Iterator> iter_for_seek(db_->NewIterator(read_opts));
  4091. iter->SeekToFirst();
  4092. for (int i = 0; i < kNum; ++i) {
  4093. if (expected_status[i].ok()) {
  4094. auto verify_iter = [&](Iterator* iter_ptr) {
  4095. ASSERT_TRUE(iter_ptr->Valid());
  4096. ASSERT_EQ(iter_ptr->key(), keys[i]);
  4097. ASSERT_EQ(iter_ptr->value(), expected_values[i]);
  4098. ASSERT_EQ(iter_ptr->timestamp(), expected_timestamps[i]);
  4099. };
  4100. verify_iter(iter.get());
  4101. iter->Next();
  4102. iter_for_seek->Seek(keys[i]);
  4103. verify_iter(iter_for_seek.get());
  4104. iter_for_seek->SeekForPrev(keys[i]);
  4105. verify_iter(iter_for_seek.get());
  4106. }
  4107. }
  4108. ASSERT_FALSE(iter->Valid());
  4109. ASSERT_OK(iter->status());
  4110. };
  4111. verify();
  4112. // snapshot before tombstone and ts after tombstone
  4113. read_ts_str = Timestamp(kNum, 0); // (4, 0)
  4114. read_ts = read_ts_str;
  4115. read_opts.timestamp = &read_ts;
  4116. read_opts.snapshot = before_tombstone;
  4117. expected_status[1] = Status::OK();
  4118. expected_timestamps[1] = Timestamp(1, 0);
  4119. expected_values[1] = "val" + std::to_string(1);
  4120. verify();
  4121. // snapshot after tombstone and ts before tombstone
  4122. read_ts_str = Timestamp(kRangeBegin - 1, 0); // (0, 0)
  4123. read_ts = read_ts_str;
  4124. read_opts.timestamp = &read_ts;
  4125. read_opts.snapshot = after_tombstone;
  4126. expected_status[1] = Status::NotFound();
  4127. expected_timestamps[1].clear();
  4128. expected_values[1].clear();
  4129. verify();
  4130. // snapshot and ts after tombstone
  4131. read_ts_str = Timestamp(kNum, 0); // (4, 0)
  4132. read_ts = read_ts_str;
  4133. read_opts.timestamp = &read_ts;
  4134. read_opts.snapshot = after_tombstone;
  4135. for (int i = 0; i < kNum; ++i) {
  4136. if (i == kRangeBegin) {
  4137. expected_status[i] = Status::NotFound();
  4138. expected_values[i].clear();
  4139. } else {
  4140. expected_status[i] = Status::OK();
  4141. expected_values[i] = "val" + std::to_string(i);
  4142. }
  4143. expected_timestamps[i] = Timestamp(i, 0);
  4144. }
  4145. verify();
  4146. db_->ReleaseSnapshot(before_tombstone);
  4147. db_->ReleaseSnapshot(after_tombstone);
  4148. Close();
  4149. }
  4150. TEST_F(DBBasicTestWithTimestamp, MergeBasic) {
  4151. Options options = GetDefaultOptions();
  4152. options.create_if_missing = true;
  4153. const size_t kTimestampSize = Timestamp(0, 0).size();
  4154. TestComparator test_cmp(kTimestampSize);
  4155. options.comparator = &test_cmp;
  4156. options.merge_operator = std::make_shared<StringAppendTESTOperator>('.');
  4157. DestroyAndReopen(options);
  4158. const std::array<std::string, 3> write_ts_strs = {
  4159. Timestamp(100, 0), Timestamp(200, 0), Timestamp(300, 0)};
  4160. constexpr size_t kNumOfUniqKeys = 100;
  4161. ColumnFamilyHandle* default_cf = db_->DefaultColumnFamily();
  4162. for (size_t i = 0; i < write_ts_strs.size(); ++i) {
  4163. for (size_t j = 0; j < kNumOfUniqKeys; ++j) {
  4164. Status s;
  4165. if (i == 0) {
  4166. const std::string val = "v" + std::to_string(j) + "_0";
  4167. s = db_->Put(WriteOptions(), Key1(j), write_ts_strs[i], val);
  4168. } else {
  4169. const std::string merge_op = std::to_string(i);
  4170. s = db_->Merge(WriteOptions(), default_cf, Key1(j), write_ts_strs[i],
  4171. merge_op);
  4172. }
  4173. ASSERT_OK(s);
  4174. }
  4175. }
  4176. std::array<std::string, 3> read_ts_strs = {
  4177. Timestamp(150, 0), Timestamp(250, 0), Timestamp(350, 0)};
  4178. const auto verify_db_with_get = [&]() {
  4179. for (size_t i = 0; i < kNumOfUniqKeys; ++i) {
  4180. const std::string base_val = "v" + std::to_string(i) + "_0";
  4181. const std::array<std::string, 3> expected_values = {
  4182. base_val, base_val + ".1", base_val + ".1.2"};
  4183. const std::array<std::string, 3>& expected_ts = write_ts_strs;
  4184. ReadOptions read_opts;
  4185. for (size_t j = 0; j < read_ts_strs.size(); ++j) {
  4186. Slice read_ts = read_ts_strs[j];
  4187. read_opts.timestamp = &read_ts;
  4188. std::string value;
  4189. std::string ts;
  4190. const Status s = db_->Get(read_opts, Key1(i), &value, &ts);
  4191. ASSERT_OK(s);
  4192. ASSERT_EQ(expected_values[j], value);
  4193. ASSERT_EQ(expected_ts[j], ts);
  4194. // Do Seek/SeekForPrev
  4195. std::unique_ptr<Iterator> it(db_->NewIterator(read_opts));
  4196. it->Seek(Key1(i));
  4197. ASSERT_TRUE(it->Valid());
  4198. ASSERT_EQ(expected_values[j], it->value());
  4199. ASSERT_EQ(expected_ts[j], it->timestamp());
  4200. it->SeekForPrev(Key1(i));
  4201. ASSERT_TRUE(it->Valid());
  4202. ASSERT_EQ(expected_values[j], it->value());
  4203. ASSERT_EQ(expected_ts[j], it->timestamp());
  4204. }
  4205. }
  4206. };
  4207. const auto verify_db_with_iterator = [&]() {
  4208. std::string value_suffix;
  4209. for (size_t i = 0; i < read_ts_strs.size(); ++i) {
  4210. ReadOptions read_opts;
  4211. Slice read_ts = read_ts_strs[i];
  4212. read_opts.timestamp = &read_ts;
  4213. std::unique_ptr<Iterator> it(db_->NewIterator(read_opts));
  4214. size_t key_int_val = 0;
  4215. for (it->SeekToFirst(); it->Valid(); it->Next(), ++key_int_val) {
  4216. const std::string key = Key1(key_int_val);
  4217. const std::string value =
  4218. "v" + std::to_string(key_int_val) + "_0" + value_suffix;
  4219. ASSERT_EQ(key, it->key());
  4220. ASSERT_EQ(value, it->value());
  4221. ASSERT_EQ(write_ts_strs[i], it->timestamp());
  4222. }
  4223. EXPECT_OK(it->status());
  4224. ASSERT_EQ(kNumOfUniqKeys, key_int_val);
  4225. key_int_val = kNumOfUniqKeys - 1;
  4226. for (it->SeekToLast(); it->Valid(); it->Prev(), --key_int_val) {
  4227. const std::string key = Key1(key_int_val);
  4228. const std::string value =
  4229. "v" + std::to_string(key_int_val) + "_0" + value_suffix;
  4230. ASSERT_EQ(key, it->key());
  4231. ASSERT_EQ(value, it->value());
  4232. ASSERT_EQ(write_ts_strs[i], it->timestamp());
  4233. }
  4234. ASSERT_OK(it->status());
  4235. ASSERT_EQ(std::numeric_limits<size_t>::max(), key_int_val);
  4236. value_suffix = value_suffix + "." + std::to_string(i + 1);
  4237. }
  4238. };
  4239. verify_db_with_get();
  4240. verify_db_with_iterator();
  4241. ASSERT_OK(db_->Flush(FlushOptions()));
  4242. verify_db_with_get();
  4243. verify_db_with_iterator();
  4244. Close();
  4245. }
  4246. TEST_F(DBBasicTestWithTimestamp, MergeAfterDeletion) {
  4247. Options options = GetDefaultOptions();
  4248. options.create_if_missing = true;
  4249. const size_t kTimestampSize = Timestamp(0, 0).size();
  4250. TestComparator test_cmp(kTimestampSize);
  4251. options.comparator = &test_cmp;
  4252. options.merge_operator = std::make_shared<StringAppendTESTOperator>('.');
  4253. DestroyAndReopen(options);
  4254. ColumnFamilyHandle* const column_family = db_->DefaultColumnFamily();
  4255. const size_t num_keys_per_file = 10;
  4256. const size_t num_merges_per_key = 2;
  4257. for (size_t i = 0; i < num_keys_per_file; ++i) {
  4258. std::string ts = Timestamp(i + 10000, 0);
  4259. Status s = db_->Delete(WriteOptions(), Key1(i), ts);
  4260. ASSERT_OK(s);
  4261. for (size_t j = 1; j <= num_merges_per_key; ++j) {
  4262. ts = Timestamp(i + 10000 + j, 0);
  4263. s = db_->Merge(WriteOptions(), column_family, Key1(i), ts,
  4264. std::to_string(j));
  4265. ASSERT_OK(s);
  4266. }
  4267. }
  4268. const auto verify_db = [&]() {
  4269. ReadOptions read_opts;
  4270. std::string read_ts_str = Timestamp(20000, 0);
  4271. Slice ts = read_ts_str;
  4272. read_opts.timestamp = &ts;
  4273. std::unique_ptr<Iterator> it(db_->NewIterator(read_opts));
  4274. size_t count = 0;
  4275. for (it->SeekToFirst(); it->Valid(); it->Next(), ++count) {
  4276. std::string key = Key1(count);
  4277. ASSERT_EQ(key, it->key());
  4278. std::string value;
  4279. for (size_t j = 1; j <= num_merges_per_key; ++j) {
  4280. value.append(std::to_string(j));
  4281. if (j < num_merges_per_key) {
  4282. value.push_back('.');
  4283. }
  4284. }
  4285. ASSERT_EQ(value, it->value());
  4286. std::string ts1 = Timestamp(count + 10000 + num_merges_per_key, 0);
  4287. ASSERT_EQ(ts1, it->timestamp());
  4288. }
  4289. ASSERT_OK(it->status());
  4290. ASSERT_EQ(num_keys_per_file, count);
  4291. for (it->SeekToLast(); it->Valid(); it->Prev(), --count) {
  4292. std::string key = Key1(count - 1);
  4293. ASSERT_EQ(key, it->key());
  4294. std::string value;
  4295. for (size_t j = 1; j <= num_merges_per_key; ++j) {
  4296. value.append(std::to_string(j));
  4297. if (j < num_merges_per_key) {
  4298. value.push_back('.');
  4299. }
  4300. }
  4301. ASSERT_EQ(value, it->value());
  4302. std::string ts1 = Timestamp(count - 1 + 10000 + num_merges_per_key, 0);
  4303. ASSERT_EQ(ts1, it->timestamp());
  4304. }
  4305. ASSERT_OK(it->status());
  4306. ASSERT_EQ(0, count);
  4307. };
  4308. verify_db();
  4309. Close();
  4310. }
  4311. TEST_F(DBBasicTestWithTimestamp, RangeTombstoneApproximateSize) {
  4312. // Test code path for calculating range tombstone compensated size
  4313. // during flush and compaction.
  4314. Options options = CurrentOptions();
  4315. const size_t kTimestampSize = Timestamp(0, 0).size();
  4316. TestComparator test_cmp(kTimestampSize);
  4317. options.comparator = &test_cmp;
  4318. DestroyAndReopen(options);
  4319. // So that the compaction below is non-bottommost and will calcualte
  4320. // compensated range tombstone size.
  4321. ASSERT_OK(db_->Put(WriteOptions(), Key(1), Timestamp(1, 0), "val"));
  4322. ASSERT_OK(Flush());
  4323. MoveFilesToLevel(5);
  4324. ASSERT_OK(db_->DeleteRange(WriteOptions(), db_->DefaultColumnFamily(), Key(0),
  4325. Key(1), Timestamp(1, 0)));
  4326. ASSERT_OK(db_->DeleteRange(WriteOptions(), db_->DefaultColumnFamily(), Key(1),
  4327. Key(2), Timestamp(2, 0)));
  4328. ASSERT_OK(Flush());
  4329. ASSERT_OK(dbfull()->RunManualCompaction(
  4330. static_cast_with_check<ColumnFamilyHandleImpl>(db_->DefaultColumnFamily())
  4331. ->cfd(),
  4332. 0 /* input_level */, 1 /* output_level */, CompactRangeOptions(),
  4333. nullptr /* begin */, nullptr /* end */, true /* exclusive */,
  4334. true /* disallow_trivial_move */,
  4335. std::numeric_limits<uint64_t>::max() /* max_file_num_to_ignore */,
  4336. "" /*trim_ts*/));
  4337. }
  4338. TEST_F(DBBasicTestWithTimestamp, IterSeekToLastWithIterateUpperbound) {
  4339. // Test for a bug fix where DBIter::SeekToLast() could fail when
  4340. // iterate_upper_bound and iter_start_ts are both set.
  4341. Options options = CurrentOptions();
  4342. const size_t kTimestampSize = Timestamp(0, 0).size();
  4343. TestComparator test_cmp(kTimestampSize);
  4344. options.comparator = &test_cmp;
  4345. DestroyAndReopen(options);
  4346. ASSERT_OK(db_->Put(WriteOptions(), Key(1), Timestamp(2, 0), "val"));
  4347. ReadOptions ro;
  4348. std::string k = Key(1);
  4349. Slice k_slice = k;
  4350. ro.iterate_upper_bound = &k_slice;
  4351. std::string ts = Timestamp(3, 0);
  4352. Slice read_ts = ts;
  4353. ro.timestamp = &read_ts;
  4354. std::string start_ts = Timestamp(0, 0);
  4355. Slice start_ts_slice = start_ts;
  4356. ro.iter_start_ts = &start_ts_slice;
  4357. std::unique_ptr<Iterator> iter{db_->NewIterator(ro)};
  4358. iter->SeekToLast();
  4359. ASSERT_FALSE(iter->Valid());
  4360. ASSERT_OK(iter->status());
  4361. }
  4362. TEST_F(DBBasicTestWithTimestamp, TimestampFilterTableReadOnGet) {
  4363. Options options = CurrentOptions();
  4364. options.env = env_;
  4365. options.create_if_missing = true;
  4366. options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
  4367. const size_t kTimestampSize = Timestamp(0, 0).size();
  4368. TestComparator test_cmp(kTimestampSize);
  4369. options.comparator = &test_cmp;
  4370. BlockBasedTableOptions bbto;
  4371. bbto.block_size = 100;
  4372. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  4373. DestroyAndReopen(options);
  4374. // Put
  4375. // Create two SST files
  4376. // file1: key => [1, 3], timestamp => [10, 20]
  4377. // file2, key => [2, 4], timestamp => [30, 40]
  4378. {
  4379. WriteOptions write_opts;
  4380. std::string write_ts = Timestamp(10, 0);
  4381. ASSERT_OK(db_->Put(write_opts, Key1(1), write_ts, "value1"));
  4382. write_ts = Timestamp(20, 0);
  4383. ASSERT_OK(db_->Put(write_opts, Key1(3), write_ts, "value3"));
  4384. ASSERT_OK(Flush());
  4385. write_ts = Timestamp(30, 0);
  4386. ASSERT_OK(db_->Put(write_opts, Key1(2), write_ts, "value2"));
  4387. write_ts = Timestamp(40, 0);
  4388. ASSERT_OK(db_->Put(write_opts, Key1(4), write_ts, "value4"));
  4389. ASSERT_OK(Flush());
  4390. }
  4391. // Get with timestamp
  4392. {
  4393. auto prev_checked_events = options.statistics->getTickerCount(
  4394. Tickers::TIMESTAMP_FILTER_TABLE_CHECKED);
  4395. auto prev_filtered_events = options.statistics->getTickerCount(
  4396. Tickers::TIMESTAMP_FILTER_TABLE_FILTERED);
  4397. // key=3 (ts=20) does not exist at timestamp=1
  4398. std::string read_ts_str = Timestamp(1, 0);
  4399. Slice read_ts_slice = Slice(read_ts_str);
  4400. ReadOptions read_opts;
  4401. read_opts.timestamp = &read_ts_slice;
  4402. std::string value_from_get;
  4403. std::string timestamp_from_get;
  4404. auto status =
  4405. db_->Get(read_opts, Key1(3), &value_from_get, &timestamp_from_get);
  4406. ASSERT_TRUE(status.IsNotFound());
  4407. ASSERT_EQ(value_from_get, std::string(""));
  4408. ASSERT_EQ(timestamp_from_get, std::string(""));
  4409. // key=3 is in the key ranges for both files, so both files will be queried.
  4410. // The table read was skipped because the timestamp is out of the table
  4411. // range, i.e.., 1 < [10,20], [30,40].
  4412. // The tickers increase by 2 due to 2 files.
  4413. ASSERT_EQ(prev_checked_events + 2,
  4414. options.statistics->getTickerCount(
  4415. Tickers::TIMESTAMP_FILTER_TABLE_CHECKED));
  4416. ASSERT_EQ(prev_filtered_events + 2,
  4417. options.statistics->getTickerCount(
  4418. Tickers::TIMESTAMP_FILTER_TABLE_FILTERED));
  4419. // key=3 (ts=20) exists at timestamp = 25
  4420. read_ts_str = Timestamp(25, 0);
  4421. read_ts_slice = Slice(read_ts_str);
  4422. read_opts.timestamp = &read_ts_slice;
  4423. ASSERT_OK(
  4424. db_->Get(read_opts, Key1(3), &value_from_get, &timestamp_from_get));
  4425. ASSERT_EQ("value3", value_from_get);
  4426. ASSERT_EQ(Timestamp(20, 0), timestamp_from_get);
  4427. // file1 was not skipped, because the timestamp is in range, [10,20] < 25.
  4428. // file2 was skipped, because the timestamp is not in range, 25 < [30,40].
  4429. // So the checked ticker increase by 2 due to 2 files;
  4430. // filtered ticker increase by 1 because file2 was skipped
  4431. ASSERT_EQ(prev_checked_events + 4,
  4432. options.statistics->getTickerCount(
  4433. Tickers::TIMESTAMP_FILTER_TABLE_CHECKED));
  4434. ASSERT_EQ(prev_filtered_events + 3,
  4435. options.statistics->getTickerCount(
  4436. Tickers::TIMESTAMP_FILTER_TABLE_FILTERED));
  4437. }
  4438. Close();
  4439. }
  4440. class GetNewestUserDefinedTimestampTest : public DBBasicTestWithTimestampBase {
  4441. public:
  4442. explicit GetNewestUserDefinedTimestampTest()
  4443. : DBBasicTestWithTimestampBase("get_newest_udt_test") {}
  4444. };
  4445. TEST_F(GetNewestUserDefinedTimestampTest, Basic) {
  4446. std::string newest_timestamp;
  4447. // UDT disabled, get InvalidArgument.
  4448. ASSERT_TRUE(db_->GetNewestUserDefinedTimestamp(nullptr, &newest_timestamp)
  4449. .IsInvalidArgument());
  4450. Options options = CurrentOptions();
  4451. options.env = env_;
  4452. options.create_if_missing = true;
  4453. options.max_write_buffer_number = 5;
  4454. options.min_write_buffer_number_to_merge = 4;
  4455. options.comparator = test::BytewiseComparatorWithU64TsWrapper();
  4456. DestroyAndReopen(options);
  4457. // UDT persisted, get NotSupported.
  4458. ASSERT_TRUE(db_->GetNewestUserDefinedTimestamp(nullptr, &newest_timestamp)
  4459. .IsNotSupported());
  4460. options.persist_user_defined_timestamps = false;
  4461. options.allow_concurrent_memtable_write = false;
  4462. DestroyAndReopen(options);
  4463. ASSERT_TRUE(
  4464. db_->GetNewestUserDefinedTimestamp(nullptr, nullptr).IsInvalidArgument());
  4465. ColumnFamilyHandleImpl* cfh = static_cast_with_check<ColumnFamilyHandleImpl>(
  4466. db_->DefaultColumnFamily());
  4467. ColumnFamilyData* cfd = cfh->cfd();
  4468. // The column family hasn't seen any user defined timestamp
  4469. ASSERT_OK(db_->GetNewestUserDefinedTimestamp(nullptr, &newest_timestamp));
  4470. ASSERT_TRUE(newest_timestamp.empty());
  4471. ASSERT_OK(db_->Put(WriteOptions(), Key(1), EncodeAsUint64(1), "val1"));
  4472. // Testing get newest timestamp from mutable memtable.
  4473. ASSERT_OK(db_->GetNewestUserDefinedTimestamp(nullptr, &newest_timestamp));
  4474. ASSERT_EQ(EncodeAsUint64(1), newest_timestamp);
  4475. ASSERT_OK(db_->Put(WriteOptions(), Key(1), EncodeAsUint64(2), "val2"));
  4476. ASSERT_OK(dbfull()->TEST_SwitchMemtable(cfd));
  4477. // Testing get the newest timestamp from immutable memtable because the
  4478. // mutable one is empty.
  4479. ASSERT_OK(db_->GetNewestUserDefinedTimestamp(nullptr, &newest_timestamp));
  4480. ASSERT_EQ(EncodeAsUint64(2), newest_timestamp);
  4481. ASSERT_OK(db_->Put(WriteOptions(), Key(1), EncodeAsUint64(3), "val3"));
  4482. ASSERT_OK(db_->Put(WriteOptions(), Key(1), EncodeAsUint64(4), "val4"));
  4483. ASSERT_OK(dbfull()->TEST_SwitchMemtable(cfd));
  4484. // Testing get the newest timestamp from the more recent immutable memtable
  4485. // when there are multiple immutable memtables.
  4486. ASSERT_OK(db_->GetNewestUserDefinedTimestamp(nullptr, &newest_timestamp));
  4487. ASSERT_EQ(EncodeAsUint64(4), newest_timestamp);
  4488. ASSERT_OK(db_->Put(WriteOptions(), Key(1), EncodeAsUint64(5), "val5"));
  4489. // Testing get newest timestamp from mutable memtable when it has data, in the
  4490. // presence of immutable memtables.
  4491. ASSERT_OK(db_->GetNewestUserDefinedTimestamp(nullptr, &newest_timestamp));
  4492. ASSERT_EQ(EncodeAsUint64(5), newest_timestamp);
  4493. ASSERT_OK(Flush());
  4494. // After flushing and all the user defined timestamp are flushed. User defined
  4495. // timestamp info for SST files is available from MANIFEST.
  4496. ASSERT_OK(db_->GetNewestUserDefinedTimestamp(nullptr, &newest_timestamp));
  4497. ASSERT_EQ(EncodeAsUint64(5), newest_timestamp);
  4498. Reopen(options);
  4499. // Similar after flush, when there is no memtables, but some SST files,
  4500. // if MANIFEST records the upperbound of flushed timestamps because timestamps
  4501. // are not persisted in SST files, this info can be found.
  4502. ASSERT_OK(db_->GetNewestUserDefinedTimestamp(nullptr, &newest_timestamp));
  4503. ASSERT_EQ(EncodeAsUint64(5), newest_timestamp);
  4504. Close();
  4505. }
  4506. TEST_F(GetNewestUserDefinedTimestampTest, ConcurrentWrites) {
  4507. Options options = CurrentOptions();
  4508. options.create_if_missing = true;
  4509. options.comparator = test::BytewiseComparatorWithU64TsWrapper();
  4510. options.persist_user_defined_timestamps = false;
  4511. options.allow_concurrent_memtable_write = false;
  4512. DestroyAndReopen(options);
  4513. std::vector<std::thread> threads;
  4514. threads.reserve(10);
  4515. std::atomic<uint64_t> current_ts{0};
  4516. for (int i = 0; i < 10; i++) {
  4517. threads.emplace_back([this, i, &current_ts]() {
  4518. if (i % 2 == 0) {
  4519. std::string newest_timestamp;
  4520. ASSERT_OK(
  4521. db_->GetNewestUserDefinedTimestamp(nullptr, &newest_timestamp));
  4522. } else {
  4523. uint64_t write_ts = current_ts.fetch_add(1);
  4524. ASSERT_OK(db_->Put(WriteOptions(), Key(1), EncodeAsUint64(write_ts),
  4525. "val" + std::to_string(i)));
  4526. }
  4527. });
  4528. }
  4529. for (auto& t : threads) {
  4530. t.join();
  4531. }
  4532. Close();
  4533. }
  4534. } // namespace ROCKSDB_NAMESPACE
  4535. int main(int argc, char** argv) {
  4536. ROCKSDB_NAMESPACE::port::InstallStackTraceHandler();
  4537. ::testing::InitGoogleTest(&argc, argv);
  4538. RegisterCustomObjects(argc, argv);
  4539. return RUN_ALL_TESTS();
  4540. }