table_test.cc 170 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651
  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 <stdio.h>
  10. #include <algorithm>
  11. #include <iostream>
  12. #include <map>
  13. #include <memory>
  14. #include <string>
  15. #include <vector>
  16. #include "block_fetcher.h"
  17. #include "cache/lru_cache.h"
  18. #include "db/dbformat.h"
  19. #include "db/memtable.h"
  20. #include "db/write_batch_internal.h"
  21. #include "memtable/stl_wrappers.h"
  22. #include "meta_blocks.h"
  23. #include "monitoring/statistics.h"
  24. #include "port/port.h"
  25. #include "rocksdb/cache.h"
  26. #include "rocksdb/db.h"
  27. #include "rocksdb/env.h"
  28. #include "rocksdb/file_checksum.h"
  29. #include "rocksdb/file_system.h"
  30. #include "rocksdb/iterator.h"
  31. #include "rocksdb/memtablerep.h"
  32. #include "rocksdb/perf_context.h"
  33. #include "rocksdb/slice_transform.h"
  34. #include "rocksdb/statistics.h"
  35. #include "rocksdb/write_buffer_manager.h"
  36. #include "table/block_based/block.h"
  37. #include "table/block_based/block_based_table_builder.h"
  38. #include "table/block_based/block_based_table_factory.h"
  39. #include "table/block_based/block_based_table_reader.h"
  40. #include "table/block_based/block_builder.h"
  41. #include "table/block_based/flush_block_policy.h"
  42. #include "table/format.h"
  43. #include "table/get_context.h"
  44. #include "table/internal_iterator.h"
  45. #include "table/plain/plain_table_factory.h"
  46. #include "table/scoped_arena_iterator.h"
  47. #include "table/sst_file_writer_collectors.h"
  48. #include "test_util/sync_point.h"
  49. #include "test_util/testharness.h"
  50. #include "test_util/testutil.h"
  51. #include "util/compression.h"
  52. #include "util/file_checksum_helper.h"
  53. #include "util/random.h"
  54. #include "util/string_util.h"
  55. #include "utilities/merge_operators.h"
  56. namespace ROCKSDB_NAMESPACE {
  57. extern const uint64_t kLegacyBlockBasedTableMagicNumber;
  58. extern const uint64_t kLegacyPlainTableMagicNumber;
  59. extern const uint64_t kBlockBasedTableMagicNumber;
  60. extern const uint64_t kPlainTableMagicNumber;
  61. namespace {
  62. const std::string kDummyValue(10000, 'o');
  63. // DummyPropertiesCollector used to test BlockBasedTableProperties
  64. class DummyPropertiesCollector : public TablePropertiesCollector {
  65. public:
  66. const char* Name() const override { return ""; }
  67. Status Finish(UserCollectedProperties* /*properties*/) override {
  68. return Status::OK();
  69. }
  70. Status Add(const Slice& /*user_key*/, const Slice& /*value*/) override {
  71. return Status::OK();
  72. }
  73. UserCollectedProperties GetReadableProperties() const override {
  74. return UserCollectedProperties{};
  75. }
  76. };
  77. class DummyPropertiesCollectorFactory1
  78. : public TablePropertiesCollectorFactory {
  79. public:
  80. TablePropertiesCollector* CreateTablePropertiesCollector(
  81. TablePropertiesCollectorFactory::Context /*context*/) override {
  82. return new DummyPropertiesCollector();
  83. }
  84. const char* Name() const override { return "DummyPropertiesCollector1"; }
  85. };
  86. class DummyPropertiesCollectorFactory2
  87. : public TablePropertiesCollectorFactory {
  88. public:
  89. TablePropertiesCollector* CreateTablePropertiesCollector(
  90. TablePropertiesCollectorFactory::Context /*context*/) override {
  91. return new DummyPropertiesCollector();
  92. }
  93. const char* Name() const override { return "DummyPropertiesCollector2"; }
  94. };
  95. // Return reverse of "key".
  96. // Used to test non-lexicographic comparators.
  97. std::string Reverse(const Slice& key) {
  98. auto rev = key.ToString();
  99. std::reverse(rev.begin(), rev.end());
  100. return rev;
  101. }
  102. class ReverseKeyComparator : public Comparator {
  103. public:
  104. const char* Name() const override {
  105. return "rocksdb.ReverseBytewiseComparator";
  106. }
  107. int Compare(const Slice& a, const Slice& b) const override {
  108. return BytewiseComparator()->Compare(Reverse(a), Reverse(b));
  109. }
  110. void FindShortestSeparator(std::string* start,
  111. const Slice& limit) const override {
  112. std::string s = Reverse(*start);
  113. std::string l = Reverse(limit);
  114. BytewiseComparator()->FindShortestSeparator(&s, l);
  115. *start = Reverse(s);
  116. }
  117. void FindShortSuccessor(std::string* key) const override {
  118. std::string s = Reverse(*key);
  119. BytewiseComparator()->FindShortSuccessor(&s);
  120. *key = Reverse(s);
  121. }
  122. };
  123. ReverseKeyComparator reverse_key_comparator;
  124. void Increment(const Comparator* cmp, std::string* key) {
  125. if (cmp == BytewiseComparator()) {
  126. key->push_back('\0');
  127. } else {
  128. assert(cmp == &reverse_key_comparator);
  129. std::string rev = Reverse(*key);
  130. rev.push_back('\0');
  131. *key = Reverse(rev);
  132. }
  133. }
  134. } // namespace
  135. // Helper class for tests to unify the interface between
  136. // BlockBuilder/TableBuilder and Block/Table.
  137. class Constructor {
  138. public:
  139. explicit Constructor(const Comparator* cmp)
  140. : data_(stl_wrappers::LessOfComparator(cmp)) {}
  141. virtual ~Constructor() { }
  142. void Add(const std::string& key, const Slice& value) {
  143. data_[key] = value.ToString();
  144. }
  145. // Finish constructing the data structure with all the keys that have
  146. // been added so far. Returns the keys in sorted order in "*keys"
  147. // and stores the key/value pairs in "*kvmap"
  148. void Finish(const Options& options, const ImmutableCFOptions& ioptions,
  149. const MutableCFOptions& moptions,
  150. const BlockBasedTableOptions& table_options,
  151. const InternalKeyComparator& internal_comparator,
  152. std::vector<std::string>* keys, stl_wrappers::KVMap* kvmap) {
  153. last_internal_key_ = &internal_comparator;
  154. *kvmap = data_;
  155. keys->clear();
  156. for (const auto& kv : data_) {
  157. keys->push_back(kv.first);
  158. }
  159. data_.clear();
  160. Status s = FinishImpl(options, ioptions, moptions, table_options,
  161. internal_comparator, *kvmap);
  162. ASSERT_TRUE(s.ok()) << s.ToString();
  163. }
  164. // Construct the data structure from the data in "data"
  165. virtual Status FinishImpl(const Options& options,
  166. const ImmutableCFOptions& ioptions,
  167. const MutableCFOptions& moptions,
  168. const BlockBasedTableOptions& table_options,
  169. const InternalKeyComparator& internal_comparator,
  170. const stl_wrappers::KVMap& data) = 0;
  171. virtual InternalIterator* NewIterator(
  172. const SliceTransform* prefix_extractor = nullptr) const = 0;
  173. virtual const stl_wrappers::KVMap& data() { return data_; }
  174. virtual bool IsArenaMode() const { return false; }
  175. virtual DB* db() const { return nullptr; } // Overridden in DBConstructor
  176. virtual bool AnywayDeleteIterator() const { return false; }
  177. protected:
  178. const InternalKeyComparator* last_internal_key_;
  179. private:
  180. stl_wrappers::KVMap data_;
  181. };
  182. class BlockConstructor: public Constructor {
  183. public:
  184. explicit BlockConstructor(const Comparator* cmp)
  185. : Constructor(cmp),
  186. comparator_(cmp),
  187. block_(nullptr) { }
  188. ~BlockConstructor() override { delete block_; }
  189. Status FinishImpl(const Options& /*options*/,
  190. const ImmutableCFOptions& /*ioptions*/,
  191. const MutableCFOptions& /*moptions*/,
  192. const BlockBasedTableOptions& table_options,
  193. const InternalKeyComparator& /*internal_comparator*/,
  194. const stl_wrappers::KVMap& kv_map) override {
  195. delete block_;
  196. block_ = nullptr;
  197. BlockBuilder builder(table_options.block_restart_interval);
  198. for (const auto kv : kv_map) {
  199. builder.Add(kv.first, kv.second);
  200. }
  201. // Open the block
  202. data_ = builder.Finish().ToString();
  203. BlockContents contents;
  204. contents.data = data_;
  205. block_ = new Block(std::move(contents), kDisableGlobalSequenceNumber);
  206. return Status::OK();
  207. }
  208. InternalIterator* NewIterator(
  209. const SliceTransform* /*prefix_extractor*/) const override {
  210. return block_->NewDataIterator(comparator_, comparator_);
  211. }
  212. private:
  213. const Comparator* comparator_;
  214. std::string data_;
  215. Block* block_;
  216. BlockConstructor();
  217. };
  218. // A helper class that converts internal format keys into user keys
  219. class KeyConvertingIterator : public InternalIterator {
  220. public:
  221. explicit KeyConvertingIterator(InternalIterator* iter,
  222. bool arena_mode = false)
  223. : iter_(iter), arena_mode_(arena_mode) {}
  224. ~KeyConvertingIterator() override {
  225. if (arena_mode_) {
  226. iter_->~InternalIterator();
  227. } else {
  228. delete iter_;
  229. }
  230. }
  231. bool Valid() const override { return iter_->Valid() && status_.ok(); }
  232. void Seek(const Slice& target) override {
  233. ParsedInternalKey ikey(target, kMaxSequenceNumber, kTypeValue);
  234. std::string encoded;
  235. AppendInternalKey(&encoded, ikey);
  236. iter_->Seek(encoded);
  237. }
  238. void SeekForPrev(const Slice& target) override {
  239. ParsedInternalKey ikey(target, kMaxSequenceNumber, kTypeValue);
  240. std::string encoded;
  241. AppendInternalKey(&encoded, ikey);
  242. iter_->SeekForPrev(encoded);
  243. }
  244. void SeekToFirst() override { iter_->SeekToFirst(); }
  245. void SeekToLast() override { iter_->SeekToLast(); }
  246. void Next() override { iter_->Next(); }
  247. void Prev() override { iter_->Prev(); }
  248. bool IsOutOfBound() override { return iter_->IsOutOfBound(); }
  249. Slice key() const override {
  250. assert(Valid());
  251. ParsedInternalKey parsed_key;
  252. if (!ParseInternalKey(iter_->key(), &parsed_key)) {
  253. status_ = Status::Corruption("malformed internal key");
  254. return Slice("corrupted key");
  255. }
  256. return parsed_key.user_key;
  257. }
  258. Slice value() const override { return iter_->value(); }
  259. Status status() const override {
  260. return status_.ok() ? iter_->status() : status_;
  261. }
  262. private:
  263. mutable Status status_;
  264. InternalIterator* iter_;
  265. bool arena_mode_;
  266. // No copying allowed
  267. KeyConvertingIterator(const KeyConvertingIterator&);
  268. void operator=(const KeyConvertingIterator&);
  269. };
  270. class TableConstructor: public Constructor {
  271. public:
  272. explicit TableConstructor(const Comparator* cmp,
  273. bool convert_to_internal_key = false,
  274. int level = -1, SequenceNumber largest_seqno = 0)
  275. : Constructor(cmp),
  276. largest_seqno_(largest_seqno),
  277. convert_to_internal_key_(convert_to_internal_key),
  278. level_(level) {
  279. env_ = ROCKSDB_NAMESPACE::Env::Default();
  280. }
  281. ~TableConstructor() override { Reset(); }
  282. Status FinishImpl(const Options& options, const ImmutableCFOptions& ioptions,
  283. const MutableCFOptions& moptions,
  284. const BlockBasedTableOptions& /*table_options*/,
  285. const InternalKeyComparator& internal_comparator,
  286. const stl_wrappers::KVMap& kv_map) override {
  287. Reset();
  288. soptions.use_mmap_reads = ioptions.allow_mmap_reads;
  289. file_writer_.reset(test::GetWritableFileWriter(new test::StringSink(),
  290. "" /* don't care */));
  291. std::unique_ptr<TableBuilder> builder;
  292. std::vector<std::unique_ptr<IntTblPropCollectorFactory>>
  293. int_tbl_prop_collector_factories;
  294. if (largest_seqno_ != 0) {
  295. // Pretend that it's an external file written by SstFileWriter.
  296. int_tbl_prop_collector_factories.emplace_back(
  297. new SstFileWriterPropertiesCollectorFactory(2 /* version */,
  298. 0 /* global_seqno*/));
  299. }
  300. std::string column_family_name;
  301. builder.reset(ioptions.table_factory->NewTableBuilder(
  302. TableBuilderOptions(ioptions, moptions, internal_comparator,
  303. &int_tbl_prop_collector_factories,
  304. options.compression, options.sample_for_compression,
  305. options.compression_opts, false /* skip_filters */,
  306. column_family_name, level_),
  307. TablePropertiesCollectorFactory::Context::kUnknownColumnFamily,
  308. file_writer_.get()));
  309. for (const auto kv : kv_map) {
  310. if (convert_to_internal_key_) {
  311. ParsedInternalKey ikey(kv.first, kMaxSequenceNumber, kTypeValue);
  312. std::string encoded;
  313. AppendInternalKey(&encoded, ikey);
  314. builder->Add(encoded, kv.second);
  315. } else {
  316. builder->Add(kv.first, kv.second);
  317. }
  318. EXPECT_TRUE(builder->status().ok());
  319. }
  320. Status s = builder->Finish();
  321. file_writer_->Flush();
  322. EXPECT_TRUE(s.ok()) << s.ToString();
  323. EXPECT_EQ(TEST_GetSink()->contents().size(), builder->FileSize());
  324. // Open the table
  325. uniq_id_ = cur_uniq_id_++;
  326. file_reader_.reset(test::GetRandomAccessFileReader(new test::StringSource(
  327. TEST_GetSink()->contents(), uniq_id_, ioptions.allow_mmap_reads)));
  328. const bool kSkipFilters = true;
  329. const bool kImmortal = true;
  330. return ioptions.table_factory->NewTableReader(
  331. TableReaderOptions(ioptions, moptions.prefix_extractor.get(), soptions,
  332. internal_comparator, !kSkipFilters, !kImmortal,
  333. level_, largest_seqno_, &block_cache_tracer_),
  334. std::move(file_reader_), TEST_GetSink()->contents().size(),
  335. &table_reader_);
  336. }
  337. InternalIterator* NewIterator(
  338. const SliceTransform* prefix_extractor) const override {
  339. ReadOptions ro;
  340. InternalIterator* iter = table_reader_->NewIterator(
  341. ro, prefix_extractor, /*arena=*/nullptr, /*skip_filters=*/false,
  342. TableReaderCaller::kUncategorized);
  343. if (convert_to_internal_key_) {
  344. return new KeyConvertingIterator(iter);
  345. } else {
  346. return iter;
  347. }
  348. }
  349. uint64_t ApproximateOffsetOf(const Slice& key) const {
  350. if (convert_to_internal_key_) {
  351. InternalKey ikey(key, kMaxSequenceNumber, kTypeValue);
  352. const Slice skey = ikey.Encode();
  353. return table_reader_->ApproximateOffsetOf(
  354. skey, TableReaderCaller::kUncategorized);
  355. }
  356. return table_reader_->ApproximateOffsetOf(
  357. key, TableReaderCaller::kUncategorized);
  358. }
  359. virtual Status Reopen(const ImmutableCFOptions& ioptions,
  360. const MutableCFOptions& moptions) {
  361. file_reader_.reset(test::GetRandomAccessFileReader(new test::StringSource(
  362. TEST_GetSink()->contents(), uniq_id_, ioptions.allow_mmap_reads)));
  363. return ioptions.table_factory->NewTableReader(
  364. TableReaderOptions(ioptions, moptions.prefix_extractor.get(), soptions,
  365. *last_internal_key_),
  366. std::move(file_reader_), TEST_GetSink()->contents().size(),
  367. &table_reader_);
  368. }
  369. virtual TableReader* GetTableReader() { return table_reader_.get(); }
  370. bool AnywayDeleteIterator() const override {
  371. return convert_to_internal_key_;
  372. }
  373. void ResetTableReader() { table_reader_.reset(); }
  374. bool ConvertToInternalKey() { return convert_to_internal_key_; }
  375. test::StringSink* TEST_GetSink() {
  376. return ROCKSDB_NAMESPACE::test::GetStringSinkFromLegacyWriter(
  377. file_writer_.get());
  378. }
  379. BlockCacheTracer block_cache_tracer_;
  380. private:
  381. void Reset() {
  382. uniq_id_ = 0;
  383. table_reader_.reset();
  384. file_writer_.reset();
  385. file_reader_.reset();
  386. }
  387. uint64_t uniq_id_;
  388. std::unique_ptr<WritableFileWriter> file_writer_;
  389. std::unique_ptr<RandomAccessFileReader> file_reader_;
  390. std::unique_ptr<TableReader> table_reader_;
  391. SequenceNumber largest_seqno_;
  392. bool convert_to_internal_key_;
  393. int level_;
  394. TableConstructor();
  395. static uint64_t cur_uniq_id_;
  396. EnvOptions soptions;
  397. Env* env_;
  398. };
  399. uint64_t TableConstructor::cur_uniq_id_ = 1;
  400. class MemTableConstructor: public Constructor {
  401. public:
  402. explicit MemTableConstructor(const Comparator* cmp, WriteBufferManager* wb)
  403. : Constructor(cmp),
  404. internal_comparator_(cmp),
  405. write_buffer_manager_(wb),
  406. table_factory_(new SkipListFactory) {
  407. options_.memtable_factory = table_factory_;
  408. ImmutableCFOptions ioptions(options_);
  409. memtable_ =
  410. new MemTable(internal_comparator_, ioptions, MutableCFOptions(options_),
  411. wb, kMaxSequenceNumber, 0 /* column_family_id */);
  412. memtable_->Ref();
  413. }
  414. ~MemTableConstructor() override { delete memtable_->Unref(); }
  415. Status FinishImpl(const Options&, const ImmutableCFOptions& ioptions,
  416. const MutableCFOptions& /*moptions*/,
  417. const BlockBasedTableOptions& /*table_options*/,
  418. const InternalKeyComparator& /*internal_comparator*/,
  419. const stl_wrappers::KVMap& kv_map) override {
  420. delete memtable_->Unref();
  421. ImmutableCFOptions mem_ioptions(ioptions);
  422. memtable_ = new MemTable(internal_comparator_, mem_ioptions,
  423. MutableCFOptions(options_), write_buffer_manager_,
  424. kMaxSequenceNumber, 0 /* column_family_id */);
  425. memtable_->Ref();
  426. int seq = 1;
  427. for (const auto kv : kv_map) {
  428. memtable_->Add(seq, kTypeValue, kv.first, kv.second);
  429. seq++;
  430. }
  431. return Status::OK();
  432. }
  433. InternalIterator* NewIterator(
  434. const SliceTransform* /*prefix_extractor*/) const override {
  435. return new KeyConvertingIterator(
  436. memtable_->NewIterator(ReadOptions(), &arena_), true);
  437. }
  438. bool AnywayDeleteIterator() const override { return true; }
  439. bool IsArenaMode() const override { return true; }
  440. private:
  441. mutable Arena arena_;
  442. InternalKeyComparator internal_comparator_;
  443. Options options_;
  444. WriteBufferManager* write_buffer_manager_;
  445. MemTable* memtable_;
  446. std::shared_ptr<SkipListFactory> table_factory_;
  447. };
  448. class InternalIteratorFromIterator : public InternalIterator {
  449. public:
  450. explicit InternalIteratorFromIterator(Iterator* it) : it_(it) {}
  451. bool Valid() const override { return it_->Valid(); }
  452. void Seek(const Slice& target) override { it_->Seek(target); }
  453. void SeekForPrev(const Slice& target) override { it_->SeekForPrev(target); }
  454. void SeekToFirst() override { it_->SeekToFirst(); }
  455. void SeekToLast() override { it_->SeekToLast(); }
  456. void Next() override { it_->Next(); }
  457. void Prev() override { it_->Prev(); }
  458. Slice key() const override { return it_->key(); }
  459. Slice value() const override { return it_->value(); }
  460. Status status() const override { return it_->status(); }
  461. private:
  462. std::unique_ptr<Iterator> it_;
  463. };
  464. class DBConstructor: public Constructor {
  465. public:
  466. explicit DBConstructor(const Comparator* cmp)
  467. : Constructor(cmp),
  468. comparator_(cmp) {
  469. db_ = nullptr;
  470. NewDB();
  471. }
  472. ~DBConstructor() override { delete db_; }
  473. Status FinishImpl(const Options& /*options*/,
  474. const ImmutableCFOptions& /*ioptions*/,
  475. const MutableCFOptions& /*moptions*/,
  476. const BlockBasedTableOptions& /*table_options*/,
  477. const InternalKeyComparator& /*internal_comparator*/,
  478. const stl_wrappers::KVMap& kv_map) override {
  479. delete db_;
  480. db_ = nullptr;
  481. NewDB();
  482. for (const auto kv : kv_map) {
  483. WriteBatch batch;
  484. batch.Put(kv.first, kv.second);
  485. EXPECT_TRUE(db_->Write(WriteOptions(), &batch).ok());
  486. }
  487. return Status::OK();
  488. }
  489. InternalIterator* NewIterator(
  490. const SliceTransform* /*prefix_extractor*/) const override {
  491. return new InternalIteratorFromIterator(db_->NewIterator(ReadOptions()));
  492. }
  493. DB* db() const override { return db_; }
  494. private:
  495. void NewDB() {
  496. std::string name = test::PerThreadDBPath("table_testdb");
  497. Options options;
  498. options.comparator = comparator_;
  499. Status status = DestroyDB(name, options);
  500. ASSERT_TRUE(status.ok()) << status.ToString();
  501. options.create_if_missing = true;
  502. options.error_if_exists = true;
  503. options.write_buffer_size = 10000; // Something small to force merging
  504. status = DB::Open(options, name, &db_);
  505. ASSERT_TRUE(status.ok()) << status.ToString();
  506. }
  507. const Comparator* comparator_;
  508. DB* db_;
  509. };
  510. enum TestType {
  511. BLOCK_BASED_TABLE_TEST,
  512. #ifndef ROCKSDB_LITE
  513. PLAIN_TABLE_SEMI_FIXED_PREFIX,
  514. PLAIN_TABLE_FULL_STR_PREFIX,
  515. PLAIN_TABLE_TOTAL_ORDER,
  516. #endif // !ROCKSDB_LITE
  517. BLOCK_TEST,
  518. MEMTABLE_TEST,
  519. DB_TEST
  520. };
  521. struct TestArgs {
  522. TestType type;
  523. bool reverse_compare;
  524. int restart_interval;
  525. CompressionType compression;
  526. uint32_t format_version;
  527. bool use_mmap;
  528. };
  529. static std::vector<TestArgs> GenerateArgList() {
  530. std::vector<TestArgs> test_args;
  531. std::vector<TestType> test_types = {
  532. BLOCK_BASED_TABLE_TEST,
  533. #ifndef ROCKSDB_LITE
  534. PLAIN_TABLE_SEMI_FIXED_PREFIX,
  535. PLAIN_TABLE_FULL_STR_PREFIX,
  536. PLAIN_TABLE_TOTAL_ORDER,
  537. #endif // !ROCKSDB_LITE
  538. BLOCK_TEST,
  539. MEMTABLE_TEST, DB_TEST};
  540. std::vector<bool> reverse_compare_types = {false, true};
  541. std::vector<int> restart_intervals = {16, 1, 1024};
  542. // Only add compression if it is supported
  543. std::vector<std::pair<CompressionType, bool>> compression_types;
  544. compression_types.emplace_back(kNoCompression, false);
  545. if (Snappy_Supported()) {
  546. compression_types.emplace_back(kSnappyCompression, false);
  547. }
  548. if (Zlib_Supported()) {
  549. compression_types.emplace_back(kZlibCompression, false);
  550. compression_types.emplace_back(kZlibCompression, true);
  551. }
  552. if (BZip2_Supported()) {
  553. compression_types.emplace_back(kBZip2Compression, false);
  554. compression_types.emplace_back(kBZip2Compression, true);
  555. }
  556. if (LZ4_Supported()) {
  557. compression_types.emplace_back(kLZ4Compression, false);
  558. compression_types.emplace_back(kLZ4Compression, true);
  559. compression_types.emplace_back(kLZ4HCCompression, false);
  560. compression_types.emplace_back(kLZ4HCCompression, true);
  561. }
  562. if (XPRESS_Supported()) {
  563. compression_types.emplace_back(kXpressCompression, false);
  564. compression_types.emplace_back(kXpressCompression, true);
  565. }
  566. if (ZSTD_Supported()) {
  567. compression_types.emplace_back(kZSTD, false);
  568. compression_types.emplace_back(kZSTD, true);
  569. }
  570. for (auto test_type : test_types) {
  571. for (auto reverse_compare : reverse_compare_types) {
  572. #ifndef ROCKSDB_LITE
  573. if (test_type == PLAIN_TABLE_SEMI_FIXED_PREFIX ||
  574. test_type == PLAIN_TABLE_FULL_STR_PREFIX ||
  575. test_type == PLAIN_TABLE_TOTAL_ORDER) {
  576. // Plain table doesn't use restart index or compression.
  577. TestArgs one_arg;
  578. one_arg.type = test_type;
  579. one_arg.reverse_compare = reverse_compare;
  580. one_arg.restart_interval = restart_intervals[0];
  581. one_arg.compression = compression_types[0].first;
  582. one_arg.use_mmap = true;
  583. test_args.push_back(one_arg);
  584. one_arg.use_mmap = false;
  585. test_args.push_back(one_arg);
  586. continue;
  587. }
  588. #endif // !ROCKSDB_LITE
  589. for (auto restart_interval : restart_intervals) {
  590. for (auto compression_type : compression_types) {
  591. TestArgs one_arg;
  592. one_arg.type = test_type;
  593. one_arg.reverse_compare = reverse_compare;
  594. one_arg.restart_interval = restart_interval;
  595. one_arg.compression = compression_type.first;
  596. one_arg.format_version = compression_type.second ? 2 : 1;
  597. one_arg.use_mmap = false;
  598. test_args.push_back(one_arg);
  599. }
  600. }
  601. }
  602. }
  603. return test_args;
  604. }
  605. // In order to make all tests run for plain table format, including
  606. // those operating on empty keys, create a new prefix transformer which
  607. // return fixed prefix if the slice is not shorter than the prefix length,
  608. // and the full slice if it is shorter.
  609. class FixedOrLessPrefixTransform : public SliceTransform {
  610. private:
  611. const size_t prefix_len_;
  612. public:
  613. explicit FixedOrLessPrefixTransform(size_t prefix_len) :
  614. prefix_len_(prefix_len) {
  615. }
  616. const char* Name() const override { return "rocksdb.FixedPrefix"; }
  617. Slice Transform(const Slice& src) const override {
  618. assert(InDomain(src));
  619. if (src.size() < prefix_len_) {
  620. return src;
  621. }
  622. return Slice(src.data(), prefix_len_);
  623. }
  624. bool InDomain(const Slice& /*src*/) const override { return true; }
  625. bool InRange(const Slice& dst) const override {
  626. return (dst.size() <= prefix_len_);
  627. }
  628. bool FullLengthEnabled(size_t* /*len*/) const override { return false; }
  629. };
  630. class HarnessTest : public testing::Test {
  631. public:
  632. HarnessTest()
  633. : ioptions_(options_),
  634. moptions_(options_),
  635. constructor_(nullptr),
  636. write_buffer_(options_.db_write_buffer_size) {}
  637. void Init(const TestArgs& args) {
  638. delete constructor_;
  639. constructor_ = nullptr;
  640. options_ = Options();
  641. options_.compression = args.compression;
  642. // Use shorter block size for tests to exercise block boundary
  643. // conditions more.
  644. if (args.reverse_compare) {
  645. options_.comparator = &reverse_key_comparator;
  646. }
  647. internal_comparator_.reset(
  648. new test::PlainInternalKeyComparator(options_.comparator));
  649. support_prev_ = true;
  650. only_support_prefix_seek_ = false;
  651. options_.allow_mmap_reads = args.use_mmap;
  652. switch (args.type) {
  653. case BLOCK_BASED_TABLE_TEST:
  654. table_options_.flush_block_policy_factory.reset(
  655. new FlushBlockBySizePolicyFactory());
  656. table_options_.block_size = 256;
  657. table_options_.block_restart_interval = args.restart_interval;
  658. table_options_.index_block_restart_interval = args.restart_interval;
  659. table_options_.format_version = args.format_version;
  660. options_.table_factory.reset(
  661. new BlockBasedTableFactory(table_options_));
  662. constructor_ = new TableConstructor(
  663. options_.comparator, true /* convert_to_internal_key_ */);
  664. internal_comparator_.reset(
  665. new InternalKeyComparator(options_.comparator));
  666. break;
  667. // Plain table is not supported in ROCKSDB_LITE
  668. #ifndef ROCKSDB_LITE
  669. case PLAIN_TABLE_SEMI_FIXED_PREFIX:
  670. support_prev_ = false;
  671. only_support_prefix_seek_ = true;
  672. options_.prefix_extractor.reset(new FixedOrLessPrefixTransform(2));
  673. options_.table_factory.reset(NewPlainTableFactory());
  674. constructor_ = new TableConstructor(
  675. options_.comparator, true /* convert_to_internal_key_ */);
  676. internal_comparator_.reset(
  677. new InternalKeyComparator(options_.comparator));
  678. break;
  679. case PLAIN_TABLE_FULL_STR_PREFIX:
  680. support_prev_ = false;
  681. only_support_prefix_seek_ = true;
  682. options_.prefix_extractor.reset(NewNoopTransform());
  683. options_.table_factory.reset(NewPlainTableFactory());
  684. constructor_ = new TableConstructor(
  685. options_.comparator, true /* convert_to_internal_key_ */);
  686. internal_comparator_.reset(
  687. new InternalKeyComparator(options_.comparator));
  688. break;
  689. case PLAIN_TABLE_TOTAL_ORDER:
  690. support_prev_ = false;
  691. only_support_prefix_seek_ = false;
  692. options_.prefix_extractor = nullptr;
  693. {
  694. PlainTableOptions plain_table_options;
  695. plain_table_options.user_key_len = kPlainTableVariableLength;
  696. plain_table_options.bloom_bits_per_key = 0;
  697. plain_table_options.hash_table_ratio = 0;
  698. options_.table_factory.reset(
  699. NewPlainTableFactory(plain_table_options));
  700. }
  701. constructor_ = new TableConstructor(
  702. options_.comparator, true /* convert_to_internal_key_ */);
  703. internal_comparator_.reset(
  704. new InternalKeyComparator(options_.comparator));
  705. break;
  706. #endif // !ROCKSDB_LITE
  707. case BLOCK_TEST:
  708. table_options_.block_size = 256;
  709. options_.table_factory.reset(
  710. new BlockBasedTableFactory(table_options_));
  711. constructor_ = new BlockConstructor(options_.comparator);
  712. break;
  713. case MEMTABLE_TEST:
  714. table_options_.block_size = 256;
  715. options_.table_factory.reset(
  716. new BlockBasedTableFactory(table_options_));
  717. constructor_ = new MemTableConstructor(options_.comparator,
  718. &write_buffer_);
  719. break;
  720. case DB_TEST:
  721. table_options_.block_size = 256;
  722. options_.table_factory.reset(
  723. new BlockBasedTableFactory(table_options_));
  724. constructor_ = new DBConstructor(options_.comparator);
  725. break;
  726. }
  727. ioptions_ = ImmutableCFOptions(options_);
  728. moptions_ = MutableCFOptions(options_);
  729. }
  730. ~HarnessTest() override { delete constructor_; }
  731. void Add(const std::string& key, const std::string& value) {
  732. constructor_->Add(key, value);
  733. }
  734. void Test(Random* rnd) {
  735. std::vector<std::string> keys;
  736. stl_wrappers::KVMap data;
  737. constructor_->Finish(options_, ioptions_, moptions_, table_options_,
  738. *internal_comparator_, &keys, &data);
  739. TestForwardScan(keys, data);
  740. if (support_prev_) {
  741. TestBackwardScan(keys, data);
  742. }
  743. TestRandomAccess(rnd, keys, data);
  744. }
  745. void TestForwardScan(const std::vector<std::string>& /*keys*/,
  746. const stl_wrappers::KVMap& data) {
  747. InternalIterator* iter = constructor_->NewIterator();
  748. ASSERT_TRUE(!iter->Valid());
  749. iter->SeekToFirst();
  750. for (stl_wrappers::KVMap::const_iterator model_iter = data.begin();
  751. model_iter != data.end(); ++model_iter) {
  752. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  753. iter->Next();
  754. }
  755. ASSERT_TRUE(!iter->Valid());
  756. if (constructor_->IsArenaMode() && !constructor_->AnywayDeleteIterator()) {
  757. iter->~InternalIterator();
  758. } else {
  759. delete iter;
  760. }
  761. }
  762. void TestBackwardScan(const std::vector<std::string>& /*keys*/,
  763. const stl_wrappers::KVMap& data) {
  764. InternalIterator* iter = constructor_->NewIterator();
  765. ASSERT_TRUE(!iter->Valid());
  766. iter->SeekToLast();
  767. for (stl_wrappers::KVMap::const_reverse_iterator model_iter = data.rbegin();
  768. model_iter != data.rend(); ++model_iter) {
  769. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  770. iter->Prev();
  771. }
  772. ASSERT_TRUE(!iter->Valid());
  773. if (constructor_->IsArenaMode() && !constructor_->AnywayDeleteIterator()) {
  774. iter->~InternalIterator();
  775. } else {
  776. delete iter;
  777. }
  778. }
  779. void TestRandomAccess(Random* rnd, const std::vector<std::string>& keys,
  780. const stl_wrappers::KVMap& data) {
  781. static const bool kVerbose = false;
  782. InternalIterator* iter = constructor_->NewIterator();
  783. ASSERT_TRUE(!iter->Valid());
  784. stl_wrappers::KVMap::const_iterator model_iter = data.begin();
  785. if (kVerbose) fprintf(stderr, "---\n");
  786. for (int i = 0; i < 200; i++) {
  787. const int toss = rnd->Uniform(support_prev_ ? 5 : 3);
  788. switch (toss) {
  789. case 0: {
  790. if (iter->Valid()) {
  791. if (kVerbose) fprintf(stderr, "Next\n");
  792. iter->Next();
  793. ++model_iter;
  794. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  795. }
  796. break;
  797. }
  798. case 1: {
  799. if (kVerbose) fprintf(stderr, "SeekToFirst\n");
  800. iter->SeekToFirst();
  801. model_iter = data.begin();
  802. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  803. break;
  804. }
  805. case 2: {
  806. std::string key = PickRandomKey(rnd, keys);
  807. model_iter = data.lower_bound(key);
  808. if (kVerbose) fprintf(stderr, "Seek '%s'\n",
  809. EscapeString(key).c_str());
  810. iter->Seek(Slice(key));
  811. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  812. break;
  813. }
  814. case 3: {
  815. if (iter->Valid()) {
  816. if (kVerbose) fprintf(stderr, "Prev\n");
  817. iter->Prev();
  818. if (model_iter == data.begin()) {
  819. model_iter = data.end(); // Wrap around to invalid value
  820. } else {
  821. --model_iter;
  822. }
  823. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  824. }
  825. break;
  826. }
  827. case 4: {
  828. if (kVerbose) fprintf(stderr, "SeekToLast\n");
  829. iter->SeekToLast();
  830. if (keys.empty()) {
  831. model_iter = data.end();
  832. } else {
  833. std::string last = data.rbegin()->first;
  834. model_iter = data.lower_bound(last);
  835. }
  836. ASSERT_EQ(ToString(data, model_iter), ToString(iter));
  837. break;
  838. }
  839. }
  840. }
  841. if (constructor_->IsArenaMode() && !constructor_->AnywayDeleteIterator()) {
  842. iter->~InternalIterator();
  843. } else {
  844. delete iter;
  845. }
  846. }
  847. std::string ToString(const stl_wrappers::KVMap& data,
  848. const stl_wrappers::KVMap::const_iterator& it) {
  849. if (it == data.end()) {
  850. return "END";
  851. } else {
  852. return "'" + it->first + "->" + it->second + "'";
  853. }
  854. }
  855. std::string ToString(const stl_wrappers::KVMap& data,
  856. const stl_wrappers::KVMap::const_reverse_iterator& it) {
  857. if (it == data.rend()) {
  858. return "END";
  859. } else {
  860. return "'" + it->first + "->" + it->second + "'";
  861. }
  862. }
  863. std::string ToString(const InternalIterator* it) {
  864. if (!it->Valid()) {
  865. return "END";
  866. } else {
  867. return "'" + it->key().ToString() + "->" + it->value().ToString() + "'";
  868. }
  869. }
  870. std::string PickRandomKey(Random* rnd, const std::vector<std::string>& keys) {
  871. if (keys.empty()) {
  872. return "foo";
  873. } else {
  874. const int index = rnd->Uniform(static_cast<int>(keys.size()));
  875. std::string result = keys[index];
  876. switch (rnd->Uniform(support_prev_ ? 3 : 1)) {
  877. case 0:
  878. // Return an existing key
  879. break;
  880. case 1: {
  881. // Attempt to return something smaller than an existing key
  882. if (result.size() > 0 && result[result.size() - 1] > '\0'
  883. && (!only_support_prefix_seek_
  884. || options_.prefix_extractor->Transform(result).size()
  885. < result.size())) {
  886. result[result.size() - 1]--;
  887. }
  888. break;
  889. }
  890. case 2: {
  891. // Return something larger than an existing key
  892. Increment(options_.comparator, &result);
  893. break;
  894. }
  895. }
  896. return result;
  897. }
  898. }
  899. // Returns nullptr if not running against a DB
  900. DB* db() const { return constructor_->db(); }
  901. void RandomizedHarnessTest(size_t part, size_t total) {
  902. std::vector<TestArgs> args = GenerateArgList();
  903. assert(part);
  904. assert(part <= total);
  905. for (size_t i = 0; i < args.size(); i++) {
  906. if ((i % total) + 1 != part) {
  907. continue;
  908. }
  909. Init(args[i]);
  910. Random rnd(test::RandomSeed() + 5);
  911. for (int num_entries = 0; num_entries < 2000;
  912. num_entries += (num_entries < 50 ? 1 : 200)) {
  913. for (int e = 0; e < num_entries; e++) {
  914. std::string v;
  915. Add(test::RandomKey(&rnd, rnd.Skewed(4)),
  916. test::RandomString(&rnd, rnd.Skewed(5), &v).ToString());
  917. }
  918. Test(&rnd);
  919. }
  920. }
  921. }
  922. private:
  923. Options options_ = Options();
  924. ImmutableCFOptions ioptions_;
  925. MutableCFOptions moptions_;
  926. BlockBasedTableOptions table_options_ = BlockBasedTableOptions();
  927. Constructor* constructor_;
  928. WriteBufferManager write_buffer_;
  929. bool support_prev_;
  930. bool only_support_prefix_seek_;
  931. std::shared_ptr<InternalKeyComparator> internal_comparator_;
  932. };
  933. static bool Between(uint64_t val, uint64_t low, uint64_t high) {
  934. bool result = (val >= low) && (val <= high);
  935. if (!result) {
  936. fprintf(stderr, "Value %llu is not in range [%llu, %llu]\n",
  937. (unsigned long long)(val),
  938. (unsigned long long)(low),
  939. (unsigned long long)(high));
  940. }
  941. return result;
  942. }
  943. // Tests against all kinds of tables
  944. class TableTest : public testing::Test {
  945. public:
  946. const InternalKeyComparator& GetPlainInternalComparator(
  947. const Comparator* comp) {
  948. if (!plain_internal_comparator) {
  949. plain_internal_comparator.reset(
  950. new test::PlainInternalKeyComparator(comp));
  951. }
  952. return *plain_internal_comparator;
  953. }
  954. void IndexTest(BlockBasedTableOptions table_options);
  955. private:
  956. std::unique_ptr<InternalKeyComparator> plain_internal_comparator;
  957. };
  958. class GeneralTableTest : public TableTest {};
  959. class BlockBasedTableTest
  960. : public TableTest,
  961. virtual public ::testing::WithParamInterface<uint32_t> {
  962. public:
  963. BlockBasedTableTest() : format_(GetParam()) {
  964. env_ = ROCKSDB_NAMESPACE::Env::Default();
  965. }
  966. BlockBasedTableOptions GetBlockBasedTableOptions() {
  967. BlockBasedTableOptions options;
  968. options.format_version = format_;
  969. return options;
  970. }
  971. void SetupTracingTest(TableConstructor* c) {
  972. test_path_ = test::PerThreadDBPath("block_based_table_tracing_test");
  973. EXPECT_OK(env_->CreateDir(test_path_));
  974. trace_file_path_ = test_path_ + "/block_cache_trace_file";
  975. TraceOptions trace_opt;
  976. std::unique_ptr<TraceWriter> trace_writer;
  977. EXPECT_OK(NewFileTraceWriter(env_, EnvOptions(), trace_file_path_,
  978. &trace_writer));
  979. c->block_cache_tracer_.StartTrace(env_, trace_opt, std::move(trace_writer));
  980. {
  981. std::string user_key = "k01";
  982. InternalKey internal_key(user_key, 0, kTypeValue);
  983. std::string encoded_key = internal_key.Encode().ToString();
  984. c->Add(encoded_key, kDummyValue);
  985. }
  986. {
  987. std::string user_key = "k02";
  988. InternalKey internal_key(user_key, 0, kTypeValue);
  989. std::string encoded_key = internal_key.Encode().ToString();
  990. c->Add(encoded_key, kDummyValue);
  991. }
  992. }
  993. void VerifyBlockAccessTrace(
  994. TableConstructor* c,
  995. const std::vector<BlockCacheTraceRecord>& expected_records) {
  996. c->block_cache_tracer_.EndTrace();
  997. std::unique_ptr<TraceReader> trace_reader;
  998. Status s =
  999. NewFileTraceReader(env_, EnvOptions(), trace_file_path_, &trace_reader);
  1000. EXPECT_OK(s);
  1001. BlockCacheTraceReader reader(std::move(trace_reader));
  1002. BlockCacheTraceHeader header;
  1003. EXPECT_OK(reader.ReadHeader(&header));
  1004. uint32_t index = 0;
  1005. while (s.ok()) {
  1006. BlockCacheTraceRecord access;
  1007. s = reader.ReadAccess(&access);
  1008. if (!s.ok()) {
  1009. break;
  1010. }
  1011. ASSERT_LT(index, expected_records.size());
  1012. EXPECT_NE("", access.block_key);
  1013. EXPECT_EQ(access.block_type, expected_records[index].block_type);
  1014. EXPECT_GT(access.block_size, 0);
  1015. EXPECT_EQ(access.caller, expected_records[index].caller);
  1016. EXPECT_EQ(access.no_insert, expected_records[index].no_insert);
  1017. EXPECT_EQ(access.is_cache_hit, expected_records[index].is_cache_hit);
  1018. // Get
  1019. if (access.caller == TableReaderCaller::kUserGet) {
  1020. EXPECT_EQ(access.referenced_key,
  1021. expected_records[index].referenced_key);
  1022. EXPECT_EQ(access.get_id, expected_records[index].get_id);
  1023. EXPECT_EQ(access.get_from_user_specified_snapshot,
  1024. expected_records[index].get_from_user_specified_snapshot);
  1025. if (access.block_type == TraceType::kBlockTraceDataBlock) {
  1026. EXPECT_GT(access.referenced_data_size, 0);
  1027. EXPECT_GT(access.num_keys_in_block, 0);
  1028. EXPECT_EQ(access.referenced_key_exist_in_block,
  1029. expected_records[index].referenced_key_exist_in_block);
  1030. }
  1031. } else {
  1032. EXPECT_EQ(access.referenced_key, "");
  1033. EXPECT_EQ(access.get_id, 0);
  1034. EXPECT_TRUE(access.get_from_user_specified_snapshot == Boolean::kFalse);
  1035. EXPECT_EQ(access.referenced_data_size, 0);
  1036. EXPECT_EQ(access.num_keys_in_block, 0);
  1037. EXPECT_TRUE(access.referenced_key_exist_in_block == Boolean::kFalse);
  1038. }
  1039. index++;
  1040. }
  1041. EXPECT_EQ(index, expected_records.size());
  1042. EXPECT_OK(env_->DeleteFile(trace_file_path_));
  1043. EXPECT_OK(env_->DeleteDir(test_path_));
  1044. }
  1045. protected:
  1046. uint64_t IndexUncompressedHelper(bool indexCompress);
  1047. private:
  1048. uint32_t format_;
  1049. Env* env_;
  1050. std::string trace_file_path_;
  1051. std::string test_path_;
  1052. };
  1053. class PlainTableTest : public TableTest {};
  1054. class TablePropertyTest : public testing::Test {};
  1055. class BBTTailPrefetchTest : public TableTest {};
  1056. // The helper class to test the file checksum
  1057. class FileChecksumTestHelper {
  1058. public:
  1059. FileChecksumTestHelper(bool convert_to_internal_key = false)
  1060. : convert_to_internal_key_(convert_to_internal_key) {
  1061. sink_ = new test::StringSink();
  1062. }
  1063. ~FileChecksumTestHelper() {}
  1064. void CreateWriteableFile() {
  1065. file_writer_.reset(test::GetWritableFileWriter(sink_, "" /* don't care */));
  1066. }
  1067. void SetFileChecksumFunc(FileChecksumFunc* checksum_func) {
  1068. if (file_writer_ != nullptr) {
  1069. file_writer_->TEST_SetFileChecksumFunc(checksum_func);
  1070. }
  1071. }
  1072. WritableFileWriter* GetFileWriter() { return file_writer_.get(); }
  1073. Status ResetTableBuilder(std::unique_ptr<TableBuilder>&& builder) {
  1074. assert(builder != nullptr);
  1075. table_builder_ = std::move(builder);
  1076. return Status::OK();
  1077. }
  1078. void AddKVtoKVMap(int num_entries) {
  1079. Random rnd(test::RandomSeed());
  1080. for (int i = 0; i < num_entries; i++) {
  1081. std::string v;
  1082. test::RandomString(&rnd, 100, &v);
  1083. kv_map_[test::RandomKey(&rnd, 20)] = v;
  1084. }
  1085. }
  1086. Status WriteKVAndFlushTable() {
  1087. for (const auto kv : kv_map_) {
  1088. if (convert_to_internal_key_) {
  1089. ParsedInternalKey ikey(kv.first, kMaxSequenceNumber, kTypeValue);
  1090. std::string encoded;
  1091. AppendInternalKey(&encoded, ikey);
  1092. table_builder_->Add(encoded, kv.second);
  1093. } else {
  1094. table_builder_->Add(kv.first, kv.second);
  1095. }
  1096. EXPECT_TRUE(table_builder_->status().ok());
  1097. }
  1098. Status s = table_builder_->Finish();
  1099. file_writer_->Flush();
  1100. EXPECT_TRUE(s.ok());
  1101. EXPECT_EQ(sink_->contents().size(), table_builder_->FileSize());
  1102. return s;
  1103. }
  1104. std::string GetFileChecksum() { return table_builder_->GetFileChecksum(); }
  1105. const char* GetFileChecksumFuncName() {
  1106. return table_builder_->GetFileChecksumFuncName();
  1107. }
  1108. Status CalculateFileChecksum(FileChecksumFunc* file_checksum_func,
  1109. std::string* checksum) {
  1110. assert(file_checksum_func != nullptr);
  1111. cur_uniq_id_ = checksum_uniq_id_++;
  1112. test::StringSink* ss_rw =
  1113. ROCKSDB_NAMESPACE::test::GetStringSinkFromLegacyWriter(
  1114. file_writer_.get());
  1115. file_reader_.reset(test::GetRandomAccessFileReader(
  1116. new test::StringSource(ss_rw->contents())));
  1117. std::unique_ptr<char[]> scratch(new char[2048]);
  1118. Slice result;
  1119. uint64_t offset = 0;
  1120. std::string tmp_checksum;
  1121. bool first_read = true;
  1122. Status s;
  1123. s = file_reader_->Read(offset, 2048, &result, scratch.get(), false);
  1124. if (!s.ok()) {
  1125. return s;
  1126. }
  1127. while (result.size() != 0) {
  1128. if (first_read) {
  1129. first_read = false;
  1130. tmp_checksum = file_checksum_func->Value(scratch.get(), result.size());
  1131. } else {
  1132. tmp_checksum = file_checksum_func->Extend(tmp_checksum, scratch.get(),
  1133. result.size());
  1134. }
  1135. offset += static_cast<uint64_t>(result.size());
  1136. s = file_reader_->Read(offset, 2048, &result, scratch.get(), false);
  1137. if (!s.ok()) {
  1138. return s;
  1139. }
  1140. }
  1141. EXPECT_EQ(offset, static_cast<uint64_t>(table_builder_->FileSize()));
  1142. *checksum = tmp_checksum;
  1143. return Status::OK();
  1144. }
  1145. private:
  1146. bool convert_to_internal_key_;
  1147. uint64_t cur_uniq_id_;
  1148. std::unique_ptr<WritableFileWriter> file_writer_;
  1149. std::unique_ptr<RandomAccessFileReader> file_reader_;
  1150. std::unique_ptr<TableBuilder> table_builder_;
  1151. stl_wrappers::KVMap kv_map_;
  1152. test::StringSink* sink_;
  1153. static uint64_t checksum_uniq_id_;
  1154. };
  1155. uint64_t FileChecksumTestHelper::checksum_uniq_id_ = 1;
  1156. INSTANTIATE_TEST_CASE_P(FormatDef, BlockBasedTableTest,
  1157. testing::Values(test::kDefaultFormatVersion));
  1158. INSTANTIATE_TEST_CASE_P(FormatLatest, BlockBasedTableTest,
  1159. testing::Values(test::kLatestFormatVersion));
  1160. // This test serves as the living tutorial for the prefix scan of user collected
  1161. // properties.
  1162. TEST_F(TablePropertyTest, PrefixScanTest) {
  1163. UserCollectedProperties props{{"num.111.1", "1"},
  1164. {"num.111.2", "2"},
  1165. {"num.111.3", "3"},
  1166. {"num.333.1", "1"},
  1167. {"num.333.2", "2"},
  1168. {"num.333.3", "3"},
  1169. {"num.555.1", "1"},
  1170. {"num.555.2", "2"},
  1171. {"num.555.3", "3"}, };
  1172. // prefixes that exist
  1173. for (const std::string& prefix : {"num.111", "num.333", "num.555"}) {
  1174. int num = 0;
  1175. for (auto pos = props.lower_bound(prefix);
  1176. pos != props.end() &&
  1177. pos->first.compare(0, prefix.size(), prefix) == 0;
  1178. ++pos) {
  1179. ++num;
  1180. auto key = prefix + "." + ToString(num);
  1181. ASSERT_EQ(key, pos->first);
  1182. ASSERT_EQ(ToString(num), pos->second);
  1183. }
  1184. ASSERT_EQ(3, num);
  1185. }
  1186. // prefixes that don't exist
  1187. for (const std::string& prefix :
  1188. {"num.000", "num.222", "num.444", "num.666"}) {
  1189. auto pos = props.lower_bound(prefix);
  1190. ASSERT_TRUE(pos == props.end() ||
  1191. pos->first.compare(0, prefix.size(), prefix) != 0);
  1192. }
  1193. }
  1194. // This test include all the basic checks except those for index size and block
  1195. // size, which will be conducted in separated unit tests.
  1196. TEST_P(BlockBasedTableTest, BasicBlockBasedTableProperties) {
  1197. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  1198. c.Add("a1", "val1");
  1199. c.Add("b2", "val2");
  1200. c.Add("c3", "val3");
  1201. c.Add("d4", "val4");
  1202. c.Add("e5", "val5");
  1203. c.Add("f6", "val6");
  1204. c.Add("g7", "val7");
  1205. c.Add("h8", "val8");
  1206. c.Add("j9", "val9");
  1207. uint64_t diff_internal_user_bytes = 9 * 8; // 8 is seq size, 9 k-v totally
  1208. std::vector<std::string> keys;
  1209. stl_wrappers::KVMap kvmap;
  1210. Options options;
  1211. options.compression = kNoCompression;
  1212. options.statistics = CreateDBStatistics();
  1213. options.statistics->set_stats_level(StatsLevel::kAll);
  1214. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1215. table_options.block_restart_interval = 1;
  1216. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1217. ImmutableCFOptions ioptions(options);
  1218. MutableCFOptions moptions(options);
  1219. ioptions.statistics = options.statistics.get();
  1220. c.Finish(options, ioptions, moptions, table_options,
  1221. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  1222. ASSERT_EQ(options.statistics->getTickerCount(NUMBER_BLOCK_NOT_COMPRESSED), 0);
  1223. auto& props = *c.GetTableReader()->GetTableProperties();
  1224. ASSERT_EQ(kvmap.size(), props.num_entries);
  1225. auto raw_key_size = kvmap.size() * 2ul;
  1226. auto raw_value_size = kvmap.size() * 4ul;
  1227. ASSERT_EQ(raw_key_size + diff_internal_user_bytes, props.raw_key_size);
  1228. ASSERT_EQ(raw_value_size, props.raw_value_size);
  1229. ASSERT_EQ(1ul, props.num_data_blocks);
  1230. ASSERT_EQ("", props.filter_policy_name); // no filter policy is used
  1231. // Verify data size.
  1232. BlockBuilder block_builder(1);
  1233. for (const auto& item : kvmap) {
  1234. block_builder.Add(item.first, item.second);
  1235. }
  1236. Slice content = block_builder.Finish();
  1237. ASSERT_EQ(content.size() + kBlockTrailerSize + diff_internal_user_bytes,
  1238. props.data_size);
  1239. c.ResetTableReader();
  1240. }
  1241. #ifdef SNAPPY
  1242. uint64_t BlockBasedTableTest::IndexUncompressedHelper(bool compressed) {
  1243. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  1244. constexpr size_t kNumKeys = 10000;
  1245. for (size_t k = 0; k < kNumKeys; ++k) {
  1246. c.Add("key" + ToString(k), "val" + ToString(k));
  1247. }
  1248. std::vector<std::string> keys;
  1249. stl_wrappers::KVMap kvmap;
  1250. Options options;
  1251. options.compression = kSnappyCompression;
  1252. options.statistics = CreateDBStatistics();
  1253. options.statistics->set_stats_level(StatsLevel::kAll);
  1254. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1255. table_options.block_restart_interval = 1;
  1256. table_options.enable_index_compression = compressed;
  1257. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1258. ImmutableCFOptions ioptions(options);
  1259. MutableCFOptions moptions(options);
  1260. ioptions.statistics = options.statistics.get();
  1261. c.Finish(options, ioptions, moptions, table_options,
  1262. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  1263. c.ResetTableReader();
  1264. return options.statistics->getTickerCount(NUMBER_BLOCK_COMPRESSED);
  1265. }
  1266. TEST_P(BlockBasedTableTest, IndexUncompressed) {
  1267. uint64_t tbl1_compressed_cnt = IndexUncompressedHelper(true);
  1268. uint64_t tbl2_compressed_cnt = IndexUncompressedHelper(false);
  1269. // tbl1_compressed_cnt should include 1 index block
  1270. EXPECT_EQ(tbl2_compressed_cnt + 1, tbl1_compressed_cnt);
  1271. }
  1272. #endif // SNAPPY
  1273. TEST_P(BlockBasedTableTest, BlockBasedTableProperties2) {
  1274. TableConstructor c(&reverse_key_comparator);
  1275. std::vector<std::string> keys;
  1276. stl_wrappers::KVMap kvmap;
  1277. {
  1278. Options options;
  1279. options.compression = CompressionType::kNoCompression;
  1280. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1281. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1282. const ImmutableCFOptions ioptions(options);
  1283. const MutableCFOptions moptions(options);
  1284. c.Finish(options, ioptions, moptions, table_options,
  1285. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  1286. auto& props = *c.GetTableReader()->GetTableProperties();
  1287. // Default comparator
  1288. ASSERT_EQ("leveldb.BytewiseComparator", props.comparator_name);
  1289. // No merge operator
  1290. ASSERT_EQ("nullptr", props.merge_operator_name);
  1291. // No prefix extractor
  1292. ASSERT_EQ("nullptr", props.prefix_extractor_name);
  1293. // No property collectors
  1294. ASSERT_EQ("[]", props.property_collectors_names);
  1295. // No filter policy is used
  1296. ASSERT_EQ("", props.filter_policy_name);
  1297. // Compression type == that set:
  1298. ASSERT_EQ("NoCompression", props.compression_name);
  1299. c.ResetTableReader();
  1300. }
  1301. {
  1302. Options options;
  1303. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1304. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1305. options.comparator = &reverse_key_comparator;
  1306. options.merge_operator = MergeOperators::CreateUInt64AddOperator();
  1307. options.prefix_extractor.reset(NewNoopTransform());
  1308. options.table_properties_collector_factories.emplace_back(
  1309. new DummyPropertiesCollectorFactory1());
  1310. options.table_properties_collector_factories.emplace_back(
  1311. new DummyPropertiesCollectorFactory2());
  1312. const ImmutableCFOptions ioptions(options);
  1313. const MutableCFOptions moptions(options);
  1314. c.Finish(options, ioptions, moptions, table_options,
  1315. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  1316. auto& props = *c.GetTableReader()->GetTableProperties();
  1317. ASSERT_EQ("rocksdb.ReverseBytewiseComparator", props.comparator_name);
  1318. ASSERT_EQ("UInt64AddOperator", props.merge_operator_name);
  1319. ASSERT_EQ("rocksdb.Noop", props.prefix_extractor_name);
  1320. ASSERT_EQ("[DummyPropertiesCollector1,DummyPropertiesCollector2]",
  1321. props.property_collectors_names);
  1322. ASSERT_EQ("", props.filter_policy_name); // no filter policy is used
  1323. c.ResetTableReader();
  1324. }
  1325. }
  1326. TEST_P(BlockBasedTableTest, RangeDelBlock) {
  1327. TableConstructor c(BytewiseComparator());
  1328. std::vector<std::string> keys = {"1pika", "2chu"};
  1329. std::vector<std::string> vals = {"p", "c"};
  1330. std::vector<RangeTombstone> expected_tombstones = {
  1331. {"1pika", "2chu", 0},
  1332. {"2chu", "c", 1},
  1333. {"2chu", "c", 0},
  1334. {"c", "p", 0},
  1335. };
  1336. for (int i = 0; i < 2; i++) {
  1337. RangeTombstone t(keys[i], vals[i], i);
  1338. std::pair<InternalKey, Slice> p = t.Serialize();
  1339. c.Add(p.first.Encode().ToString(), p.second);
  1340. }
  1341. std::vector<std::string> sorted_keys;
  1342. stl_wrappers::KVMap kvmap;
  1343. Options options;
  1344. options.compression = kNoCompression;
  1345. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1346. table_options.block_restart_interval = 1;
  1347. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1348. const ImmutableCFOptions ioptions(options);
  1349. const MutableCFOptions moptions(options);
  1350. std::unique_ptr<InternalKeyComparator> internal_cmp(
  1351. new InternalKeyComparator(options.comparator));
  1352. c.Finish(options, ioptions, moptions, table_options, *internal_cmp,
  1353. &sorted_keys, &kvmap);
  1354. for (int j = 0; j < 2; ++j) {
  1355. std::unique_ptr<InternalIterator> iter(
  1356. c.GetTableReader()->NewRangeTombstoneIterator(ReadOptions()));
  1357. if (j > 0) {
  1358. // For second iteration, delete the table reader object and verify the
  1359. // iterator can still access its metablock's range tombstones.
  1360. c.ResetTableReader();
  1361. }
  1362. ASSERT_FALSE(iter->Valid());
  1363. iter->SeekToFirst();
  1364. ASSERT_TRUE(iter->Valid());
  1365. for (size_t i = 0; i < expected_tombstones.size(); i++) {
  1366. ASSERT_TRUE(iter->Valid());
  1367. ParsedInternalKey parsed_key;
  1368. ASSERT_TRUE(ParseInternalKey(iter->key(), &parsed_key));
  1369. RangeTombstone t(parsed_key, iter->value());
  1370. const auto& expected_t = expected_tombstones[i];
  1371. ASSERT_EQ(t.start_key_, expected_t.start_key_);
  1372. ASSERT_EQ(t.end_key_, expected_t.end_key_);
  1373. ASSERT_EQ(t.seq_, expected_t.seq_);
  1374. iter->Next();
  1375. }
  1376. ASSERT_TRUE(!iter->Valid());
  1377. }
  1378. }
  1379. TEST_P(BlockBasedTableTest, FilterPolicyNameProperties) {
  1380. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  1381. c.Add("a1", "val1");
  1382. std::vector<std::string> keys;
  1383. stl_wrappers::KVMap kvmap;
  1384. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1385. table_options.filter_policy.reset(NewBloomFilterPolicy(10));
  1386. Options options;
  1387. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1388. const ImmutableCFOptions ioptions(options);
  1389. const MutableCFOptions moptions(options);
  1390. c.Finish(options, ioptions, moptions, table_options,
  1391. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  1392. auto& props = *c.GetTableReader()->GetTableProperties();
  1393. ASSERT_EQ("rocksdb.BuiltinBloomFilter", props.filter_policy_name);
  1394. c.ResetTableReader();
  1395. }
  1396. //
  1397. // BlockBasedTableTest::PrefetchTest
  1398. //
  1399. void AssertKeysInCache(BlockBasedTable* table_reader,
  1400. const std::vector<std::string>& keys_in_cache,
  1401. const std::vector<std::string>& keys_not_in_cache,
  1402. bool convert = false) {
  1403. if (convert) {
  1404. for (auto key : keys_in_cache) {
  1405. InternalKey ikey(key, kMaxSequenceNumber, kTypeValue);
  1406. ASSERT_TRUE(table_reader->TEST_KeyInCache(ReadOptions(), ikey.Encode()));
  1407. }
  1408. for (auto key : keys_not_in_cache) {
  1409. InternalKey ikey(key, kMaxSequenceNumber, kTypeValue);
  1410. ASSERT_TRUE(!table_reader->TEST_KeyInCache(ReadOptions(), ikey.Encode()));
  1411. }
  1412. } else {
  1413. for (auto key : keys_in_cache) {
  1414. ASSERT_TRUE(table_reader->TEST_KeyInCache(ReadOptions(), key));
  1415. }
  1416. for (auto key : keys_not_in_cache) {
  1417. ASSERT_TRUE(!table_reader->TEST_KeyInCache(ReadOptions(), key));
  1418. }
  1419. }
  1420. }
  1421. void PrefetchRange(TableConstructor* c, Options* opt,
  1422. BlockBasedTableOptions* table_options, const char* key_begin,
  1423. const char* key_end,
  1424. const std::vector<std::string>& keys_in_cache,
  1425. const std::vector<std::string>& keys_not_in_cache,
  1426. const Status expected_status = Status::OK()) {
  1427. // reset the cache and reopen the table
  1428. table_options->block_cache = NewLRUCache(16 * 1024 * 1024, 4);
  1429. opt->table_factory.reset(NewBlockBasedTableFactory(*table_options));
  1430. const ImmutableCFOptions ioptions2(*opt);
  1431. const MutableCFOptions moptions(*opt);
  1432. ASSERT_OK(c->Reopen(ioptions2, moptions));
  1433. // prefetch
  1434. auto* table_reader = dynamic_cast<BlockBasedTable*>(c->GetTableReader());
  1435. Status s;
  1436. std::unique_ptr<Slice> begin, end;
  1437. std::unique_ptr<InternalKey> i_begin, i_end;
  1438. if (key_begin != nullptr) {
  1439. if (c->ConvertToInternalKey()) {
  1440. i_begin.reset(new InternalKey(key_begin, kMaxSequenceNumber, kTypeValue));
  1441. begin.reset(new Slice(i_begin->Encode()));
  1442. } else {
  1443. begin.reset(new Slice(key_begin));
  1444. }
  1445. }
  1446. if (key_end != nullptr) {
  1447. if (c->ConvertToInternalKey()) {
  1448. i_end.reset(new InternalKey(key_end, kMaxSequenceNumber, kTypeValue));
  1449. end.reset(new Slice(i_end->Encode()));
  1450. } else {
  1451. end.reset(new Slice(key_end));
  1452. }
  1453. }
  1454. s = table_reader->Prefetch(begin.get(), end.get());
  1455. ASSERT_TRUE(s.code() == expected_status.code());
  1456. // assert our expectation in cache warmup
  1457. AssertKeysInCache(table_reader, keys_in_cache, keys_not_in_cache,
  1458. c->ConvertToInternalKey());
  1459. c->ResetTableReader();
  1460. }
  1461. TEST_P(BlockBasedTableTest, PrefetchTest) {
  1462. // The purpose of this test is to test the prefetching operation built into
  1463. // BlockBasedTable.
  1464. Options opt;
  1465. std::unique_ptr<InternalKeyComparator> ikc;
  1466. ikc.reset(new test::PlainInternalKeyComparator(opt.comparator));
  1467. opt.compression = kNoCompression;
  1468. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1469. table_options.block_size = 1024;
  1470. // big enough so we don't ever lose cached values.
  1471. table_options.block_cache = NewLRUCache(16 * 1024 * 1024, 4);
  1472. opt.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1473. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  1474. c.Add("k01", "hello");
  1475. c.Add("k02", "hello2");
  1476. c.Add("k03", std::string(10000, 'x'));
  1477. c.Add("k04", std::string(200000, 'x'));
  1478. c.Add("k05", std::string(300000, 'x'));
  1479. c.Add("k06", "hello3");
  1480. c.Add("k07", std::string(100000, 'x'));
  1481. std::vector<std::string> keys;
  1482. stl_wrappers::KVMap kvmap;
  1483. const ImmutableCFOptions ioptions(opt);
  1484. const MutableCFOptions moptions(opt);
  1485. c.Finish(opt, ioptions, moptions, table_options, *ikc, &keys, &kvmap);
  1486. c.ResetTableReader();
  1487. // We get the following data spread :
  1488. //
  1489. // Data block Index
  1490. // ========================
  1491. // [ k01 k02 k03 ] k03
  1492. // [ k04 ] k04
  1493. // [ k05 ] k05
  1494. // [ k06 k07 ] k07
  1495. // Simple
  1496. PrefetchRange(&c, &opt, &table_options,
  1497. /*key_range=*/"k01", "k05",
  1498. /*keys_in_cache=*/{"k01", "k02", "k03", "k04", "k05"},
  1499. /*keys_not_in_cache=*/{"k06", "k07"});
  1500. PrefetchRange(&c, &opt, &table_options, "k01", "k01", {"k01", "k02", "k03"},
  1501. {"k04", "k05", "k06", "k07"});
  1502. // odd
  1503. PrefetchRange(&c, &opt, &table_options, "a", "z",
  1504. {"k01", "k02", "k03", "k04", "k05", "k06", "k07"}, {});
  1505. PrefetchRange(&c, &opt, &table_options, "k00", "k00", {"k01", "k02", "k03"},
  1506. {"k04", "k05", "k06", "k07"});
  1507. // Edge cases
  1508. PrefetchRange(&c, &opt, &table_options, "k00", "k06",
  1509. {"k01", "k02", "k03", "k04", "k05", "k06", "k07"}, {});
  1510. PrefetchRange(&c, &opt, &table_options, "k00", "zzz",
  1511. {"k01", "k02", "k03", "k04", "k05", "k06", "k07"}, {});
  1512. // null keys
  1513. PrefetchRange(&c, &opt, &table_options, nullptr, nullptr,
  1514. {"k01", "k02", "k03", "k04", "k05", "k06", "k07"}, {});
  1515. PrefetchRange(&c, &opt, &table_options, "k04", nullptr,
  1516. {"k04", "k05", "k06", "k07"}, {"k01", "k02", "k03"});
  1517. PrefetchRange(&c, &opt, &table_options, nullptr, "k05",
  1518. {"k01", "k02", "k03", "k04", "k05"}, {"k06", "k07"});
  1519. // invalid
  1520. PrefetchRange(&c, &opt, &table_options, "k06", "k00", {}, {},
  1521. Status::InvalidArgument(Slice("k06 "), Slice("k07")));
  1522. c.ResetTableReader();
  1523. }
  1524. TEST_P(BlockBasedTableTest, TotalOrderSeekOnHashIndex) {
  1525. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1526. for (int i = 0; i <= 5; ++i) {
  1527. Options options;
  1528. // Make each key/value an individual block
  1529. table_options.block_size = 64;
  1530. switch (i) {
  1531. case 0:
  1532. // Binary search index
  1533. table_options.index_type = BlockBasedTableOptions::kBinarySearch;
  1534. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  1535. break;
  1536. case 1:
  1537. // Hash search index
  1538. table_options.index_type = BlockBasedTableOptions::kHashSearch;
  1539. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  1540. options.prefix_extractor.reset(NewFixedPrefixTransform(4));
  1541. break;
  1542. case 2:
  1543. // Hash search index with hash_index_allow_collision
  1544. table_options.index_type = BlockBasedTableOptions::kHashSearch;
  1545. table_options.hash_index_allow_collision = true;
  1546. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  1547. options.prefix_extractor.reset(NewFixedPrefixTransform(4));
  1548. break;
  1549. case 3:
  1550. // Hash search index with filter policy
  1551. table_options.index_type = BlockBasedTableOptions::kHashSearch;
  1552. table_options.filter_policy.reset(NewBloomFilterPolicy(10));
  1553. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  1554. options.prefix_extractor.reset(NewFixedPrefixTransform(4));
  1555. break;
  1556. case 4:
  1557. // Two-level index
  1558. table_options.index_type = BlockBasedTableOptions::kTwoLevelIndexSearch;
  1559. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  1560. break;
  1561. case 5:
  1562. // Binary search with first key
  1563. table_options.index_type =
  1564. BlockBasedTableOptions::kBinarySearchWithFirstKey;
  1565. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  1566. break;
  1567. }
  1568. TableConstructor c(BytewiseComparator(),
  1569. true /* convert_to_internal_key_ */);
  1570. c.Add("aaaa1", std::string('a', 56));
  1571. c.Add("bbaa1", std::string('a', 56));
  1572. c.Add("cccc1", std::string('a', 56));
  1573. c.Add("bbbb1", std::string('a', 56));
  1574. c.Add("baaa1", std::string('a', 56));
  1575. c.Add("abbb1", std::string('a', 56));
  1576. c.Add("cccc2", std::string('a', 56));
  1577. std::vector<std::string> keys;
  1578. stl_wrappers::KVMap kvmap;
  1579. const ImmutableCFOptions ioptions(options);
  1580. const MutableCFOptions moptions(options);
  1581. c.Finish(options, ioptions, moptions, table_options,
  1582. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  1583. auto props = c.GetTableReader()->GetTableProperties();
  1584. ASSERT_EQ(7u, props->num_data_blocks);
  1585. auto* reader = c.GetTableReader();
  1586. ReadOptions ro;
  1587. ro.total_order_seek = true;
  1588. std::unique_ptr<InternalIterator> iter(reader->NewIterator(
  1589. ro, moptions.prefix_extractor.get(), /*arena=*/nullptr,
  1590. /*skip_filters=*/false, TableReaderCaller::kUncategorized));
  1591. iter->Seek(InternalKey("b", 0, kTypeValue).Encode());
  1592. ASSERT_OK(iter->status());
  1593. ASSERT_TRUE(iter->Valid());
  1594. ASSERT_EQ("baaa1", ExtractUserKey(iter->key()).ToString());
  1595. iter->Next();
  1596. ASSERT_OK(iter->status());
  1597. ASSERT_TRUE(iter->Valid());
  1598. ASSERT_EQ("bbaa1", ExtractUserKey(iter->key()).ToString());
  1599. iter->Seek(InternalKey("bb", 0, kTypeValue).Encode());
  1600. ASSERT_OK(iter->status());
  1601. ASSERT_TRUE(iter->Valid());
  1602. ASSERT_EQ("bbaa1", ExtractUserKey(iter->key()).ToString());
  1603. iter->Next();
  1604. ASSERT_OK(iter->status());
  1605. ASSERT_TRUE(iter->Valid());
  1606. ASSERT_EQ("bbbb1", ExtractUserKey(iter->key()).ToString());
  1607. iter->Seek(InternalKey("bbb", 0, kTypeValue).Encode());
  1608. ASSERT_OK(iter->status());
  1609. ASSERT_TRUE(iter->Valid());
  1610. ASSERT_EQ("bbbb1", ExtractUserKey(iter->key()).ToString());
  1611. iter->Next();
  1612. ASSERT_OK(iter->status());
  1613. ASSERT_TRUE(iter->Valid());
  1614. ASSERT_EQ("cccc1", ExtractUserKey(iter->key()).ToString());
  1615. }
  1616. }
  1617. TEST_P(BlockBasedTableTest, NoopTransformSeek) {
  1618. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1619. table_options.filter_policy.reset(NewBloomFilterPolicy(10));
  1620. Options options;
  1621. options.comparator = BytewiseComparator();
  1622. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  1623. options.prefix_extractor.reset(NewNoopTransform());
  1624. TableConstructor c(options.comparator);
  1625. // To tickle the PrefixMayMatch bug it is important that the
  1626. // user-key is a single byte so that the index key exactly matches
  1627. // the user-key.
  1628. InternalKey key("a", 1, kTypeValue);
  1629. c.Add(key.Encode().ToString(), "b");
  1630. std::vector<std::string> keys;
  1631. stl_wrappers::KVMap kvmap;
  1632. const ImmutableCFOptions ioptions(options);
  1633. const MutableCFOptions moptions(options);
  1634. const InternalKeyComparator internal_comparator(options.comparator);
  1635. c.Finish(options, ioptions, moptions, table_options, internal_comparator,
  1636. &keys, &kvmap);
  1637. auto* reader = c.GetTableReader();
  1638. for (int i = 0; i < 2; ++i) {
  1639. ReadOptions ro;
  1640. ro.total_order_seek = (i == 0);
  1641. std::unique_ptr<InternalIterator> iter(reader->NewIterator(
  1642. ro, moptions.prefix_extractor.get(), /*arena=*/nullptr,
  1643. /*skip_filters=*/false, TableReaderCaller::kUncategorized));
  1644. iter->Seek(key.Encode());
  1645. ASSERT_OK(iter->status());
  1646. ASSERT_TRUE(iter->Valid());
  1647. ASSERT_EQ("a", ExtractUserKey(iter->key()).ToString());
  1648. }
  1649. }
  1650. TEST_P(BlockBasedTableTest, SkipPrefixBloomFilter) {
  1651. // if DB is opened with a prefix extractor of a different name,
  1652. // prefix bloom is skipped when read the file
  1653. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1654. table_options.filter_policy.reset(NewBloomFilterPolicy(2));
  1655. table_options.whole_key_filtering = false;
  1656. Options options;
  1657. options.comparator = BytewiseComparator();
  1658. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  1659. options.prefix_extractor.reset(NewFixedPrefixTransform(1));
  1660. TableConstructor c(options.comparator);
  1661. InternalKey key("abcdefghijk", 1, kTypeValue);
  1662. c.Add(key.Encode().ToString(), "test");
  1663. std::vector<std::string> keys;
  1664. stl_wrappers::KVMap kvmap;
  1665. const ImmutableCFOptions ioptions(options);
  1666. const MutableCFOptions moptions(options);
  1667. const InternalKeyComparator internal_comparator(options.comparator);
  1668. c.Finish(options, ioptions, moptions, table_options, internal_comparator,
  1669. &keys, &kvmap);
  1670. // TODO(Zhongyi): update test to use MutableCFOptions
  1671. options.prefix_extractor.reset(NewFixedPrefixTransform(9));
  1672. const ImmutableCFOptions new_ioptions(options);
  1673. const MutableCFOptions new_moptions(options);
  1674. c.Reopen(new_ioptions, new_moptions);
  1675. auto reader = c.GetTableReader();
  1676. std::unique_ptr<InternalIterator> db_iter(reader->NewIterator(
  1677. ReadOptions(), new_moptions.prefix_extractor.get(), /*arena=*/nullptr,
  1678. /*skip_filters=*/false, TableReaderCaller::kUncategorized));
  1679. // Test point lookup
  1680. // only one kv
  1681. for (auto& kv : kvmap) {
  1682. db_iter->Seek(kv.first);
  1683. ASSERT_TRUE(db_iter->Valid());
  1684. ASSERT_OK(db_iter->status());
  1685. ASSERT_EQ(db_iter->key(), kv.first);
  1686. ASSERT_EQ(db_iter->value(), kv.second);
  1687. }
  1688. }
  1689. static std::string RandomString(Random* rnd, int len) {
  1690. std::string r;
  1691. test::RandomString(rnd, len, &r);
  1692. return r;
  1693. }
  1694. void AddInternalKey(TableConstructor* c, const std::string& prefix,
  1695. std::string value = "v", int /*suffix_len*/ = 800) {
  1696. static Random rnd(1023);
  1697. InternalKey k(prefix + RandomString(&rnd, 800), 0, kTypeValue);
  1698. c->Add(k.Encode().ToString(), value);
  1699. }
  1700. void TableTest::IndexTest(BlockBasedTableOptions table_options) {
  1701. TableConstructor c(BytewiseComparator());
  1702. // keys with prefix length 3, make sure the key/value is big enough to fill
  1703. // one block
  1704. AddInternalKey(&c, "0015");
  1705. AddInternalKey(&c, "0035");
  1706. AddInternalKey(&c, "0054");
  1707. AddInternalKey(&c, "0055");
  1708. AddInternalKey(&c, "0056");
  1709. AddInternalKey(&c, "0057");
  1710. AddInternalKey(&c, "0058");
  1711. AddInternalKey(&c, "0075");
  1712. AddInternalKey(&c, "0076");
  1713. AddInternalKey(&c, "0095");
  1714. std::vector<std::string> keys;
  1715. stl_wrappers::KVMap kvmap;
  1716. Options options;
  1717. options.prefix_extractor.reset(NewFixedPrefixTransform(3));
  1718. table_options.block_size = 1700;
  1719. table_options.block_cache = NewLRUCache(1024, 4);
  1720. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1721. std::unique_ptr<InternalKeyComparator> comparator(
  1722. new InternalKeyComparator(BytewiseComparator()));
  1723. const ImmutableCFOptions ioptions(options);
  1724. const MutableCFOptions moptions(options);
  1725. c.Finish(options, ioptions, moptions, table_options, *comparator, &keys,
  1726. &kvmap);
  1727. auto reader = c.GetTableReader();
  1728. auto props = reader->GetTableProperties();
  1729. ASSERT_EQ(5u, props->num_data_blocks);
  1730. // TODO(Zhongyi): update test to use MutableCFOptions
  1731. std::unique_ptr<InternalIterator> index_iter(reader->NewIterator(
  1732. ReadOptions(), moptions.prefix_extractor.get(), /*arena=*/nullptr,
  1733. /*skip_filters=*/false, TableReaderCaller::kUncategorized));
  1734. // -- Find keys do not exist, but have common prefix.
  1735. std::vector<std::string> prefixes = {"001", "003", "005", "007", "009"};
  1736. std::vector<std::string> lower_bound = {keys[0], keys[1], keys[2],
  1737. keys[7], keys[9], };
  1738. // find the lower bound of the prefix
  1739. for (size_t i = 0; i < prefixes.size(); ++i) {
  1740. index_iter->Seek(InternalKey(prefixes[i], 0, kTypeValue).Encode());
  1741. ASSERT_OK(index_iter->status());
  1742. ASSERT_TRUE(index_iter->Valid());
  1743. // seek the first element in the block
  1744. ASSERT_EQ(lower_bound[i], index_iter->key().ToString());
  1745. ASSERT_EQ("v", index_iter->value().ToString());
  1746. }
  1747. // find the upper bound of prefixes
  1748. std::vector<std::string> upper_bound = {keys[1], keys[2], keys[7], keys[9], };
  1749. // find existing keys
  1750. for (const auto& item : kvmap) {
  1751. auto ukey = ExtractUserKey(item.first).ToString();
  1752. index_iter->Seek(ukey);
  1753. // ASSERT_OK(regular_iter->status());
  1754. ASSERT_OK(index_iter->status());
  1755. // ASSERT_TRUE(regular_iter->Valid());
  1756. ASSERT_TRUE(index_iter->Valid());
  1757. ASSERT_EQ(item.first, index_iter->key().ToString());
  1758. ASSERT_EQ(item.second, index_iter->value().ToString());
  1759. }
  1760. for (size_t i = 0; i < prefixes.size(); ++i) {
  1761. // the key is greater than any existing keys.
  1762. auto key = prefixes[i] + "9";
  1763. index_iter->Seek(InternalKey(key, 0, kTypeValue).Encode());
  1764. ASSERT_TRUE(index_iter->status().ok() || index_iter->status().IsNotFound());
  1765. ASSERT_TRUE(!index_iter->status().IsNotFound() || !index_iter->Valid());
  1766. if (i == prefixes.size() - 1) {
  1767. // last key
  1768. ASSERT_TRUE(!index_iter->Valid());
  1769. } else {
  1770. ASSERT_TRUE(index_iter->Valid());
  1771. // seek the first element in the block
  1772. ASSERT_EQ(upper_bound[i], index_iter->key().ToString());
  1773. ASSERT_EQ("v", index_iter->value().ToString());
  1774. }
  1775. }
  1776. // find keys with prefix that don't match any of the existing prefixes.
  1777. std::vector<std::string> non_exist_prefixes = {"002", "004", "006", "008"};
  1778. for (const auto& prefix : non_exist_prefixes) {
  1779. index_iter->Seek(InternalKey(prefix, 0, kTypeValue).Encode());
  1780. // regular_iter->Seek(prefix);
  1781. ASSERT_OK(index_iter->status());
  1782. // Seek to non-existing prefixes should yield either invalid, or a
  1783. // key with prefix greater than the target.
  1784. if (index_iter->Valid()) {
  1785. Slice ukey = ExtractUserKey(index_iter->key());
  1786. Slice ukey_prefix = options.prefix_extractor->Transform(ukey);
  1787. ASSERT_TRUE(BytewiseComparator()->Compare(prefix, ukey_prefix) < 0);
  1788. }
  1789. }
  1790. for (const auto& prefix : non_exist_prefixes) {
  1791. index_iter->SeekForPrev(InternalKey(prefix, 0, kTypeValue).Encode());
  1792. // regular_iter->Seek(prefix);
  1793. ASSERT_OK(index_iter->status());
  1794. // Seek to non-existing prefixes should yield either invalid, or a
  1795. // key with prefix greater than the target.
  1796. if (index_iter->Valid()) {
  1797. Slice ukey = ExtractUserKey(index_iter->key());
  1798. Slice ukey_prefix = options.prefix_extractor->Transform(ukey);
  1799. ASSERT_TRUE(BytewiseComparator()->Compare(prefix, ukey_prefix) > 0);
  1800. }
  1801. }
  1802. c.ResetTableReader();
  1803. }
  1804. TEST_P(BlockBasedTableTest, BinaryIndexTest) {
  1805. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1806. table_options.index_type = BlockBasedTableOptions::kBinarySearch;
  1807. IndexTest(table_options);
  1808. }
  1809. TEST_P(BlockBasedTableTest, HashIndexTest) {
  1810. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1811. table_options.index_type = BlockBasedTableOptions::kHashSearch;
  1812. IndexTest(table_options);
  1813. }
  1814. TEST_P(BlockBasedTableTest, PartitionIndexTest) {
  1815. const int max_index_keys = 5;
  1816. const int est_max_index_key_value_size = 32;
  1817. const int est_max_index_size = max_index_keys * est_max_index_key_value_size;
  1818. for (int i = 1; i <= est_max_index_size + 1; i++) {
  1819. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1820. table_options.index_type = BlockBasedTableOptions::kTwoLevelIndexSearch;
  1821. table_options.metadata_block_size = i;
  1822. IndexTest(table_options);
  1823. }
  1824. }
  1825. TEST_P(BlockBasedTableTest, IndexSeekOptimizationIncomplete) {
  1826. std::unique_ptr<InternalKeyComparator> comparator(
  1827. new InternalKeyComparator(BytewiseComparator()));
  1828. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1829. Options options;
  1830. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1831. const ImmutableCFOptions ioptions(options);
  1832. const MutableCFOptions moptions(options);
  1833. TableConstructor c(BytewiseComparator());
  1834. AddInternalKey(&c, "pika");
  1835. std::vector<std::string> keys;
  1836. stl_wrappers::KVMap kvmap;
  1837. c.Finish(options, ioptions, moptions, table_options, *comparator, &keys,
  1838. &kvmap);
  1839. ASSERT_EQ(1, keys.size());
  1840. auto reader = c.GetTableReader();
  1841. ReadOptions ropt;
  1842. ropt.read_tier = ReadTier::kBlockCacheTier;
  1843. std::unique_ptr<InternalIterator> iter(reader->NewIterator(
  1844. ropt, /*prefix_extractor=*/nullptr, /*arena=*/nullptr,
  1845. /*skip_filters=*/false, TableReaderCaller::kUncategorized));
  1846. auto ikey = [](Slice user_key) {
  1847. return InternalKey(user_key, 0, kTypeValue).Encode().ToString();
  1848. };
  1849. iter->Seek(ikey("pika"));
  1850. ASSERT_FALSE(iter->Valid());
  1851. ASSERT_TRUE(iter->status().IsIncomplete());
  1852. // This used to crash at some point.
  1853. iter->Seek(ikey("pika"));
  1854. ASSERT_FALSE(iter->Valid());
  1855. ASSERT_TRUE(iter->status().IsIncomplete());
  1856. }
  1857. TEST_P(BlockBasedTableTest, BinaryIndexWithFirstKey1) {
  1858. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1859. table_options.index_type = BlockBasedTableOptions::kBinarySearchWithFirstKey;
  1860. IndexTest(table_options);
  1861. }
  1862. class CustomFlushBlockPolicy : public FlushBlockPolicyFactory,
  1863. public FlushBlockPolicy {
  1864. public:
  1865. explicit CustomFlushBlockPolicy(std::vector<int> keys_per_block)
  1866. : keys_per_block_(keys_per_block) {}
  1867. const char* Name() const override { return "table_test"; }
  1868. FlushBlockPolicy* NewFlushBlockPolicy(const BlockBasedTableOptions&,
  1869. const BlockBuilder&) const override {
  1870. return new CustomFlushBlockPolicy(keys_per_block_);
  1871. }
  1872. bool Update(const Slice&, const Slice&) override {
  1873. if (keys_in_current_block_ >= keys_per_block_.at(current_block_idx_)) {
  1874. ++current_block_idx_;
  1875. keys_in_current_block_ = 1;
  1876. return true;
  1877. }
  1878. ++keys_in_current_block_;
  1879. return false;
  1880. }
  1881. std::vector<int> keys_per_block_;
  1882. int current_block_idx_ = 0;
  1883. int keys_in_current_block_ = 0;
  1884. };
  1885. TEST_P(BlockBasedTableTest, BinaryIndexWithFirstKey2) {
  1886. for (int use_first_key = 0; use_first_key < 2; ++use_first_key) {
  1887. SCOPED_TRACE("use_first_key = " + std::to_string(use_first_key));
  1888. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  1889. table_options.index_type =
  1890. use_first_key ? BlockBasedTableOptions::kBinarySearchWithFirstKey
  1891. : BlockBasedTableOptions::kBinarySearch;
  1892. table_options.block_cache = NewLRUCache(10000); // fits all blocks
  1893. table_options.index_shortening =
  1894. BlockBasedTableOptions::IndexShorteningMode::kNoShortening;
  1895. table_options.flush_block_policy_factory =
  1896. std::make_shared<CustomFlushBlockPolicy>(std::vector<int>{2, 1, 3, 2});
  1897. Options options;
  1898. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1899. options.statistics = CreateDBStatistics();
  1900. Statistics* stats = options.statistics.get();
  1901. std::unique_ptr<InternalKeyComparator> comparator(
  1902. new InternalKeyComparator(BytewiseComparator()));
  1903. const ImmutableCFOptions ioptions(options);
  1904. const MutableCFOptions moptions(options);
  1905. TableConstructor c(BytewiseComparator());
  1906. // Block 0.
  1907. AddInternalKey(&c, "aaaa", "v0");
  1908. AddInternalKey(&c, "aaac", "v1");
  1909. // Block 1.
  1910. AddInternalKey(&c, "aaca", "v2");
  1911. // Block 2.
  1912. AddInternalKey(&c, "caaa", "v3");
  1913. AddInternalKey(&c, "caac", "v4");
  1914. AddInternalKey(&c, "caae", "v5");
  1915. // Block 3.
  1916. AddInternalKey(&c, "ccaa", "v6");
  1917. AddInternalKey(&c, "ccac", "v7");
  1918. // Write the file.
  1919. std::vector<std::string> keys;
  1920. stl_wrappers::KVMap kvmap;
  1921. c.Finish(options, ioptions, moptions, table_options, *comparator, &keys,
  1922. &kvmap);
  1923. ASSERT_EQ(8, keys.size());
  1924. auto reader = c.GetTableReader();
  1925. auto props = reader->GetTableProperties();
  1926. ASSERT_EQ(4u, props->num_data_blocks);
  1927. std::unique_ptr<InternalIterator> iter(reader->NewIterator(
  1928. ReadOptions(), /*prefix_extractor=*/nullptr, /*arena=*/nullptr,
  1929. /*skip_filters=*/false, TableReaderCaller::kUncategorized));
  1930. // Shouldn't have read data blocks before iterator is seeked.
  1931. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  1932. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  1933. auto ikey = [](Slice user_key) {
  1934. return InternalKey(user_key, 0, kTypeValue).Encode().ToString();
  1935. };
  1936. // Seek to a key between blocks. If index contains first key, we shouldn't
  1937. // read any data blocks until value is requested.
  1938. iter->Seek(ikey("aaba"));
  1939. ASSERT_TRUE(iter->Valid());
  1940. EXPECT_EQ(keys[2], iter->key().ToString());
  1941. EXPECT_EQ(use_first_key ? 0 : 1,
  1942. stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  1943. EXPECT_EQ("v2", iter->value().ToString());
  1944. EXPECT_EQ(1, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  1945. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  1946. // Seek to the middle of a block. The block should be read right away.
  1947. iter->Seek(ikey("caab"));
  1948. ASSERT_TRUE(iter->Valid());
  1949. EXPECT_EQ(keys[4], iter->key().ToString());
  1950. EXPECT_EQ(2, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  1951. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  1952. EXPECT_EQ("v4", iter->value().ToString());
  1953. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  1954. // Seek to just before the same block and don't access value.
  1955. // The iterator should keep pinning the block contents.
  1956. iter->Seek(ikey("baaa"));
  1957. ASSERT_TRUE(iter->Valid());
  1958. EXPECT_EQ(keys[3], iter->key().ToString());
  1959. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  1960. // Seek to the same block again to check that the block is still pinned.
  1961. iter->Seek(ikey("caae"));
  1962. ASSERT_TRUE(iter->Valid());
  1963. EXPECT_EQ(keys[5], iter->key().ToString());
  1964. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  1965. EXPECT_EQ("v5", iter->value().ToString());
  1966. EXPECT_EQ(2, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  1967. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  1968. // Step forward and fall through to the next block. Don't access value.
  1969. iter->Next();
  1970. ASSERT_TRUE(iter->Valid());
  1971. EXPECT_EQ(keys[6], iter->key().ToString());
  1972. EXPECT_EQ(use_first_key ? 2 : 3,
  1973. stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  1974. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  1975. // Step forward again. Block should be read.
  1976. iter->Next();
  1977. ASSERT_TRUE(iter->Valid());
  1978. EXPECT_EQ(keys[7], iter->key().ToString());
  1979. EXPECT_EQ(3, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  1980. EXPECT_EQ("v7", iter->value().ToString());
  1981. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  1982. // Step forward and reach the end.
  1983. iter->Next();
  1984. EXPECT_FALSE(iter->Valid());
  1985. EXPECT_EQ(3, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  1986. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  1987. // Seek to a single-key block and step forward without accessing value.
  1988. iter->Seek(ikey("aaca"));
  1989. ASSERT_TRUE(iter->Valid());
  1990. EXPECT_EQ(keys[2], iter->key().ToString());
  1991. EXPECT_EQ(use_first_key ? 0 : 1,
  1992. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  1993. iter->Next();
  1994. ASSERT_TRUE(iter->Valid());
  1995. EXPECT_EQ(keys[3], iter->key().ToString());
  1996. EXPECT_EQ(use_first_key ? 1 : 2,
  1997. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  1998. EXPECT_EQ("v3", iter->value().ToString());
  1999. EXPECT_EQ(2, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2000. EXPECT_EQ(3, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  2001. // Seek between blocks and step back without accessing value.
  2002. iter->Seek(ikey("aaca"));
  2003. ASSERT_TRUE(iter->Valid());
  2004. EXPECT_EQ(keys[2], iter->key().ToString());
  2005. EXPECT_EQ(use_first_key ? 2 : 3,
  2006. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2007. EXPECT_EQ(3, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  2008. iter->Prev();
  2009. ASSERT_TRUE(iter->Valid());
  2010. EXPECT_EQ(keys[1], iter->key().ToString());
  2011. EXPECT_EQ(use_first_key ? 2 : 3,
  2012. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2013. // All blocks are in cache now, there'll be no more misses ever.
  2014. EXPECT_EQ(4, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  2015. EXPECT_EQ("v1", iter->value().ToString());
  2016. // Next into the next block again.
  2017. iter->Next();
  2018. ASSERT_TRUE(iter->Valid());
  2019. EXPECT_EQ(keys[2], iter->key().ToString());
  2020. EXPECT_EQ(use_first_key ? 2 : 4,
  2021. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2022. // Seek to first and step back without accessing value.
  2023. iter->SeekToFirst();
  2024. ASSERT_TRUE(iter->Valid());
  2025. EXPECT_EQ(keys[0], iter->key().ToString());
  2026. EXPECT_EQ(use_first_key ? 2 : 5,
  2027. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2028. iter->Prev();
  2029. EXPECT_FALSE(iter->Valid());
  2030. EXPECT_EQ(use_first_key ? 2 : 5,
  2031. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2032. // Do some SeekForPrev() and SeekToLast() just to cover all methods.
  2033. iter->SeekForPrev(ikey("caad"));
  2034. ASSERT_TRUE(iter->Valid());
  2035. EXPECT_EQ(keys[4], iter->key().ToString());
  2036. EXPECT_EQ(use_first_key ? 3 : 6,
  2037. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2038. EXPECT_EQ("v4", iter->value().ToString());
  2039. EXPECT_EQ(use_first_key ? 3 : 6,
  2040. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2041. iter->SeekToLast();
  2042. ASSERT_TRUE(iter->Valid());
  2043. EXPECT_EQ(keys[7], iter->key().ToString());
  2044. EXPECT_EQ(use_first_key ? 4 : 7,
  2045. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2046. EXPECT_EQ("v7", iter->value().ToString());
  2047. EXPECT_EQ(use_first_key ? 4 : 7,
  2048. stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2049. EXPECT_EQ(4, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  2050. c.ResetTableReader();
  2051. }
  2052. }
  2053. TEST_P(BlockBasedTableTest, BinaryIndexWithFirstKeyGlobalSeqno) {
  2054. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2055. table_options.index_type = BlockBasedTableOptions::kBinarySearchWithFirstKey;
  2056. table_options.block_cache = NewLRUCache(10000);
  2057. Options options;
  2058. options.statistics = CreateDBStatistics();
  2059. Statistics* stats = options.statistics.get();
  2060. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2061. std::unique_ptr<InternalKeyComparator> comparator(
  2062. new InternalKeyComparator(BytewiseComparator()));
  2063. const ImmutableCFOptions ioptions(options);
  2064. const MutableCFOptions moptions(options);
  2065. TableConstructor c(BytewiseComparator(), /* convert_to_internal_key */ false,
  2066. /* level */ -1, /* largest_seqno */ 42);
  2067. c.Add(InternalKey("b", 0, kTypeValue).Encode().ToString(), "x");
  2068. c.Add(InternalKey("c", 0, kTypeValue).Encode().ToString(), "y");
  2069. std::vector<std::string> keys;
  2070. stl_wrappers::KVMap kvmap;
  2071. c.Finish(options, ioptions, moptions, table_options, *comparator, &keys,
  2072. &kvmap);
  2073. ASSERT_EQ(2, keys.size());
  2074. auto reader = c.GetTableReader();
  2075. auto props = reader->GetTableProperties();
  2076. ASSERT_EQ(1u, props->num_data_blocks);
  2077. std::unique_ptr<InternalIterator> iter(reader->NewIterator(
  2078. ReadOptions(), /*prefix_extractor=*/nullptr, /*arena=*/nullptr,
  2079. /*skip_filters=*/false, TableReaderCaller::kUncategorized));
  2080. iter->Seek(InternalKey("a", 0, kTypeValue).Encode().ToString());
  2081. ASSERT_TRUE(iter->Valid());
  2082. EXPECT_EQ(InternalKey("b", 42, kTypeValue).Encode().ToString(),
  2083. iter->key().ToString());
  2084. EXPECT_NE(keys[0], iter->key().ToString());
  2085. // Key should have been served from index, without reading data blocks.
  2086. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  2087. EXPECT_EQ("x", iter->value().ToString());
  2088. EXPECT_EQ(1, stats->getTickerCount(BLOCK_CACHE_DATA_MISS));
  2089. EXPECT_EQ(0, stats->getTickerCount(BLOCK_CACHE_DATA_HIT));
  2090. EXPECT_EQ(InternalKey("b", 42, kTypeValue).Encode().ToString(),
  2091. iter->key().ToString());
  2092. c.ResetTableReader();
  2093. }
  2094. // It's very hard to figure out the index block size of a block accurately.
  2095. // To make sure we get the index size, we just make sure as key number
  2096. // grows, the filter block size also grows.
  2097. TEST_P(BlockBasedTableTest, IndexSizeStat) {
  2098. uint64_t last_index_size = 0;
  2099. // we need to use random keys since the pure human readable texts
  2100. // may be well compressed, resulting insignifcant change of index
  2101. // block size.
  2102. Random rnd(test::RandomSeed());
  2103. std::vector<std::string> keys;
  2104. for (int i = 0; i < 100; ++i) {
  2105. keys.push_back(RandomString(&rnd, 10000));
  2106. }
  2107. // Each time we load one more key to the table. the table index block
  2108. // size is expected to be larger than last time's.
  2109. for (size_t i = 1; i < keys.size(); ++i) {
  2110. TableConstructor c(BytewiseComparator(),
  2111. true /* convert_to_internal_key_ */);
  2112. for (size_t j = 0; j < i; ++j) {
  2113. c.Add(keys[j], "val");
  2114. }
  2115. std::vector<std::string> ks;
  2116. stl_wrappers::KVMap kvmap;
  2117. Options options;
  2118. options.compression = kNoCompression;
  2119. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2120. table_options.block_restart_interval = 1;
  2121. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2122. const ImmutableCFOptions ioptions(options);
  2123. const MutableCFOptions moptions(options);
  2124. c.Finish(options, ioptions, moptions, table_options,
  2125. GetPlainInternalComparator(options.comparator), &ks, &kvmap);
  2126. auto index_size = c.GetTableReader()->GetTableProperties()->index_size;
  2127. ASSERT_GT(index_size, last_index_size);
  2128. last_index_size = index_size;
  2129. c.ResetTableReader();
  2130. }
  2131. }
  2132. TEST_P(BlockBasedTableTest, NumBlockStat) {
  2133. Random rnd(test::RandomSeed());
  2134. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  2135. Options options;
  2136. options.compression = kNoCompression;
  2137. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2138. table_options.block_restart_interval = 1;
  2139. table_options.block_size = 1000;
  2140. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2141. for (int i = 0; i < 10; ++i) {
  2142. // the key/val are slightly smaller than block size, so that each block
  2143. // holds roughly one key/value pair.
  2144. c.Add(RandomString(&rnd, 900), "val");
  2145. }
  2146. std::vector<std::string> ks;
  2147. stl_wrappers::KVMap kvmap;
  2148. const ImmutableCFOptions ioptions(options);
  2149. const MutableCFOptions moptions(options);
  2150. c.Finish(options, ioptions, moptions, table_options,
  2151. GetPlainInternalComparator(options.comparator), &ks, &kvmap);
  2152. ASSERT_EQ(kvmap.size(),
  2153. c.GetTableReader()->GetTableProperties()->num_data_blocks);
  2154. c.ResetTableReader();
  2155. }
  2156. TEST_P(BlockBasedTableTest, TracingGetTest) {
  2157. TableConstructor c(BytewiseComparator());
  2158. Options options;
  2159. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2160. options.create_if_missing = true;
  2161. table_options.block_cache = NewLRUCache(1024 * 1024, 0);
  2162. table_options.cache_index_and_filter_blocks = true;
  2163. table_options.filter_policy.reset(NewBloomFilterPolicy(10, true));
  2164. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  2165. SetupTracingTest(&c);
  2166. std::vector<std::string> keys;
  2167. stl_wrappers::KVMap kvmap;
  2168. ImmutableCFOptions ioptions(options);
  2169. MutableCFOptions moptions(options);
  2170. c.Finish(options, ioptions, moptions, table_options,
  2171. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  2172. std::string user_key = "k01";
  2173. InternalKey internal_key(user_key, 0, kTypeValue);
  2174. std::string encoded_key = internal_key.Encode().ToString();
  2175. for (uint32_t i = 1; i <= 2; i++) {
  2176. PinnableSlice value;
  2177. GetContext get_context(options.comparator, nullptr, nullptr, nullptr,
  2178. GetContext::kNotFound, user_key, &value, nullptr,
  2179. nullptr, true, nullptr, nullptr, nullptr, nullptr,
  2180. nullptr, nullptr, /*tracing_get_id=*/i);
  2181. get_perf_context()->Reset();
  2182. ASSERT_OK(c.GetTableReader()->Get(ReadOptions(), encoded_key, &get_context,
  2183. moptions.prefix_extractor.get()));
  2184. ASSERT_EQ(get_context.State(), GetContext::kFound);
  2185. ASSERT_EQ(value.ToString(), kDummyValue);
  2186. }
  2187. // Verify traces.
  2188. std::vector<BlockCacheTraceRecord> expected_records;
  2189. // The first two records should be prefetching index and filter blocks.
  2190. BlockCacheTraceRecord record;
  2191. record.block_type = TraceType::kBlockTraceIndexBlock;
  2192. record.caller = TableReaderCaller::kPrefetch;
  2193. record.is_cache_hit = Boolean::kFalse;
  2194. record.no_insert = Boolean::kFalse;
  2195. expected_records.push_back(record);
  2196. record.block_type = TraceType::kBlockTraceFilterBlock;
  2197. expected_records.push_back(record);
  2198. // Then we should have three records for one index, one filter, and one data
  2199. // block access.
  2200. record.get_id = 1;
  2201. record.block_type = TraceType::kBlockTraceIndexBlock;
  2202. record.caller = TableReaderCaller::kUserGet;
  2203. record.get_from_user_specified_snapshot = Boolean::kFalse;
  2204. record.referenced_key = encoded_key;
  2205. record.referenced_key_exist_in_block = Boolean::kTrue;
  2206. record.is_cache_hit = Boolean::kTrue;
  2207. expected_records.push_back(record);
  2208. record.block_type = TraceType::kBlockTraceFilterBlock;
  2209. expected_records.push_back(record);
  2210. record.is_cache_hit = Boolean::kFalse;
  2211. record.block_type = TraceType::kBlockTraceDataBlock;
  2212. expected_records.push_back(record);
  2213. // The second get should all observe cache hits.
  2214. record.is_cache_hit = Boolean::kTrue;
  2215. record.get_id = 2;
  2216. record.block_type = TraceType::kBlockTraceIndexBlock;
  2217. record.caller = TableReaderCaller::kUserGet;
  2218. record.get_from_user_specified_snapshot = Boolean::kFalse;
  2219. record.referenced_key = encoded_key;
  2220. expected_records.push_back(record);
  2221. record.block_type = TraceType::kBlockTraceFilterBlock;
  2222. expected_records.push_back(record);
  2223. record.block_type = TraceType::kBlockTraceDataBlock;
  2224. expected_records.push_back(record);
  2225. VerifyBlockAccessTrace(&c, expected_records);
  2226. c.ResetTableReader();
  2227. }
  2228. TEST_P(BlockBasedTableTest, TracingApproximateOffsetOfTest) {
  2229. TableConstructor c(BytewiseComparator());
  2230. Options options;
  2231. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2232. options.create_if_missing = true;
  2233. table_options.block_cache = NewLRUCache(1024 * 1024, 0);
  2234. table_options.cache_index_and_filter_blocks = true;
  2235. table_options.filter_policy.reset(NewBloomFilterPolicy(10, true));
  2236. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  2237. SetupTracingTest(&c);
  2238. std::vector<std::string> keys;
  2239. stl_wrappers::KVMap kvmap;
  2240. ImmutableCFOptions ioptions(options);
  2241. MutableCFOptions moptions(options);
  2242. c.Finish(options, ioptions, moptions, table_options,
  2243. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  2244. for (uint32_t i = 1; i <= 2; i++) {
  2245. std::string user_key = "k01";
  2246. InternalKey internal_key(user_key, 0, kTypeValue);
  2247. std::string encoded_key = internal_key.Encode().ToString();
  2248. c.GetTableReader()->ApproximateOffsetOf(
  2249. encoded_key, TableReaderCaller::kUserApproximateSize);
  2250. }
  2251. // Verify traces.
  2252. std::vector<BlockCacheTraceRecord> expected_records;
  2253. // The first two records should be prefetching index and filter blocks.
  2254. BlockCacheTraceRecord record;
  2255. record.block_type = TraceType::kBlockTraceIndexBlock;
  2256. record.caller = TableReaderCaller::kPrefetch;
  2257. record.is_cache_hit = Boolean::kFalse;
  2258. record.no_insert = Boolean::kFalse;
  2259. expected_records.push_back(record);
  2260. record.block_type = TraceType::kBlockTraceFilterBlock;
  2261. expected_records.push_back(record);
  2262. // Then we should have two records for only index blocks.
  2263. record.block_type = TraceType::kBlockTraceIndexBlock;
  2264. record.caller = TableReaderCaller::kUserApproximateSize;
  2265. record.is_cache_hit = Boolean::kTrue;
  2266. expected_records.push_back(record);
  2267. expected_records.push_back(record);
  2268. VerifyBlockAccessTrace(&c, expected_records);
  2269. c.ResetTableReader();
  2270. }
  2271. TEST_P(BlockBasedTableTest, TracingIterator) {
  2272. TableConstructor c(BytewiseComparator());
  2273. Options options;
  2274. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2275. options.create_if_missing = true;
  2276. table_options.block_cache = NewLRUCache(1024 * 1024, 0);
  2277. table_options.cache_index_and_filter_blocks = true;
  2278. table_options.filter_policy.reset(NewBloomFilterPolicy(10, true));
  2279. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  2280. SetupTracingTest(&c);
  2281. std::vector<std::string> keys;
  2282. stl_wrappers::KVMap kvmap;
  2283. ImmutableCFOptions ioptions(options);
  2284. MutableCFOptions moptions(options);
  2285. c.Finish(options, ioptions, moptions, table_options,
  2286. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  2287. for (uint32_t i = 1; i <= 2; i++) {
  2288. std::unique_ptr<InternalIterator> iter(c.GetTableReader()->NewIterator(
  2289. ReadOptions(), moptions.prefix_extractor.get(), /*arena=*/nullptr,
  2290. /*skip_filters=*/false, TableReaderCaller::kUserIterator));
  2291. iter->SeekToFirst();
  2292. while (iter->Valid()) {
  2293. iter->key();
  2294. iter->value();
  2295. iter->Next();
  2296. }
  2297. ASSERT_OK(iter->status());
  2298. iter.reset();
  2299. }
  2300. // Verify traces.
  2301. std::vector<BlockCacheTraceRecord> expected_records;
  2302. // The first two records should be prefetching index and filter blocks.
  2303. BlockCacheTraceRecord record;
  2304. record.block_type = TraceType::kBlockTraceIndexBlock;
  2305. record.caller = TableReaderCaller::kPrefetch;
  2306. record.is_cache_hit = Boolean::kFalse;
  2307. record.no_insert = Boolean::kFalse;
  2308. expected_records.push_back(record);
  2309. record.block_type = TraceType::kBlockTraceFilterBlock;
  2310. expected_records.push_back(record);
  2311. // Then we should have three records for index and two data block access.
  2312. record.block_type = TraceType::kBlockTraceIndexBlock;
  2313. record.caller = TableReaderCaller::kUserIterator;
  2314. record.is_cache_hit = Boolean::kTrue;
  2315. expected_records.push_back(record);
  2316. record.block_type = TraceType::kBlockTraceDataBlock;
  2317. record.is_cache_hit = Boolean::kFalse;
  2318. expected_records.push_back(record);
  2319. expected_records.push_back(record);
  2320. // When we iterate this file for the second time, we should observe all cache
  2321. // hits.
  2322. record.block_type = TraceType::kBlockTraceIndexBlock;
  2323. record.is_cache_hit = Boolean::kTrue;
  2324. expected_records.push_back(record);
  2325. record.block_type = TraceType::kBlockTraceDataBlock;
  2326. expected_records.push_back(record);
  2327. expected_records.push_back(record);
  2328. VerifyBlockAccessTrace(&c, expected_records);
  2329. c.ResetTableReader();
  2330. }
  2331. // A simple tool that takes the snapshot of block cache statistics.
  2332. class BlockCachePropertiesSnapshot {
  2333. public:
  2334. explicit BlockCachePropertiesSnapshot(Statistics* statistics) {
  2335. block_cache_miss = statistics->getTickerCount(BLOCK_CACHE_MISS);
  2336. block_cache_hit = statistics->getTickerCount(BLOCK_CACHE_HIT);
  2337. index_block_cache_miss = statistics->getTickerCount(BLOCK_CACHE_INDEX_MISS);
  2338. index_block_cache_hit = statistics->getTickerCount(BLOCK_CACHE_INDEX_HIT);
  2339. data_block_cache_miss = statistics->getTickerCount(BLOCK_CACHE_DATA_MISS);
  2340. data_block_cache_hit = statistics->getTickerCount(BLOCK_CACHE_DATA_HIT);
  2341. filter_block_cache_miss =
  2342. statistics->getTickerCount(BLOCK_CACHE_FILTER_MISS);
  2343. filter_block_cache_hit = statistics->getTickerCount(BLOCK_CACHE_FILTER_HIT);
  2344. block_cache_bytes_read = statistics->getTickerCount(BLOCK_CACHE_BYTES_READ);
  2345. block_cache_bytes_write =
  2346. statistics->getTickerCount(BLOCK_CACHE_BYTES_WRITE);
  2347. }
  2348. void AssertIndexBlockStat(int64_t expected_index_block_cache_miss,
  2349. int64_t expected_index_block_cache_hit) {
  2350. ASSERT_EQ(expected_index_block_cache_miss, index_block_cache_miss);
  2351. ASSERT_EQ(expected_index_block_cache_hit, index_block_cache_hit);
  2352. }
  2353. void AssertFilterBlockStat(int64_t expected_filter_block_cache_miss,
  2354. int64_t expected_filter_block_cache_hit) {
  2355. ASSERT_EQ(expected_filter_block_cache_miss, filter_block_cache_miss);
  2356. ASSERT_EQ(expected_filter_block_cache_hit, filter_block_cache_hit);
  2357. }
  2358. // Check if the fetched props matches the expected ones.
  2359. // TODO(kailiu) Use this only when you disabled filter policy!
  2360. void AssertEqual(int64_t expected_index_block_cache_miss,
  2361. int64_t expected_index_block_cache_hit,
  2362. int64_t expected_data_block_cache_miss,
  2363. int64_t expected_data_block_cache_hit) const {
  2364. ASSERT_EQ(expected_index_block_cache_miss, index_block_cache_miss);
  2365. ASSERT_EQ(expected_index_block_cache_hit, index_block_cache_hit);
  2366. ASSERT_EQ(expected_data_block_cache_miss, data_block_cache_miss);
  2367. ASSERT_EQ(expected_data_block_cache_hit, data_block_cache_hit);
  2368. ASSERT_EQ(expected_index_block_cache_miss + expected_data_block_cache_miss,
  2369. block_cache_miss);
  2370. ASSERT_EQ(expected_index_block_cache_hit + expected_data_block_cache_hit,
  2371. block_cache_hit);
  2372. }
  2373. int64_t GetCacheBytesRead() { return block_cache_bytes_read; }
  2374. int64_t GetCacheBytesWrite() { return block_cache_bytes_write; }
  2375. private:
  2376. int64_t block_cache_miss = 0;
  2377. int64_t block_cache_hit = 0;
  2378. int64_t index_block_cache_miss = 0;
  2379. int64_t index_block_cache_hit = 0;
  2380. int64_t data_block_cache_miss = 0;
  2381. int64_t data_block_cache_hit = 0;
  2382. int64_t filter_block_cache_miss = 0;
  2383. int64_t filter_block_cache_hit = 0;
  2384. int64_t block_cache_bytes_read = 0;
  2385. int64_t block_cache_bytes_write = 0;
  2386. };
  2387. // Make sure, by default, index/filter blocks were pre-loaded (meaning we won't
  2388. // use block cache to store them).
  2389. TEST_P(BlockBasedTableTest, BlockCacheDisabledTest) {
  2390. Options options;
  2391. options.create_if_missing = true;
  2392. options.statistics = CreateDBStatistics();
  2393. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2394. table_options.block_cache = NewLRUCache(1024, 4);
  2395. table_options.filter_policy.reset(NewBloomFilterPolicy(10));
  2396. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  2397. std::vector<std::string> keys;
  2398. stl_wrappers::KVMap kvmap;
  2399. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  2400. c.Add("key", "value");
  2401. const ImmutableCFOptions ioptions(options);
  2402. const MutableCFOptions moptions(options);
  2403. c.Finish(options, ioptions, moptions, table_options,
  2404. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  2405. // preloading filter/index blocks is enabled.
  2406. auto reader = dynamic_cast<BlockBasedTable*>(c.GetTableReader());
  2407. ASSERT_FALSE(reader->TEST_FilterBlockInCache());
  2408. ASSERT_FALSE(reader->TEST_IndexBlockInCache());
  2409. {
  2410. // nothing happens in the beginning
  2411. BlockCachePropertiesSnapshot props(options.statistics.get());
  2412. props.AssertIndexBlockStat(0, 0);
  2413. props.AssertFilterBlockStat(0, 0);
  2414. }
  2415. {
  2416. GetContext get_context(options.comparator, nullptr, nullptr, nullptr,
  2417. GetContext::kNotFound, Slice(), nullptr, nullptr,
  2418. nullptr, true, nullptr, nullptr);
  2419. // a hack that just to trigger BlockBasedTable::GetFilter.
  2420. reader->Get(ReadOptions(), "non-exist-key", &get_context,
  2421. moptions.prefix_extractor.get());
  2422. BlockCachePropertiesSnapshot props(options.statistics.get());
  2423. props.AssertIndexBlockStat(0, 0);
  2424. props.AssertFilterBlockStat(0, 0);
  2425. }
  2426. }
  2427. // Due to the difficulities of the intersaction between statistics, this test
  2428. // only tests the case when "index block is put to block cache"
  2429. TEST_P(BlockBasedTableTest, FilterBlockInBlockCache) {
  2430. // -- Table construction
  2431. Options options;
  2432. options.create_if_missing = true;
  2433. options.statistics = CreateDBStatistics();
  2434. // Enable the cache for index/filter blocks
  2435. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2436. LRUCacheOptions co;
  2437. co.capacity = 2048;
  2438. co.num_shard_bits = 2;
  2439. co.metadata_charge_policy = kDontChargeCacheMetadata;
  2440. table_options.block_cache = NewLRUCache(co);
  2441. table_options.cache_index_and_filter_blocks = true;
  2442. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  2443. std::vector<std::string> keys;
  2444. stl_wrappers::KVMap kvmap;
  2445. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  2446. c.Add("key", "value");
  2447. const ImmutableCFOptions ioptions(options);
  2448. const MutableCFOptions moptions(options);
  2449. c.Finish(options, ioptions, moptions, table_options,
  2450. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  2451. // preloading filter/index blocks is prohibited.
  2452. auto* reader = dynamic_cast<BlockBasedTable*>(c.GetTableReader());
  2453. ASSERT_FALSE(reader->TEST_FilterBlockInCache());
  2454. ASSERT_TRUE(reader->TEST_IndexBlockInCache());
  2455. // -- PART 1: Open with regular block cache.
  2456. // Since block_cache is disabled, no cache activities will be involved.
  2457. std::unique_ptr<InternalIterator> iter;
  2458. int64_t last_cache_bytes_read = 0;
  2459. // At first, no block will be accessed.
  2460. {
  2461. BlockCachePropertiesSnapshot props(options.statistics.get());
  2462. // index will be added to block cache.
  2463. props.AssertEqual(1, // index block miss
  2464. 0, 0, 0);
  2465. ASSERT_EQ(props.GetCacheBytesRead(), 0);
  2466. ASSERT_EQ(props.GetCacheBytesWrite(),
  2467. static_cast<int64_t>(table_options.block_cache->GetUsage()));
  2468. last_cache_bytes_read = props.GetCacheBytesRead();
  2469. }
  2470. // Only index block will be accessed
  2471. {
  2472. iter.reset(c.NewIterator(moptions.prefix_extractor.get()));
  2473. BlockCachePropertiesSnapshot props(options.statistics.get());
  2474. // NOTE: to help better highlight the "detla" of each ticker, I use
  2475. // <last_value> + <added_value> to indicate the increment of changed
  2476. // value; other numbers remain the same.
  2477. props.AssertEqual(1, 0 + 1, // index block hit
  2478. 0, 0);
  2479. // Cache hit, bytes read from cache should increase
  2480. ASSERT_GT(props.GetCacheBytesRead(), last_cache_bytes_read);
  2481. ASSERT_EQ(props.GetCacheBytesWrite(),
  2482. static_cast<int64_t>(table_options.block_cache->GetUsage()));
  2483. last_cache_bytes_read = props.GetCacheBytesRead();
  2484. }
  2485. // Only data block will be accessed
  2486. {
  2487. iter->SeekToFirst();
  2488. BlockCachePropertiesSnapshot props(options.statistics.get());
  2489. props.AssertEqual(1, 1, 0 + 1, // data block miss
  2490. 0);
  2491. // Cache miss, Bytes read from cache should not change
  2492. ASSERT_EQ(props.GetCacheBytesRead(), last_cache_bytes_read);
  2493. ASSERT_EQ(props.GetCacheBytesWrite(),
  2494. static_cast<int64_t>(table_options.block_cache->GetUsage()));
  2495. last_cache_bytes_read = props.GetCacheBytesRead();
  2496. }
  2497. // Data block will be in cache
  2498. {
  2499. iter.reset(c.NewIterator(moptions.prefix_extractor.get()));
  2500. iter->SeekToFirst();
  2501. BlockCachePropertiesSnapshot props(options.statistics.get());
  2502. props.AssertEqual(1, 1 + 1, /* index block hit */
  2503. 1, 0 + 1 /* data block hit */);
  2504. // Cache hit, bytes read from cache should increase
  2505. ASSERT_GT(props.GetCacheBytesRead(), last_cache_bytes_read);
  2506. ASSERT_EQ(props.GetCacheBytesWrite(),
  2507. static_cast<int64_t>(table_options.block_cache->GetUsage()));
  2508. }
  2509. // release the iterator so that the block cache can reset correctly.
  2510. iter.reset();
  2511. c.ResetTableReader();
  2512. // -- PART 2: Open with very small block cache
  2513. // In this test, no block will ever get hit since the block cache is
  2514. // too small to fit even one entry.
  2515. table_options.block_cache = NewLRUCache(1, 4);
  2516. options.statistics = CreateDBStatistics();
  2517. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  2518. const ImmutableCFOptions ioptions2(options);
  2519. const MutableCFOptions moptions2(options);
  2520. c.Reopen(ioptions2, moptions2);
  2521. {
  2522. BlockCachePropertiesSnapshot props(options.statistics.get());
  2523. props.AssertEqual(1, // index block miss
  2524. 0, 0, 0);
  2525. // Cache miss, Bytes read from cache should not change
  2526. ASSERT_EQ(props.GetCacheBytesRead(), 0);
  2527. }
  2528. {
  2529. // Both index and data block get accessed.
  2530. // It first cache index block then data block. But since the cache size
  2531. // is only 1, index block will be purged after data block is inserted.
  2532. iter.reset(c.NewIterator(moptions2.prefix_extractor.get()));
  2533. BlockCachePropertiesSnapshot props(options.statistics.get());
  2534. props.AssertEqual(1 + 1, // index block miss
  2535. 0, 0, // data block miss
  2536. 0);
  2537. // Cache hit, bytes read from cache should increase
  2538. ASSERT_EQ(props.GetCacheBytesRead(), 0);
  2539. }
  2540. {
  2541. // SeekToFirst() accesses data block. With similar reason, we expect data
  2542. // block's cache miss.
  2543. iter->SeekToFirst();
  2544. BlockCachePropertiesSnapshot props(options.statistics.get());
  2545. props.AssertEqual(2, 0, 0 + 1, // data block miss
  2546. 0);
  2547. // Cache miss, Bytes read from cache should not change
  2548. ASSERT_EQ(props.GetCacheBytesRead(), 0);
  2549. }
  2550. iter.reset();
  2551. c.ResetTableReader();
  2552. // -- PART 3: Open table with bloom filter enabled but not in SST file
  2553. table_options.block_cache = NewLRUCache(4096, 4);
  2554. table_options.cache_index_and_filter_blocks = false;
  2555. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2556. TableConstructor c3(BytewiseComparator());
  2557. std::string user_key = "k01";
  2558. InternalKey internal_key(user_key, 0, kTypeValue);
  2559. c3.Add(internal_key.Encode().ToString(), "hello");
  2560. ImmutableCFOptions ioptions3(options);
  2561. MutableCFOptions moptions3(options);
  2562. // Generate table without filter policy
  2563. c3.Finish(options, ioptions3, moptions3, table_options,
  2564. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  2565. c3.ResetTableReader();
  2566. // Open table with filter policy
  2567. table_options.filter_policy.reset(NewBloomFilterPolicy(1));
  2568. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  2569. options.statistics = CreateDBStatistics();
  2570. ImmutableCFOptions ioptions4(options);
  2571. MutableCFOptions moptions4(options);
  2572. ASSERT_OK(c3.Reopen(ioptions4, moptions4));
  2573. reader = dynamic_cast<BlockBasedTable*>(c3.GetTableReader());
  2574. ASSERT_FALSE(reader->TEST_FilterBlockInCache());
  2575. PinnableSlice value;
  2576. GetContext get_context(options.comparator, nullptr, nullptr, nullptr,
  2577. GetContext::kNotFound, user_key, &value, nullptr,
  2578. nullptr, true, nullptr, nullptr);
  2579. ASSERT_OK(reader->Get(ReadOptions(), internal_key.Encode(), &get_context,
  2580. moptions4.prefix_extractor.get()));
  2581. ASSERT_STREQ(value.data(), "hello");
  2582. BlockCachePropertiesSnapshot props(options.statistics.get());
  2583. props.AssertFilterBlockStat(0, 0);
  2584. c3.ResetTableReader();
  2585. }
  2586. void ValidateBlockSizeDeviation(int value, int expected) {
  2587. BlockBasedTableOptions table_options;
  2588. table_options.block_size_deviation = value;
  2589. BlockBasedTableFactory* factory = new BlockBasedTableFactory(table_options);
  2590. const BlockBasedTableOptions* normalized_table_options =
  2591. (const BlockBasedTableOptions*)factory->GetOptions();
  2592. ASSERT_EQ(normalized_table_options->block_size_deviation, expected);
  2593. delete factory;
  2594. }
  2595. void ValidateBlockRestartInterval(int value, int expected) {
  2596. BlockBasedTableOptions table_options;
  2597. table_options.block_restart_interval = value;
  2598. BlockBasedTableFactory* factory = new BlockBasedTableFactory(table_options);
  2599. const BlockBasedTableOptions* normalized_table_options =
  2600. (const BlockBasedTableOptions*)factory->GetOptions();
  2601. ASSERT_EQ(normalized_table_options->block_restart_interval, expected);
  2602. delete factory;
  2603. }
  2604. TEST_P(BlockBasedTableTest, InvalidOptions) {
  2605. // invalid values for block_size_deviation (<0 or >100) are silently set to 0
  2606. ValidateBlockSizeDeviation(-10, 0);
  2607. ValidateBlockSizeDeviation(-1, 0);
  2608. ValidateBlockSizeDeviation(0, 0);
  2609. ValidateBlockSizeDeviation(1, 1);
  2610. ValidateBlockSizeDeviation(99, 99);
  2611. ValidateBlockSizeDeviation(100, 100);
  2612. ValidateBlockSizeDeviation(101, 0);
  2613. ValidateBlockSizeDeviation(1000, 0);
  2614. // invalid values for block_restart_interval (<1) are silently set to 1
  2615. ValidateBlockRestartInterval(-10, 1);
  2616. ValidateBlockRestartInterval(-1, 1);
  2617. ValidateBlockRestartInterval(0, 1);
  2618. ValidateBlockRestartInterval(1, 1);
  2619. ValidateBlockRestartInterval(2, 2);
  2620. ValidateBlockRestartInterval(1000, 1000);
  2621. }
  2622. TEST_P(BlockBasedTableTest, BlockReadCountTest) {
  2623. // bloom_filter_type = 0 -- block-based filter
  2624. // bloom_filter_type = 0 -- full filter
  2625. for (int bloom_filter_type = 0; bloom_filter_type < 2; ++bloom_filter_type) {
  2626. for (int index_and_filter_in_cache = 0; index_and_filter_in_cache < 2;
  2627. ++index_and_filter_in_cache) {
  2628. Options options;
  2629. options.create_if_missing = true;
  2630. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2631. table_options.block_cache = NewLRUCache(1, 0);
  2632. table_options.cache_index_and_filter_blocks = index_and_filter_in_cache;
  2633. table_options.filter_policy.reset(
  2634. NewBloomFilterPolicy(10, bloom_filter_type == 0));
  2635. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  2636. std::vector<std::string> keys;
  2637. stl_wrappers::KVMap kvmap;
  2638. TableConstructor c(BytewiseComparator());
  2639. std::string user_key = "k04";
  2640. InternalKey internal_key(user_key, 0, kTypeValue);
  2641. std::string encoded_key = internal_key.Encode().ToString();
  2642. c.Add(encoded_key, "hello");
  2643. ImmutableCFOptions ioptions(options);
  2644. MutableCFOptions moptions(options);
  2645. // Generate table with filter policy
  2646. c.Finish(options, ioptions, moptions, table_options,
  2647. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  2648. auto reader = c.GetTableReader();
  2649. PinnableSlice value;
  2650. {
  2651. GetContext get_context(options.comparator, nullptr, nullptr, nullptr,
  2652. GetContext::kNotFound, user_key, &value, nullptr,
  2653. nullptr, true, nullptr, nullptr);
  2654. get_perf_context()->Reset();
  2655. ASSERT_OK(reader->Get(ReadOptions(), encoded_key, &get_context,
  2656. moptions.prefix_extractor.get()));
  2657. if (index_and_filter_in_cache) {
  2658. // data, index and filter block
  2659. ASSERT_EQ(get_perf_context()->block_read_count, 3);
  2660. ASSERT_EQ(get_perf_context()->index_block_read_count, 1);
  2661. ASSERT_EQ(get_perf_context()->filter_block_read_count, 1);
  2662. } else {
  2663. // just the data block
  2664. ASSERT_EQ(get_perf_context()->block_read_count, 1);
  2665. }
  2666. ASSERT_EQ(get_context.State(), GetContext::kFound);
  2667. ASSERT_STREQ(value.data(), "hello");
  2668. }
  2669. // Get non-existing key
  2670. user_key = "does-not-exist";
  2671. internal_key = InternalKey(user_key, 0, kTypeValue);
  2672. encoded_key = internal_key.Encode().ToString();
  2673. value.Reset();
  2674. {
  2675. GetContext get_context(options.comparator, nullptr, nullptr, nullptr,
  2676. GetContext::kNotFound, user_key, &value, nullptr,
  2677. nullptr, true, nullptr, nullptr);
  2678. get_perf_context()->Reset();
  2679. ASSERT_OK(reader->Get(ReadOptions(), encoded_key, &get_context,
  2680. moptions.prefix_extractor.get()));
  2681. ASSERT_EQ(get_context.State(), GetContext::kNotFound);
  2682. }
  2683. if (index_and_filter_in_cache) {
  2684. if (bloom_filter_type == 0) {
  2685. // with block-based, we read index and then the filter
  2686. ASSERT_EQ(get_perf_context()->block_read_count, 2);
  2687. ASSERT_EQ(get_perf_context()->index_block_read_count, 1);
  2688. ASSERT_EQ(get_perf_context()->filter_block_read_count, 1);
  2689. } else {
  2690. // with full-filter, we read filter first and then we stop
  2691. ASSERT_EQ(get_perf_context()->block_read_count, 1);
  2692. ASSERT_EQ(get_perf_context()->filter_block_read_count, 1);
  2693. }
  2694. } else {
  2695. // filter is already in memory and it figures out that the key doesn't
  2696. // exist
  2697. ASSERT_EQ(get_perf_context()->block_read_count, 0);
  2698. }
  2699. }
  2700. }
  2701. }
  2702. TEST_P(BlockBasedTableTest, BlockCacheLeak) {
  2703. // Check that when we reopen a table we don't lose access to blocks already
  2704. // in the cache. This test checks whether the Table actually makes use of the
  2705. // unique ID from the file.
  2706. Options opt;
  2707. std::unique_ptr<InternalKeyComparator> ikc;
  2708. ikc.reset(new test::PlainInternalKeyComparator(opt.comparator));
  2709. opt.compression = kNoCompression;
  2710. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2711. table_options.block_size = 1024;
  2712. // big enough so we don't ever lose cached values.
  2713. table_options.block_cache = NewLRUCache(16 * 1024 * 1024, 4);
  2714. opt.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2715. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  2716. c.Add("k01", "hello");
  2717. c.Add("k02", "hello2");
  2718. c.Add("k03", std::string(10000, 'x'));
  2719. c.Add("k04", std::string(200000, 'x'));
  2720. c.Add("k05", std::string(300000, 'x'));
  2721. c.Add("k06", "hello3");
  2722. c.Add("k07", std::string(100000, 'x'));
  2723. std::vector<std::string> keys;
  2724. stl_wrappers::KVMap kvmap;
  2725. const ImmutableCFOptions ioptions(opt);
  2726. const MutableCFOptions moptions(opt);
  2727. c.Finish(opt, ioptions, moptions, table_options, *ikc, &keys, &kvmap);
  2728. std::unique_ptr<InternalIterator> iter(
  2729. c.NewIterator(moptions.prefix_extractor.get()));
  2730. iter->SeekToFirst();
  2731. while (iter->Valid()) {
  2732. iter->key();
  2733. iter->value();
  2734. iter->Next();
  2735. }
  2736. ASSERT_OK(iter->status());
  2737. iter.reset();
  2738. const ImmutableCFOptions ioptions1(opt);
  2739. const MutableCFOptions moptions1(opt);
  2740. ASSERT_OK(c.Reopen(ioptions1, moptions1));
  2741. auto table_reader = dynamic_cast<BlockBasedTable*>(c.GetTableReader());
  2742. for (const std::string& key : keys) {
  2743. InternalKey ikey(key, kMaxSequenceNumber, kTypeValue);
  2744. ASSERT_TRUE(table_reader->TEST_KeyInCache(ReadOptions(), ikey.Encode()));
  2745. }
  2746. c.ResetTableReader();
  2747. // rerun with different block cache
  2748. table_options.block_cache = NewLRUCache(16 * 1024 * 1024, 4);
  2749. opt.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2750. const ImmutableCFOptions ioptions2(opt);
  2751. const MutableCFOptions moptions2(opt);
  2752. ASSERT_OK(c.Reopen(ioptions2, moptions2));
  2753. table_reader = dynamic_cast<BlockBasedTable*>(c.GetTableReader());
  2754. for (const std::string& key : keys) {
  2755. InternalKey ikey(key, kMaxSequenceNumber, kTypeValue);
  2756. ASSERT_TRUE(!table_reader->TEST_KeyInCache(ReadOptions(), ikey.Encode()));
  2757. }
  2758. c.ResetTableReader();
  2759. }
  2760. namespace {
  2761. class CustomMemoryAllocator : public MemoryAllocator {
  2762. public:
  2763. const char* Name() const override { return "CustomMemoryAllocator"; }
  2764. void* Allocate(size_t size) override {
  2765. ++numAllocations;
  2766. auto ptr = new char[size + 16];
  2767. memcpy(ptr, "memory_allocator_", 16); // mangle first 16 bytes
  2768. return reinterpret_cast<void*>(ptr + 16);
  2769. }
  2770. void Deallocate(void* p) override {
  2771. ++numDeallocations;
  2772. char* ptr = reinterpret_cast<char*>(p) - 16;
  2773. delete[] ptr;
  2774. }
  2775. std::atomic<int> numAllocations;
  2776. std::atomic<int> numDeallocations;
  2777. };
  2778. } // namespace
  2779. TEST_P(BlockBasedTableTest, MemoryAllocator) {
  2780. auto custom_memory_allocator = std::make_shared<CustomMemoryAllocator>();
  2781. {
  2782. Options opt;
  2783. std::unique_ptr<InternalKeyComparator> ikc;
  2784. ikc.reset(new test::PlainInternalKeyComparator(opt.comparator));
  2785. opt.compression = kNoCompression;
  2786. BlockBasedTableOptions table_options;
  2787. table_options.block_size = 1024;
  2788. LRUCacheOptions lruOptions;
  2789. lruOptions.memory_allocator = custom_memory_allocator;
  2790. lruOptions.capacity = 16 * 1024 * 1024;
  2791. lruOptions.num_shard_bits = 4;
  2792. table_options.block_cache = NewLRUCache(std::move(lruOptions));
  2793. opt.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2794. TableConstructor c(BytewiseComparator(),
  2795. true /* convert_to_internal_key_ */);
  2796. c.Add("k01", "hello");
  2797. c.Add("k02", "hello2");
  2798. c.Add("k03", std::string(10000, 'x'));
  2799. c.Add("k04", std::string(200000, 'x'));
  2800. c.Add("k05", std::string(300000, 'x'));
  2801. c.Add("k06", "hello3");
  2802. c.Add("k07", std::string(100000, 'x'));
  2803. std::vector<std::string> keys;
  2804. stl_wrappers::KVMap kvmap;
  2805. const ImmutableCFOptions ioptions(opt);
  2806. const MutableCFOptions moptions(opt);
  2807. c.Finish(opt, ioptions, moptions, table_options, *ikc, &keys, &kvmap);
  2808. std::unique_ptr<InternalIterator> iter(
  2809. c.NewIterator(moptions.prefix_extractor.get()));
  2810. iter->SeekToFirst();
  2811. while (iter->Valid()) {
  2812. iter->key();
  2813. iter->value();
  2814. iter->Next();
  2815. }
  2816. ASSERT_OK(iter->status());
  2817. }
  2818. // out of scope, block cache should have been deleted, all allocations
  2819. // deallocated
  2820. EXPECT_EQ(custom_memory_allocator->numAllocations.load(),
  2821. custom_memory_allocator->numDeallocations.load());
  2822. // make sure that allocations actually happened through the cache allocator
  2823. EXPECT_GT(custom_memory_allocator->numAllocations.load(), 0);
  2824. }
  2825. // Test the file checksum of block based table
  2826. TEST_P(BlockBasedTableTest, NoFileChecksum) {
  2827. Options options;
  2828. ImmutableCFOptions ioptions(options);
  2829. MutableCFOptions moptions(options);
  2830. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2831. std::unique_ptr<InternalKeyComparator> comparator(
  2832. new InternalKeyComparator(BytewiseComparator()));
  2833. SequenceNumber largest_seqno = 0;
  2834. int level = 0;
  2835. std::vector<std::unique_ptr<IntTblPropCollectorFactory>>
  2836. int_tbl_prop_collector_factories;
  2837. if (largest_seqno != 0) {
  2838. // Pretend that it's an external file written by SstFileWriter.
  2839. int_tbl_prop_collector_factories.emplace_back(
  2840. new SstFileWriterPropertiesCollectorFactory(2 /* version */,
  2841. 0 /* global_seqno*/));
  2842. }
  2843. std::string column_family_name;
  2844. FileChecksumTestHelper f(true);
  2845. f.CreateWriteableFile();
  2846. std::unique_ptr<TableBuilder> builder;
  2847. builder.reset(ioptions.table_factory->NewTableBuilder(
  2848. TableBuilderOptions(ioptions, moptions, *comparator,
  2849. &int_tbl_prop_collector_factories,
  2850. options.compression, options.sample_for_compression,
  2851. options.compression_opts, false /* skip_filters */,
  2852. column_family_name, level),
  2853. TablePropertiesCollectorFactory::Context::kUnknownColumnFamily,
  2854. f.GetFileWriter()));
  2855. f.ResetTableBuilder(std::move(builder));
  2856. f.AddKVtoKVMap(1000);
  2857. f.WriteKVAndFlushTable();
  2858. ASSERT_STREQ(f.GetFileChecksumFuncName(),
  2859. kUnknownFileChecksumFuncName.c_str());
  2860. ASSERT_STREQ(f.GetFileChecksum().c_str(), kUnknownFileChecksum.c_str());
  2861. }
  2862. TEST_P(BlockBasedTableTest, Crc32FileChecksum) {
  2863. Options options;
  2864. options.sst_file_checksum_func =
  2865. std::shared_ptr<FileChecksumFunc>(CreateFileChecksumFuncCrc32c());
  2866. ImmutableCFOptions ioptions(options);
  2867. MutableCFOptions moptions(options);
  2868. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  2869. std::unique_ptr<InternalKeyComparator> comparator(
  2870. new InternalKeyComparator(BytewiseComparator()));
  2871. SequenceNumber largest_seqno = 0;
  2872. int level = 0;
  2873. std::vector<std::unique_ptr<IntTblPropCollectorFactory>>
  2874. int_tbl_prop_collector_factories;
  2875. if (largest_seqno != 0) {
  2876. // Pretend that it's an external file written by SstFileWriter.
  2877. int_tbl_prop_collector_factories.emplace_back(
  2878. new SstFileWriterPropertiesCollectorFactory(2 /* version */,
  2879. 0 /* global_seqno*/));
  2880. }
  2881. std::string column_family_name;
  2882. FileChecksumTestHelper f(true);
  2883. f.CreateWriteableFile();
  2884. f.SetFileChecksumFunc(options.sst_file_checksum_func.get());
  2885. std::unique_ptr<TableBuilder> builder;
  2886. builder.reset(ioptions.table_factory->NewTableBuilder(
  2887. TableBuilderOptions(ioptions, moptions, *comparator,
  2888. &int_tbl_prop_collector_factories,
  2889. options.compression, options.sample_for_compression,
  2890. options.compression_opts, false /* skip_filters */,
  2891. column_family_name, level),
  2892. TablePropertiesCollectorFactory::Context::kUnknownColumnFamily,
  2893. f.GetFileWriter()));
  2894. f.ResetTableBuilder(std::move(builder));
  2895. f.AddKVtoKVMap(1000);
  2896. f.WriteKVAndFlushTable();
  2897. ASSERT_STREQ(f.GetFileChecksumFuncName(), "FileChecksumCrc32c");
  2898. std::string checksum;
  2899. ASSERT_OK(
  2900. f.CalculateFileChecksum(options.sst_file_checksum_func.get(), &checksum));
  2901. ASSERT_STREQ(f.GetFileChecksum().c_str(), checksum.c_str());
  2902. }
  2903. // Plain table is not supported in ROCKSDB_LITE
  2904. #ifndef ROCKSDB_LITE
  2905. TEST_F(PlainTableTest, BasicPlainTableProperties) {
  2906. PlainTableOptions plain_table_options;
  2907. plain_table_options.user_key_len = 8;
  2908. plain_table_options.bloom_bits_per_key = 8;
  2909. plain_table_options.hash_table_ratio = 0;
  2910. PlainTableFactory factory(plain_table_options);
  2911. test::StringSink sink;
  2912. std::unique_ptr<WritableFileWriter> file_writer(
  2913. test::GetWritableFileWriter(new test::StringSink(), "" /* don't care */));
  2914. Options options;
  2915. const ImmutableCFOptions ioptions(options);
  2916. const MutableCFOptions moptions(options);
  2917. InternalKeyComparator ikc(options.comparator);
  2918. std::vector<std::unique_ptr<IntTblPropCollectorFactory>>
  2919. int_tbl_prop_collector_factories;
  2920. std::string column_family_name;
  2921. int unknown_level = -1;
  2922. std::unique_ptr<TableBuilder> builder(factory.NewTableBuilder(
  2923. TableBuilderOptions(
  2924. ioptions, moptions, ikc, &int_tbl_prop_collector_factories,
  2925. kNoCompression, 0 /* sample_for_compression */, CompressionOptions(),
  2926. false /* skip_filters */, column_family_name, unknown_level),
  2927. TablePropertiesCollectorFactory::Context::kUnknownColumnFamily,
  2928. file_writer.get()));
  2929. for (char c = 'a'; c <= 'z'; ++c) {
  2930. std::string key(8, c);
  2931. key.append("\1 "); // PlainTable expects internal key structure
  2932. std::string value(28, c + 42);
  2933. builder->Add(key, value);
  2934. }
  2935. ASSERT_OK(builder->Finish());
  2936. file_writer->Flush();
  2937. test::StringSink* ss =
  2938. ROCKSDB_NAMESPACE::test::GetStringSinkFromLegacyWriter(file_writer.get());
  2939. std::unique_ptr<RandomAccessFileReader> file_reader(
  2940. test::GetRandomAccessFileReader(
  2941. new test::StringSource(ss->contents(), 72242, true)));
  2942. TableProperties* props = nullptr;
  2943. auto s = ReadTableProperties(file_reader.get(), ss->contents().size(),
  2944. kPlainTableMagicNumber, ioptions,
  2945. &props, true /* compression_type_missing */);
  2946. std::unique_ptr<TableProperties> props_guard(props);
  2947. ASSERT_OK(s);
  2948. ASSERT_EQ(0ul, props->index_size);
  2949. ASSERT_EQ(0ul, props->filter_size);
  2950. ASSERT_EQ(16ul * 26, props->raw_key_size);
  2951. ASSERT_EQ(28ul * 26, props->raw_value_size);
  2952. ASSERT_EQ(26ul, props->num_entries);
  2953. ASSERT_EQ(1ul, props->num_data_blocks);
  2954. }
  2955. TEST_F(PlainTableTest, NoFileChecksum) {
  2956. PlainTableOptions plain_table_options;
  2957. plain_table_options.user_key_len = 20;
  2958. plain_table_options.bloom_bits_per_key = 8;
  2959. plain_table_options.hash_table_ratio = 0;
  2960. PlainTableFactory factory(plain_table_options);
  2961. Options options;
  2962. const ImmutableCFOptions ioptions(options);
  2963. const MutableCFOptions moptions(options);
  2964. InternalKeyComparator ikc(options.comparator);
  2965. std::vector<std::unique_ptr<IntTblPropCollectorFactory>>
  2966. int_tbl_prop_collector_factories;
  2967. std::string column_family_name;
  2968. int unknown_level = -1;
  2969. FileChecksumTestHelper f(true);
  2970. f.CreateWriteableFile();
  2971. std::unique_ptr<TableBuilder> builder(factory.NewTableBuilder(
  2972. TableBuilderOptions(
  2973. ioptions, moptions, ikc, &int_tbl_prop_collector_factories,
  2974. kNoCompression, 0 /* sample_for_compression */, CompressionOptions(),
  2975. false /* skip_filters */, column_family_name, unknown_level),
  2976. TablePropertiesCollectorFactory::Context::kUnknownColumnFamily,
  2977. f.GetFileWriter()));
  2978. f.ResetTableBuilder(std::move(builder));
  2979. f.AddKVtoKVMap(1000);
  2980. f.WriteKVAndFlushTable();
  2981. ASSERT_STREQ(f.GetFileChecksumFuncName(),
  2982. kUnknownFileChecksumFuncName.c_str());
  2983. EXPECT_EQ(f.GetFileChecksum(), kUnknownFileChecksum.c_str());
  2984. }
  2985. TEST_F(PlainTableTest, Crc32FileChecksum) {
  2986. PlainTableOptions plain_table_options;
  2987. plain_table_options.user_key_len = 20;
  2988. plain_table_options.bloom_bits_per_key = 8;
  2989. plain_table_options.hash_table_ratio = 0;
  2990. PlainTableFactory factory(plain_table_options);
  2991. Options options;
  2992. options.sst_file_checksum_func =
  2993. std::shared_ptr<FileChecksumFunc>(CreateFileChecksumFuncCrc32c());
  2994. const ImmutableCFOptions ioptions(options);
  2995. const MutableCFOptions moptions(options);
  2996. InternalKeyComparator ikc(options.comparator);
  2997. std::vector<std::unique_ptr<IntTblPropCollectorFactory>>
  2998. int_tbl_prop_collector_factories;
  2999. std::string column_family_name;
  3000. int unknown_level = -1;
  3001. FileChecksumTestHelper f(true);
  3002. f.CreateWriteableFile();
  3003. f.SetFileChecksumFunc(options.sst_file_checksum_func.get());
  3004. std::unique_ptr<TableBuilder> builder(factory.NewTableBuilder(
  3005. TableBuilderOptions(
  3006. ioptions, moptions, ikc, &int_tbl_prop_collector_factories,
  3007. kNoCompression, 0 /* sample_for_compression */, CompressionOptions(),
  3008. false /* skip_filters */, column_family_name, unknown_level),
  3009. TablePropertiesCollectorFactory::Context::kUnknownColumnFamily,
  3010. f.GetFileWriter()));
  3011. f.ResetTableBuilder(std::move(builder));
  3012. f.AddKVtoKVMap(1000);
  3013. f.WriteKVAndFlushTable();
  3014. ASSERT_STREQ(f.GetFileChecksumFuncName(), "FileChecksumCrc32c");
  3015. std::string checksum;
  3016. ASSERT_OK(
  3017. f.CalculateFileChecksum(options.sst_file_checksum_func.get(), &checksum));
  3018. EXPECT_STREQ(f.GetFileChecksum().c_str(), checksum.c_str());
  3019. }
  3020. #endif // !ROCKSDB_LITE
  3021. TEST_F(GeneralTableTest, ApproximateOffsetOfPlain) {
  3022. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  3023. c.Add("k01", "hello");
  3024. c.Add("k02", "hello2");
  3025. c.Add("k03", std::string(10000, 'x'));
  3026. c.Add("k04", std::string(200000, 'x'));
  3027. c.Add("k05", std::string(300000, 'x'));
  3028. c.Add("k06", "hello3");
  3029. c.Add("k07", std::string(100000, 'x'));
  3030. std::vector<std::string> keys;
  3031. stl_wrappers::KVMap kvmap;
  3032. Options options;
  3033. test::PlainInternalKeyComparator internal_comparator(options.comparator);
  3034. options.compression = kNoCompression;
  3035. BlockBasedTableOptions table_options;
  3036. table_options.block_size = 1024;
  3037. const ImmutableCFOptions ioptions(options);
  3038. const MutableCFOptions moptions(options);
  3039. c.Finish(options, ioptions, moptions, table_options, internal_comparator,
  3040. &keys, &kvmap);
  3041. ASSERT_TRUE(Between(c.ApproximateOffsetOf("abc"), 0, 0));
  3042. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k01"), 0, 0));
  3043. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k01a"), 0, 0));
  3044. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k02"), 0, 0));
  3045. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k03"), 0, 0));
  3046. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k04"), 10000, 11000));
  3047. // k04 and k05 will be in two consecutive blocks, the index is
  3048. // an arbitrary slice between k04 and k05, either before or after k04a
  3049. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k04a"), 10000, 211000));
  3050. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k05"), 210000, 211000));
  3051. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k06"), 510000, 511000));
  3052. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k07"), 510000, 511000));
  3053. ASSERT_TRUE(Between(c.ApproximateOffsetOf("xyz"), 610000, 612000));
  3054. c.ResetTableReader();
  3055. }
  3056. static void DoCompressionTest(CompressionType comp) {
  3057. Random rnd(301);
  3058. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  3059. std::string tmp;
  3060. c.Add("k01", "hello");
  3061. c.Add("k02", test::CompressibleString(&rnd, 0.25, 10000, &tmp));
  3062. c.Add("k03", "hello3");
  3063. c.Add("k04", test::CompressibleString(&rnd, 0.25, 10000, &tmp));
  3064. std::vector<std::string> keys;
  3065. stl_wrappers::KVMap kvmap;
  3066. Options options;
  3067. test::PlainInternalKeyComparator ikc(options.comparator);
  3068. options.compression = comp;
  3069. BlockBasedTableOptions table_options;
  3070. table_options.block_size = 1024;
  3071. const ImmutableCFOptions ioptions(options);
  3072. const MutableCFOptions moptions(options);
  3073. c.Finish(options, ioptions, moptions, table_options, ikc, &keys, &kvmap);
  3074. ASSERT_TRUE(Between(c.ApproximateOffsetOf("abc"), 0, 0));
  3075. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k01"), 0, 0));
  3076. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k02"), 0, 0));
  3077. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k03"), 2000, 3500));
  3078. ASSERT_TRUE(Between(c.ApproximateOffsetOf("k04"), 2000, 3500));
  3079. ASSERT_TRUE(Between(c.ApproximateOffsetOf("xyz"), 4000, 6500));
  3080. c.ResetTableReader();
  3081. }
  3082. TEST_F(GeneralTableTest, ApproximateOffsetOfCompressed) {
  3083. std::vector<CompressionType> compression_state;
  3084. if (!Snappy_Supported()) {
  3085. fprintf(stderr, "skipping snappy compression tests\n");
  3086. } else {
  3087. compression_state.push_back(kSnappyCompression);
  3088. }
  3089. if (!Zlib_Supported()) {
  3090. fprintf(stderr, "skipping zlib compression tests\n");
  3091. } else {
  3092. compression_state.push_back(kZlibCompression);
  3093. }
  3094. // TODO(kailiu) DoCompressionTest() doesn't work with BZip2.
  3095. /*
  3096. if (!BZip2_Supported()) {
  3097. fprintf(stderr, "skipping bzip2 compression tests\n");
  3098. } else {
  3099. compression_state.push_back(kBZip2Compression);
  3100. }
  3101. */
  3102. if (!LZ4_Supported()) {
  3103. fprintf(stderr, "skipping lz4 and lz4hc compression tests\n");
  3104. } else {
  3105. compression_state.push_back(kLZ4Compression);
  3106. compression_state.push_back(kLZ4HCCompression);
  3107. }
  3108. if (!XPRESS_Supported()) {
  3109. fprintf(stderr, "skipping xpress and xpress compression tests\n");
  3110. }
  3111. else {
  3112. compression_state.push_back(kXpressCompression);
  3113. }
  3114. for (auto state : compression_state) {
  3115. DoCompressionTest(state);
  3116. }
  3117. }
  3118. #ifndef ROCKSDB_VALGRIND_RUN
  3119. // RandomizedHarnessTest is very slow for certain combination of arguments
  3120. // Split into 8 pieces to reduce the time individual tests take.
  3121. TEST_F(HarnessTest, Randomized1) {
  3122. // part 1 out of 8
  3123. const size_t part = 1;
  3124. const size_t total = 8;
  3125. RandomizedHarnessTest(part, total);
  3126. }
  3127. TEST_F(HarnessTest, Randomized2) {
  3128. // part 2 out of 8
  3129. const size_t part = 2;
  3130. const size_t total = 8;
  3131. RandomizedHarnessTest(part, total);
  3132. }
  3133. TEST_F(HarnessTest, Randomized3) {
  3134. // part 3 out of 8
  3135. const size_t part = 3;
  3136. const size_t total = 8;
  3137. RandomizedHarnessTest(part, total);
  3138. }
  3139. TEST_F(HarnessTest, Randomized4) {
  3140. // part 4 out of 8
  3141. const size_t part = 4;
  3142. const size_t total = 8;
  3143. RandomizedHarnessTest(part, total);
  3144. }
  3145. TEST_F(HarnessTest, Randomized5) {
  3146. // part 5 out of 8
  3147. const size_t part = 5;
  3148. const size_t total = 8;
  3149. RandomizedHarnessTest(part, total);
  3150. }
  3151. TEST_F(HarnessTest, Randomized6) {
  3152. // part 6 out of 8
  3153. const size_t part = 6;
  3154. const size_t total = 8;
  3155. RandomizedHarnessTest(part, total);
  3156. }
  3157. TEST_F(HarnessTest, Randomized7) {
  3158. // part 7 out of 8
  3159. const size_t part = 7;
  3160. const size_t total = 8;
  3161. RandomizedHarnessTest(part, total);
  3162. }
  3163. TEST_F(HarnessTest, Randomized8) {
  3164. // part 8 out of 8
  3165. const size_t part = 8;
  3166. const size_t total = 8;
  3167. RandomizedHarnessTest(part, total);
  3168. }
  3169. #ifndef ROCKSDB_LITE
  3170. TEST_F(HarnessTest, RandomizedLongDB) {
  3171. Random rnd(test::RandomSeed());
  3172. TestArgs args = {DB_TEST, false, 16, kNoCompression, 0, false};
  3173. Init(args);
  3174. int num_entries = 100000;
  3175. for (int e = 0; e < num_entries; e++) {
  3176. std::string v;
  3177. Add(test::RandomKey(&rnd, rnd.Skewed(4)),
  3178. test::RandomString(&rnd, rnd.Skewed(5), &v).ToString());
  3179. }
  3180. Test(&rnd);
  3181. // We must have created enough data to force merging
  3182. int files = 0;
  3183. for (int level = 0; level < db()->NumberLevels(); level++) {
  3184. std::string value;
  3185. char name[100];
  3186. snprintf(name, sizeof(name), "rocksdb.num-files-at-level%d", level);
  3187. ASSERT_TRUE(db()->GetProperty(name, &value));
  3188. files += atoi(value.c_str());
  3189. }
  3190. ASSERT_GT(files, 0);
  3191. }
  3192. #endif // ROCKSDB_LITE
  3193. #endif // ROCKSDB_VALGRIND_RUN
  3194. class MemTableTest : public testing::Test {};
  3195. TEST_F(MemTableTest, Simple) {
  3196. InternalKeyComparator cmp(BytewiseComparator());
  3197. auto table_factory = std::make_shared<SkipListFactory>();
  3198. Options options;
  3199. options.memtable_factory = table_factory;
  3200. ImmutableCFOptions ioptions(options);
  3201. WriteBufferManager wb(options.db_write_buffer_size);
  3202. MemTable* memtable =
  3203. new MemTable(cmp, ioptions, MutableCFOptions(options), &wb,
  3204. kMaxSequenceNumber, 0 /* column_family_id */);
  3205. memtable->Ref();
  3206. WriteBatch batch;
  3207. WriteBatchInternal::SetSequence(&batch, 100);
  3208. batch.Put(std::string("k1"), std::string("v1"));
  3209. batch.Put(std::string("k2"), std::string("v2"));
  3210. batch.Put(std::string("k3"), std::string("v3"));
  3211. batch.Put(std::string("largekey"), std::string("vlarge"));
  3212. batch.DeleteRange(std::string("chi"), std::string("xigua"));
  3213. batch.DeleteRange(std::string("begin"), std::string("end"));
  3214. ColumnFamilyMemTablesDefault cf_mems_default(memtable);
  3215. ASSERT_TRUE(
  3216. WriteBatchInternal::InsertInto(&batch, &cf_mems_default, nullptr, nullptr)
  3217. .ok());
  3218. for (int i = 0; i < 2; ++i) {
  3219. Arena arena;
  3220. ScopedArenaIterator arena_iter_guard;
  3221. std::unique_ptr<InternalIterator> iter_guard;
  3222. InternalIterator* iter;
  3223. if (i == 0) {
  3224. iter = memtable->NewIterator(ReadOptions(), &arena);
  3225. arena_iter_guard.set(iter);
  3226. } else {
  3227. iter = memtable->NewRangeTombstoneIterator(
  3228. ReadOptions(), kMaxSequenceNumber /* read_seq */);
  3229. iter_guard.reset(iter);
  3230. }
  3231. if (iter == nullptr) {
  3232. continue;
  3233. }
  3234. iter->SeekToFirst();
  3235. while (iter->Valid()) {
  3236. fprintf(stderr, "key: '%s' -> '%s'\n", iter->key().ToString().c_str(),
  3237. iter->value().ToString().c_str());
  3238. iter->Next();
  3239. }
  3240. }
  3241. delete memtable->Unref();
  3242. }
  3243. // Test the empty key
  3244. TEST_F(HarnessTest, SimpleEmptyKey) {
  3245. auto args = GenerateArgList();
  3246. for (const auto& arg : args) {
  3247. Init(arg);
  3248. Random rnd(test::RandomSeed() + 1);
  3249. Add("", "v");
  3250. Test(&rnd);
  3251. }
  3252. }
  3253. TEST_F(HarnessTest, SimpleSingle) {
  3254. auto args = GenerateArgList();
  3255. for (const auto& arg : args) {
  3256. Init(arg);
  3257. Random rnd(test::RandomSeed() + 2);
  3258. Add("abc", "v");
  3259. Test(&rnd);
  3260. }
  3261. }
  3262. TEST_F(HarnessTest, SimpleMulti) {
  3263. auto args = GenerateArgList();
  3264. for (const auto& arg : args) {
  3265. Init(arg);
  3266. Random rnd(test::RandomSeed() + 3);
  3267. Add("abc", "v");
  3268. Add("abcd", "v");
  3269. Add("ac", "v2");
  3270. Test(&rnd);
  3271. }
  3272. }
  3273. TEST_F(HarnessTest, SimpleSpecialKey) {
  3274. auto args = GenerateArgList();
  3275. for (const auto& arg : args) {
  3276. Init(arg);
  3277. Random rnd(test::RandomSeed() + 4);
  3278. Add("\xff\xff", "v3");
  3279. Test(&rnd);
  3280. }
  3281. }
  3282. TEST_F(HarnessTest, FooterTests) {
  3283. {
  3284. // upconvert legacy block based
  3285. std::string encoded;
  3286. Footer footer(kLegacyBlockBasedTableMagicNumber, 0);
  3287. BlockHandle meta_index(10, 5), index(20, 15);
  3288. footer.set_metaindex_handle(meta_index);
  3289. footer.set_index_handle(index);
  3290. footer.EncodeTo(&encoded);
  3291. Footer decoded_footer;
  3292. Slice encoded_slice(encoded);
  3293. decoded_footer.DecodeFrom(&encoded_slice);
  3294. ASSERT_EQ(decoded_footer.table_magic_number(), kBlockBasedTableMagicNumber);
  3295. ASSERT_EQ(decoded_footer.checksum(), kCRC32c);
  3296. ASSERT_EQ(decoded_footer.metaindex_handle().offset(), meta_index.offset());
  3297. ASSERT_EQ(decoded_footer.metaindex_handle().size(), meta_index.size());
  3298. ASSERT_EQ(decoded_footer.index_handle().offset(), index.offset());
  3299. ASSERT_EQ(decoded_footer.index_handle().size(), index.size());
  3300. ASSERT_EQ(decoded_footer.version(), 0U);
  3301. }
  3302. {
  3303. // xxhash block based
  3304. std::string encoded;
  3305. Footer footer(kBlockBasedTableMagicNumber, 1);
  3306. BlockHandle meta_index(10, 5), index(20, 15);
  3307. footer.set_metaindex_handle(meta_index);
  3308. footer.set_index_handle(index);
  3309. footer.set_checksum(kxxHash);
  3310. footer.EncodeTo(&encoded);
  3311. Footer decoded_footer;
  3312. Slice encoded_slice(encoded);
  3313. decoded_footer.DecodeFrom(&encoded_slice);
  3314. ASSERT_EQ(decoded_footer.table_magic_number(), kBlockBasedTableMagicNumber);
  3315. ASSERT_EQ(decoded_footer.checksum(), kxxHash);
  3316. ASSERT_EQ(decoded_footer.metaindex_handle().offset(), meta_index.offset());
  3317. ASSERT_EQ(decoded_footer.metaindex_handle().size(), meta_index.size());
  3318. ASSERT_EQ(decoded_footer.index_handle().offset(), index.offset());
  3319. ASSERT_EQ(decoded_footer.index_handle().size(), index.size());
  3320. ASSERT_EQ(decoded_footer.version(), 1U);
  3321. }
  3322. {
  3323. // xxhash64 block based
  3324. std::string encoded;
  3325. Footer footer(kBlockBasedTableMagicNumber, 1);
  3326. BlockHandle meta_index(10, 5), index(20, 15);
  3327. footer.set_metaindex_handle(meta_index);
  3328. footer.set_index_handle(index);
  3329. footer.set_checksum(kxxHash64);
  3330. footer.EncodeTo(&encoded);
  3331. Footer decoded_footer;
  3332. Slice encoded_slice(encoded);
  3333. decoded_footer.DecodeFrom(&encoded_slice);
  3334. ASSERT_EQ(decoded_footer.table_magic_number(), kBlockBasedTableMagicNumber);
  3335. ASSERT_EQ(decoded_footer.checksum(), kxxHash64);
  3336. ASSERT_EQ(decoded_footer.metaindex_handle().offset(), meta_index.offset());
  3337. ASSERT_EQ(decoded_footer.metaindex_handle().size(), meta_index.size());
  3338. ASSERT_EQ(decoded_footer.index_handle().offset(), index.offset());
  3339. ASSERT_EQ(decoded_footer.index_handle().size(), index.size());
  3340. ASSERT_EQ(decoded_footer.version(), 1U);
  3341. }
  3342. // Plain table is not supported in ROCKSDB_LITE
  3343. #ifndef ROCKSDB_LITE
  3344. {
  3345. // upconvert legacy plain table
  3346. std::string encoded;
  3347. Footer footer(kLegacyPlainTableMagicNumber, 0);
  3348. BlockHandle meta_index(10, 5), index(20, 15);
  3349. footer.set_metaindex_handle(meta_index);
  3350. footer.set_index_handle(index);
  3351. footer.EncodeTo(&encoded);
  3352. Footer decoded_footer;
  3353. Slice encoded_slice(encoded);
  3354. decoded_footer.DecodeFrom(&encoded_slice);
  3355. ASSERT_EQ(decoded_footer.table_magic_number(), kPlainTableMagicNumber);
  3356. ASSERT_EQ(decoded_footer.checksum(), kCRC32c);
  3357. ASSERT_EQ(decoded_footer.metaindex_handle().offset(), meta_index.offset());
  3358. ASSERT_EQ(decoded_footer.metaindex_handle().size(), meta_index.size());
  3359. ASSERT_EQ(decoded_footer.index_handle().offset(), index.offset());
  3360. ASSERT_EQ(decoded_footer.index_handle().size(), index.size());
  3361. ASSERT_EQ(decoded_footer.version(), 0U);
  3362. }
  3363. {
  3364. // xxhash block based
  3365. std::string encoded;
  3366. Footer footer(kPlainTableMagicNumber, 1);
  3367. BlockHandle meta_index(10, 5), index(20, 15);
  3368. footer.set_metaindex_handle(meta_index);
  3369. footer.set_index_handle(index);
  3370. footer.set_checksum(kxxHash);
  3371. footer.EncodeTo(&encoded);
  3372. Footer decoded_footer;
  3373. Slice encoded_slice(encoded);
  3374. decoded_footer.DecodeFrom(&encoded_slice);
  3375. ASSERT_EQ(decoded_footer.table_magic_number(), kPlainTableMagicNumber);
  3376. ASSERT_EQ(decoded_footer.checksum(), kxxHash);
  3377. ASSERT_EQ(decoded_footer.metaindex_handle().offset(), meta_index.offset());
  3378. ASSERT_EQ(decoded_footer.metaindex_handle().size(), meta_index.size());
  3379. ASSERT_EQ(decoded_footer.index_handle().offset(), index.offset());
  3380. ASSERT_EQ(decoded_footer.index_handle().size(), index.size());
  3381. ASSERT_EQ(decoded_footer.version(), 1U);
  3382. }
  3383. #endif // !ROCKSDB_LITE
  3384. {
  3385. // version == 2
  3386. std::string encoded;
  3387. Footer footer(kBlockBasedTableMagicNumber, 2);
  3388. BlockHandle meta_index(10, 5), index(20, 15);
  3389. footer.set_metaindex_handle(meta_index);
  3390. footer.set_index_handle(index);
  3391. footer.EncodeTo(&encoded);
  3392. Footer decoded_footer;
  3393. Slice encoded_slice(encoded);
  3394. decoded_footer.DecodeFrom(&encoded_slice);
  3395. ASSERT_EQ(decoded_footer.table_magic_number(), kBlockBasedTableMagicNumber);
  3396. ASSERT_EQ(decoded_footer.checksum(), kCRC32c);
  3397. ASSERT_EQ(decoded_footer.metaindex_handle().offset(), meta_index.offset());
  3398. ASSERT_EQ(decoded_footer.metaindex_handle().size(), meta_index.size());
  3399. ASSERT_EQ(decoded_footer.index_handle().offset(), index.offset());
  3400. ASSERT_EQ(decoded_footer.index_handle().size(), index.size());
  3401. ASSERT_EQ(decoded_footer.version(), 2U);
  3402. }
  3403. }
  3404. class IndexBlockRestartIntervalTest
  3405. : public TableTest,
  3406. public ::testing::WithParamInterface<std::pair<int, bool>> {
  3407. public:
  3408. static std::vector<std::pair<int, bool>> GetRestartValues() {
  3409. return {{-1, false}, {0, false}, {1, false}, {8, false},
  3410. {16, false}, {32, false}, {-1, true}, {0, true},
  3411. {1, true}, {8, true}, {16, true}, {32, true}};
  3412. }
  3413. };
  3414. INSTANTIATE_TEST_CASE_P(
  3415. IndexBlockRestartIntervalTest, IndexBlockRestartIntervalTest,
  3416. ::testing::ValuesIn(IndexBlockRestartIntervalTest::GetRestartValues()));
  3417. TEST_P(IndexBlockRestartIntervalTest, IndexBlockRestartInterval) {
  3418. const int kKeysInTable = 10000;
  3419. const int kKeySize = 100;
  3420. const int kValSize = 500;
  3421. const int index_block_restart_interval = std::get<0>(GetParam());
  3422. const bool value_delta_encoding = std::get<1>(GetParam());
  3423. Options options;
  3424. BlockBasedTableOptions table_options;
  3425. table_options.block_size = 64; // small block size to get big index block
  3426. table_options.index_block_restart_interval = index_block_restart_interval;
  3427. if (value_delta_encoding) {
  3428. table_options.format_version = 4;
  3429. }
  3430. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  3431. TableConstructor c(BytewiseComparator());
  3432. static Random rnd(301);
  3433. for (int i = 0; i < kKeysInTable; i++) {
  3434. InternalKey k(RandomString(&rnd, kKeySize), 0, kTypeValue);
  3435. c.Add(k.Encode().ToString(), RandomString(&rnd, kValSize));
  3436. }
  3437. std::vector<std::string> keys;
  3438. stl_wrappers::KVMap kvmap;
  3439. std::unique_ptr<InternalKeyComparator> comparator(
  3440. new InternalKeyComparator(BytewiseComparator()));
  3441. const ImmutableCFOptions ioptions(options);
  3442. const MutableCFOptions moptions(options);
  3443. c.Finish(options, ioptions, moptions, table_options, *comparator, &keys,
  3444. &kvmap);
  3445. auto reader = c.GetTableReader();
  3446. std::unique_ptr<InternalIterator> db_iter(reader->NewIterator(
  3447. ReadOptions(), moptions.prefix_extractor.get(), /*arena=*/nullptr,
  3448. /*skip_filters=*/false, TableReaderCaller::kUncategorized));
  3449. // Test point lookup
  3450. for (auto& kv : kvmap) {
  3451. db_iter->Seek(kv.first);
  3452. ASSERT_TRUE(db_iter->Valid());
  3453. ASSERT_OK(db_iter->status());
  3454. ASSERT_EQ(db_iter->key(), kv.first);
  3455. ASSERT_EQ(db_iter->value(), kv.second);
  3456. }
  3457. // Test iterating
  3458. auto kv_iter = kvmap.begin();
  3459. for (db_iter->SeekToFirst(); db_iter->Valid(); db_iter->Next()) {
  3460. ASSERT_EQ(db_iter->key(), kv_iter->first);
  3461. ASSERT_EQ(db_iter->value(), kv_iter->second);
  3462. kv_iter++;
  3463. }
  3464. ASSERT_EQ(kv_iter, kvmap.end());
  3465. c.ResetTableReader();
  3466. }
  3467. class PrefixTest : public testing::Test {
  3468. public:
  3469. PrefixTest() : testing::Test() {}
  3470. ~PrefixTest() override {}
  3471. };
  3472. namespace {
  3473. // A simple PrefixExtractor that only works for test PrefixAndWholeKeyTest
  3474. class TestPrefixExtractor : public ROCKSDB_NAMESPACE::SliceTransform {
  3475. public:
  3476. ~TestPrefixExtractor() override{};
  3477. const char* Name() const override { return "TestPrefixExtractor"; }
  3478. ROCKSDB_NAMESPACE::Slice Transform(
  3479. const ROCKSDB_NAMESPACE::Slice& src) const override {
  3480. assert(IsValid(src));
  3481. return ROCKSDB_NAMESPACE::Slice(src.data(), 3);
  3482. }
  3483. bool InDomain(const ROCKSDB_NAMESPACE::Slice& src) const override {
  3484. assert(IsValid(src));
  3485. return true;
  3486. }
  3487. bool InRange(const ROCKSDB_NAMESPACE::Slice& /*dst*/) const override {
  3488. return true;
  3489. }
  3490. bool IsValid(const ROCKSDB_NAMESPACE::Slice& src) const {
  3491. if (src.size() != 4) {
  3492. return false;
  3493. }
  3494. if (src[0] != '[') {
  3495. return false;
  3496. }
  3497. if (src[1] < '0' || src[1] > '9') {
  3498. return false;
  3499. }
  3500. if (src[2] != ']') {
  3501. return false;
  3502. }
  3503. if (src[3] < '0' || src[3] > '9') {
  3504. return false;
  3505. }
  3506. return true;
  3507. }
  3508. };
  3509. } // namespace
  3510. TEST_F(PrefixTest, PrefixAndWholeKeyTest) {
  3511. ROCKSDB_NAMESPACE::Options options;
  3512. options.compaction_style = ROCKSDB_NAMESPACE::kCompactionStyleUniversal;
  3513. options.num_levels = 20;
  3514. options.create_if_missing = true;
  3515. options.optimize_filters_for_hits = false;
  3516. options.target_file_size_base = 268435456;
  3517. options.prefix_extractor = std::make_shared<TestPrefixExtractor>();
  3518. ROCKSDB_NAMESPACE::BlockBasedTableOptions bbto;
  3519. bbto.filter_policy.reset(ROCKSDB_NAMESPACE::NewBloomFilterPolicy(10));
  3520. bbto.block_size = 262144;
  3521. bbto.whole_key_filtering = true;
  3522. const std::string kDBPath = test::PerThreadDBPath("table_prefix_test");
  3523. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  3524. DestroyDB(kDBPath, options);
  3525. ROCKSDB_NAMESPACE::DB* db;
  3526. ASSERT_OK(ROCKSDB_NAMESPACE::DB::Open(options, kDBPath, &db));
  3527. // Create a bunch of keys with 10 filters.
  3528. for (int i = 0; i < 10; i++) {
  3529. std::string prefix = "[" + std::to_string(i) + "]";
  3530. for (int j = 0; j < 10; j++) {
  3531. std::string key = prefix + std::to_string(j);
  3532. db->Put(ROCKSDB_NAMESPACE::WriteOptions(), key, "1");
  3533. }
  3534. }
  3535. // Trigger compaction.
  3536. db->CompactRange(CompactRangeOptions(), nullptr, nullptr);
  3537. delete db;
  3538. // In the second round, turn whole_key_filtering off and expect
  3539. // rocksdb still works.
  3540. }
  3541. /*
  3542. * Disable TableWithGlobalSeqno since RocksDB does not store global_seqno in
  3543. * the SST file any more. Instead, RocksDB deduces global_seqno from the
  3544. * MANIFEST while reading from an SST. Therefore, it's not possible to test the
  3545. * functionality of global_seqno in a single, isolated unit test without the
  3546. * involvement of Version, VersionSet, etc.
  3547. */
  3548. TEST_P(BlockBasedTableTest, DISABLED_TableWithGlobalSeqno) {
  3549. BlockBasedTableOptions bbto = GetBlockBasedTableOptions();
  3550. test::StringSink* sink = new test::StringSink();
  3551. std::unique_ptr<WritableFileWriter> file_writer(
  3552. test::GetWritableFileWriter(sink, "" /* don't care */));
  3553. Options options;
  3554. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  3555. const ImmutableCFOptions ioptions(options);
  3556. const MutableCFOptions moptions(options);
  3557. InternalKeyComparator ikc(options.comparator);
  3558. std::vector<std::unique_ptr<IntTblPropCollectorFactory>>
  3559. int_tbl_prop_collector_factories;
  3560. int_tbl_prop_collector_factories.emplace_back(
  3561. new SstFileWriterPropertiesCollectorFactory(2 /* version */,
  3562. 0 /* global_seqno*/));
  3563. std::string column_family_name;
  3564. std::unique_ptr<TableBuilder> builder(options.table_factory->NewTableBuilder(
  3565. TableBuilderOptions(ioptions, moptions, ikc,
  3566. &int_tbl_prop_collector_factories, kNoCompression,
  3567. 0 /* sample_for_compression */, CompressionOptions(),
  3568. false /* skip_filters */, column_family_name, -1),
  3569. TablePropertiesCollectorFactory::Context::kUnknownColumnFamily,
  3570. file_writer.get()));
  3571. for (char c = 'a'; c <= 'z'; ++c) {
  3572. std::string key(8, c);
  3573. std::string value = key;
  3574. InternalKey ik(key, 0, kTypeValue);
  3575. builder->Add(ik.Encode(), value);
  3576. }
  3577. ASSERT_OK(builder->Finish());
  3578. file_writer->Flush();
  3579. test::RandomRWStringSink ss_rw(sink);
  3580. uint32_t version;
  3581. uint64_t global_seqno;
  3582. uint64_t global_seqno_offset;
  3583. // Helper function to get version, global_seqno, global_seqno_offset
  3584. std::function<void()> GetVersionAndGlobalSeqno = [&]() {
  3585. std::unique_ptr<RandomAccessFileReader> file_reader(
  3586. test::GetRandomAccessFileReader(
  3587. new test::StringSource(ss_rw.contents(), 73342, true)));
  3588. TableProperties* props = nullptr;
  3589. ASSERT_OK(ReadTableProperties(file_reader.get(), ss_rw.contents().size(),
  3590. kBlockBasedTableMagicNumber, ioptions,
  3591. &props, true /* compression_type_missing */));
  3592. UserCollectedProperties user_props = props->user_collected_properties;
  3593. version = DecodeFixed32(
  3594. user_props[ExternalSstFilePropertyNames::kVersion].c_str());
  3595. global_seqno = DecodeFixed64(
  3596. user_props[ExternalSstFilePropertyNames::kGlobalSeqno].c_str());
  3597. global_seqno_offset =
  3598. props->properties_offsets[ExternalSstFilePropertyNames::kGlobalSeqno];
  3599. delete props;
  3600. };
  3601. // Helper function to update the value of the global seqno in the file
  3602. std::function<void(uint64_t)> SetGlobalSeqno = [&](uint64_t val) {
  3603. std::string new_global_seqno;
  3604. PutFixed64(&new_global_seqno, val);
  3605. ASSERT_OK(ss_rw.Write(global_seqno_offset, new_global_seqno));
  3606. };
  3607. // Helper function to get the contents of the table InternalIterator
  3608. std::unique_ptr<TableReader> table_reader;
  3609. std::function<InternalIterator*()> GetTableInternalIter = [&]() {
  3610. std::unique_ptr<RandomAccessFileReader> file_reader(
  3611. test::GetRandomAccessFileReader(
  3612. new test::StringSource(ss_rw.contents(), 73342, true)));
  3613. options.table_factory->NewTableReader(
  3614. TableReaderOptions(ioptions, moptions.prefix_extractor.get(),
  3615. EnvOptions(), ikc),
  3616. std::move(file_reader), ss_rw.contents().size(), &table_reader);
  3617. return table_reader->NewIterator(
  3618. ReadOptions(), moptions.prefix_extractor.get(), /*arena=*/nullptr,
  3619. /*skip_filters=*/false, TableReaderCaller::kUncategorized);
  3620. };
  3621. GetVersionAndGlobalSeqno();
  3622. ASSERT_EQ(2u, version);
  3623. ASSERT_EQ(0u, global_seqno);
  3624. InternalIterator* iter = GetTableInternalIter();
  3625. char current_c = 'a';
  3626. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  3627. ParsedInternalKey pik;
  3628. ASSERT_TRUE(ParseInternalKey(iter->key(), &pik));
  3629. ASSERT_EQ(pik.type, ValueType::kTypeValue);
  3630. ASSERT_EQ(pik.sequence, 0);
  3631. ASSERT_EQ(pik.user_key, iter->value());
  3632. ASSERT_EQ(pik.user_key.ToString(), std::string(8, current_c));
  3633. current_c++;
  3634. }
  3635. ASSERT_EQ(current_c, 'z' + 1);
  3636. delete iter;
  3637. // Update global sequence number to 10
  3638. SetGlobalSeqno(10);
  3639. GetVersionAndGlobalSeqno();
  3640. ASSERT_EQ(2u, version);
  3641. ASSERT_EQ(10u, global_seqno);
  3642. iter = GetTableInternalIter();
  3643. current_c = 'a';
  3644. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  3645. ParsedInternalKey pik;
  3646. ASSERT_TRUE(ParseInternalKey(iter->key(), &pik));
  3647. ASSERT_EQ(pik.type, ValueType::kTypeValue);
  3648. ASSERT_EQ(pik.sequence, 10);
  3649. ASSERT_EQ(pik.user_key, iter->value());
  3650. ASSERT_EQ(pik.user_key.ToString(), std::string(8, current_c));
  3651. current_c++;
  3652. }
  3653. ASSERT_EQ(current_c, 'z' + 1);
  3654. // Verify Seek
  3655. for (char c = 'a'; c <= 'z'; c++) {
  3656. std::string k = std::string(8, c);
  3657. InternalKey ik(k, 10, kValueTypeForSeek);
  3658. iter->Seek(ik.Encode());
  3659. ASSERT_TRUE(iter->Valid());
  3660. ParsedInternalKey pik;
  3661. ASSERT_TRUE(ParseInternalKey(iter->key(), &pik));
  3662. ASSERT_EQ(pik.type, ValueType::kTypeValue);
  3663. ASSERT_EQ(pik.sequence, 10);
  3664. ASSERT_EQ(pik.user_key.ToString(), k);
  3665. ASSERT_EQ(iter->value().ToString(), k);
  3666. }
  3667. delete iter;
  3668. // Update global sequence number to 3
  3669. SetGlobalSeqno(3);
  3670. GetVersionAndGlobalSeqno();
  3671. ASSERT_EQ(2u, version);
  3672. ASSERT_EQ(3u, global_seqno);
  3673. iter = GetTableInternalIter();
  3674. current_c = 'a';
  3675. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  3676. ParsedInternalKey pik;
  3677. ASSERT_TRUE(ParseInternalKey(iter->key(), &pik));
  3678. ASSERT_EQ(pik.type, ValueType::kTypeValue);
  3679. ASSERT_EQ(pik.sequence, 3);
  3680. ASSERT_EQ(pik.user_key, iter->value());
  3681. ASSERT_EQ(pik.user_key.ToString(), std::string(8, current_c));
  3682. current_c++;
  3683. }
  3684. ASSERT_EQ(current_c, 'z' + 1);
  3685. // Verify Seek
  3686. for (char c = 'a'; c <= 'z'; c++) {
  3687. std::string k = std::string(8, c);
  3688. // seqno=4 is less than 3 so we still should get our key
  3689. InternalKey ik(k, 4, kValueTypeForSeek);
  3690. iter->Seek(ik.Encode());
  3691. ASSERT_TRUE(iter->Valid());
  3692. ParsedInternalKey pik;
  3693. ASSERT_TRUE(ParseInternalKey(iter->key(), &pik));
  3694. ASSERT_EQ(pik.type, ValueType::kTypeValue);
  3695. ASSERT_EQ(pik.sequence, 3);
  3696. ASSERT_EQ(pik.user_key.ToString(), k);
  3697. ASSERT_EQ(iter->value().ToString(), k);
  3698. }
  3699. delete iter;
  3700. }
  3701. TEST_P(BlockBasedTableTest, BlockAlignTest) {
  3702. BlockBasedTableOptions bbto = GetBlockBasedTableOptions();
  3703. bbto.block_align = true;
  3704. test::StringSink* sink = new test::StringSink();
  3705. std::unique_ptr<WritableFileWriter> file_writer(
  3706. test::GetWritableFileWriter(sink, "" /* don't care */));
  3707. Options options;
  3708. options.compression = kNoCompression;
  3709. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  3710. const ImmutableCFOptions ioptions(options);
  3711. const MutableCFOptions moptions(options);
  3712. InternalKeyComparator ikc(options.comparator);
  3713. std::vector<std::unique_ptr<IntTblPropCollectorFactory>>
  3714. int_tbl_prop_collector_factories;
  3715. std::string column_family_name;
  3716. std::unique_ptr<TableBuilder> builder(options.table_factory->NewTableBuilder(
  3717. TableBuilderOptions(ioptions, moptions, ikc,
  3718. &int_tbl_prop_collector_factories, kNoCompression,
  3719. 0 /* sample_for_compression */, CompressionOptions(),
  3720. false /* skip_filters */, column_family_name, -1),
  3721. TablePropertiesCollectorFactory::Context::kUnknownColumnFamily,
  3722. file_writer.get()));
  3723. for (int i = 1; i <= 10000; ++i) {
  3724. std::ostringstream ostr;
  3725. ostr << std::setfill('0') << std::setw(5) << i;
  3726. std::string key = ostr.str();
  3727. std::string value = "val";
  3728. InternalKey ik(key, 0, kTypeValue);
  3729. builder->Add(ik.Encode(), value);
  3730. }
  3731. ASSERT_OK(builder->Finish());
  3732. file_writer->Flush();
  3733. test::RandomRWStringSink ss_rw(sink);
  3734. std::unique_ptr<RandomAccessFileReader> file_reader(
  3735. test::GetRandomAccessFileReader(
  3736. new test::StringSource(ss_rw.contents(), 73342, true)));
  3737. // Helper function to get version, global_seqno, global_seqno_offset
  3738. std::function<void()> VerifyBlockAlignment = [&]() {
  3739. TableProperties* props = nullptr;
  3740. ASSERT_OK(ReadTableProperties(file_reader.get(), ss_rw.contents().size(),
  3741. kBlockBasedTableMagicNumber, ioptions,
  3742. &props, true /* compression_type_missing */));
  3743. uint64_t data_block_size = props->data_size / props->num_data_blocks;
  3744. ASSERT_EQ(data_block_size, 4096);
  3745. ASSERT_EQ(props->data_size, data_block_size * props->num_data_blocks);
  3746. delete props;
  3747. };
  3748. VerifyBlockAlignment();
  3749. // The below block of code verifies that we can read back the keys. Set
  3750. // block_align to false when creating the reader to ensure we can flip between
  3751. // the two modes without any issues
  3752. std::unique_ptr<TableReader> table_reader;
  3753. bbto.block_align = false;
  3754. Options options2;
  3755. options2.table_factory.reset(NewBlockBasedTableFactory(bbto));
  3756. ImmutableCFOptions ioptions2(options2);
  3757. const MutableCFOptions moptions2(options2);
  3758. ASSERT_OK(ioptions.table_factory->NewTableReader(
  3759. TableReaderOptions(ioptions2, moptions2.prefix_extractor.get(),
  3760. EnvOptions(),
  3761. GetPlainInternalComparator(options2.comparator)),
  3762. std::move(file_reader), ss_rw.contents().size(), &table_reader));
  3763. std::unique_ptr<InternalIterator> db_iter(table_reader->NewIterator(
  3764. ReadOptions(), moptions2.prefix_extractor.get(), /*arena=*/nullptr,
  3765. /*skip_filters=*/false, TableReaderCaller::kUncategorized));
  3766. int expected_key = 1;
  3767. for (db_iter->SeekToFirst(); db_iter->Valid(); db_iter->Next()) {
  3768. std::ostringstream ostr;
  3769. ostr << std::setfill('0') << std::setw(5) << expected_key++;
  3770. std::string key = ostr.str();
  3771. std::string value = "val";
  3772. ASSERT_OK(db_iter->status());
  3773. ASSERT_EQ(ExtractUserKey(db_iter->key()).ToString(), key);
  3774. ASSERT_EQ(db_iter->value().ToString(), value);
  3775. }
  3776. expected_key--;
  3777. ASSERT_EQ(expected_key, 10000);
  3778. table_reader.reset();
  3779. }
  3780. TEST_P(BlockBasedTableTest, PropertiesBlockRestartPointTest) {
  3781. BlockBasedTableOptions bbto = GetBlockBasedTableOptions();
  3782. bbto.block_align = true;
  3783. test::StringSink* sink = new test::StringSink();
  3784. std::unique_ptr<WritableFileWriter> file_writer(
  3785. test::GetWritableFileWriter(sink, "" /* don't care */));
  3786. Options options;
  3787. options.compression = kNoCompression;
  3788. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  3789. const ImmutableCFOptions ioptions(options);
  3790. const MutableCFOptions moptions(options);
  3791. InternalKeyComparator ikc(options.comparator);
  3792. std::vector<std::unique_ptr<IntTblPropCollectorFactory>>
  3793. int_tbl_prop_collector_factories;
  3794. std::string column_family_name;
  3795. std::unique_ptr<TableBuilder> builder(options.table_factory->NewTableBuilder(
  3796. TableBuilderOptions(ioptions, moptions, ikc,
  3797. &int_tbl_prop_collector_factories, kNoCompression,
  3798. 0 /* sample_for_compression */, CompressionOptions(),
  3799. false /* skip_filters */, column_family_name, -1),
  3800. TablePropertiesCollectorFactory::Context::kUnknownColumnFamily,
  3801. file_writer.get()));
  3802. for (int i = 1; i <= 10000; ++i) {
  3803. std::ostringstream ostr;
  3804. ostr << std::setfill('0') << std::setw(5) << i;
  3805. std::string key = ostr.str();
  3806. std::string value = "val";
  3807. InternalKey ik(key, 0, kTypeValue);
  3808. builder->Add(ik.Encode(), value);
  3809. }
  3810. ASSERT_OK(builder->Finish());
  3811. file_writer->Flush();
  3812. test::RandomRWStringSink ss_rw(sink);
  3813. std::unique_ptr<RandomAccessFileReader> file_reader(
  3814. test::GetRandomAccessFileReader(
  3815. new test::StringSource(ss_rw.contents(), 73342, true)));
  3816. {
  3817. RandomAccessFileReader* file = file_reader.get();
  3818. uint64_t file_size = ss_rw.contents().size();
  3819. Footer footer;
  3820. ASSERT_OK(ReadFooterFromFile(file, nullptr /* prefetch_buffer */, file_size,
  3821. &footer, kBlockBasedTableMagicNumber));
  3822. auto BlockFetchHelper = [&](const BlockHandle& handle, BlockType block_type,
  3823. BlockContents* contents) {
  3824. ReadOptions read_options;
  3825. read_options.verify_checksums = false;
  3826. PersistentCacheOptions cache_options;
  3827. BlockFetcher block_fetcher(
  3828. file, nullptr /* prefetch_buffer */, footer, read_options, handle,
  3829. contents, ioptions, false /* decompress */,
  3830. false /*maybe_compressed*/, block_type,
  3831. UncompressionDict::GetEmptyDict(), cache_options);
  3832. ASSERT_OK(block_fetcher.ReadBlockContents());
  3833. };
  3834. // -- Read metaindex block
  3835. auto metaindex_handle = footer.metaindex_handle();
  3836. BlockContents metaindex_contents;
  3837. BlockFetchHelper(metaindex_handle, BlockType::kMetaIndex,
  3838. &metaindex_contents);
  3839. Block metaindex_block(std::move(metaindex_contents),
  3840. kDisableGlobalSequenceNumber);
  3841. std::unique_ptr<InternalIterator> meta_iter(metaindex_block.NewDataIterator(
  3842. BytewiseComparator(), BytewiseComparator()));
  3843. bool found_properties_block = true;
  3844. ASSERT_OK(SeekToPropertiesBlock(meta_iter.get(), &found_properties_block));
  3845. ASSERT_TRUE(found_properties_block);
  3846. // -- Read properties block
  3847. Slice v = meta_iter->value();
  3848. BlockHandle properties_handle;
  3849. ASSERT_OK(properties_handle.DecodeFrom(&v));
  3850. BlockContents properties_contents;
  3851. BlockFetchHelper(properties_handle, BlockType::kProperties,
  3852. &properties_contents);
  3853. Block properties_block(std::move(properties_contents),
  3854. kDisableGlobalSequenceNumber);
  3855. ASSERT_EQ(properties_block.NumRestarts(), 1u);
  3856. }
  3857. }
  3858. TEST_P(BlockBasedTableTest, PropertiesMetaBlockLast) {
  3859. // The properties meta-block should come at the end since we always need to
  3860. // read it when opening a file, unlike index/filter/other meta-blocks, which
  3861. // are sometimes read depending on the user's configuration. This ordering
  3862. // allows us to do a small readahead on the end of the file to read properties
  3863. // and meta-index blocks with one I/O.
  3864. TableConstructor c(BytewiseComparator(), true /* convert_to_internal_key_ */);
  3865. c.Add("a1", "val1");
  3866. c.Add("b2", "val2");
  3867. c.Add("c3", "val3");
  3868. c.Add("d4", "val4");
  3869. c.Add("e5", "val5");
  3870. c.Add("f6", "val6");
  3871. c.Add("g7", "val7");
  3872. c.Add("h8", "val8");
  3873. c.Add("j9", "val9");
  3874. // write an SST file
  3875. Options options;
  3876. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  3877. table_options.filter_policy.reset(NewBloomFilterPolicy(
  3878. 8 /* bits_per_key */, false /* use_block_based_filter */));
  3879. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  3880. ImmutableCFOptions ioptions(options);
  3881. MutableCFOptions moptions(options);
  3882. std::vector<std::string> keys;
  3883. stl_wrappers::KVMap kvmap;
  3884. c.Finish(options, ioptions, moptions, table_options,
  3885. GetPlainInternalComparator(options.comparator), &keys, &kvmap);
  3886. // get file reader
  3887. test::StringSink* table_sink = c.TEST_GetSink();
  3888. std::unique_ptr<RandomAccessFileReader> table_reader{
  3889. test::GetRandomAccessFileReader(
  3890. new test::StringSource(table_sink->contents(), 0 /* unique_id */,
  3891. false /* allow_mmap_reads */))};
  3892. size_t table_size = table_sink->contents().size();
  3893. // read footer
  3894. Footer footer;
  3895. ASSERT_OK(ReadFooterFromFile(table_reader.get(),
  3896. nullptr /* prefetch_buffer */, table_size,
  3897. &footer, kBlockBasedTableMagicNumber));
  3898. // read metaindex
  3899. auto metaindex_handle = footer.metaindex_handle();
  3900. BlockContents metaindex_contents;
  3901. PersistentCacheOptions pcache_opts;
  3902. BlockFetcher block_fetcher(
  3903. table_reader.get(), nullptr /* prefetch_buffer */, footer, ReadOptions(),
  3904. metaindex_handle, &metaindex_contents, ioptions, false /* decompress */,
  3905. false /*maybe_compressed*/, BlockType::kMetaIndex,
  3906. UncompressionDict::GetEmptyDict(), pcache_opts,
  3907. nullptr /*memory_allocator*/);
  3908. ASSERT_OK(block_fetcher.ReadBlockContents());
  3909. Block metaindex_block(std::move(metaindex_contents),
  3910. kDisableGlobalSequenceNumber);
  3911. // verify properties block comes last
  3912. std::unique_ptr<InternalIterator> metaindex_iter{
  3913. metaindex_block.NewDataIterator(options.comparator, options.comparator)};
  3914. uint64_t max_offset = 0;
  3915. std::string key_at_max_offset;
  3916. for (metaindex_iter->SeekToFirst(); metaindex_iter->Valid();
  3917. metaindex_iter->Next()) {
  3918. BlockHandle handle;
  3919. Slice value = metaindex_iter->value();
  3920. ASSERT_OK(handle.DecodeFrom(&value));
  3921. if (handle.offset() > max_offset) {
  3922. max_offset = handle.offset();
  3923. key_at_max_offset = metaindex_iter->key().ToString();
  3924. }
  3925. }
  3926. ASSERT_EQ(kPropertiesBlock, key_at_max_offset);
  3927. // index handle is stored in footer rather than metaindex block, so need
  3928. // separate logic to verify it comes before properties block.
  3929. ASSERT_GT(max_offset, footer.index_handle().offset());
  3930. c.ResetTableReader();
  3931. }
  3932. TEST_P(BlockBasedTableTest, BadOptions) {
  3933. ROCKSDB_NAMESPACE::Options options;
  3934. options.compression = kNoCompression;
  3935. BlockBasedTableOptions bbto = GetBlockBasedTableOptions();
  3936. bbto.block_size = 4000;
  3937. bbto.block_align = true;
  3938. const std::string kDBPath =
  3939. test::PerThreadDBPath("block_based_table_bad_options_test");
  3940. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  3941. DestroyDB(kDBPath, options);
  3942. ROCKSDB_NAMESPACE::DB* db;
  3943. ASSERT_NOK(ROCKSDB_NAMESPACE::DB::Open(options, kDBPath, &db));
  3944. bbto.block_size = 4096;
  3945. options.compression = kSnappyCompression;
  3946. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  3947. ASSERT_NOK(ROCKSDB_NAMESPACE::DB::Open(options, kDBPath, &db));
  3948. }
  3949. TEST_F(BBTTailPrefetchTest, TestTailPrefetchStats) {
  3950. TailPrefetchStats tpstats;
  3951. ASSERT_EQ(0, tpstats.GetSuggestedPrefetchSize());
  3952. tpstats.RecordEffectiveSize(size_t{1000});
  3953. tpstats.RecordEffectiveSize(size_t{1005});
  3954. tpstats.RecordEffectiveSize(size_t{1002});
  3955. ASSERT_EQ(1005, tpstats.GetSuggestedPrefetchSize());
  3956. // One single super large value shouldn't influence much
  3957. tpstats.RecordEffectiveSize(size_t{1002000});
  3958. tpstats.RecordEffectiveSize(size_t{999});
  3959. ASSERT_LE(1005, tpstats.GetSuggestedPrefetchSize());
  3960. ASSERT_GT(1200, tpstats.GetSuggestedPrefetchSize());
  3961. // Only history of 32 is kept
  3962. for (int i = 0; i < 32; i++) {
  3963. tpstats.RecordEffectiveSize(size_t{100});
  3964. }
  3965. ASSERT_EQ(100, tpstats.GetSuggestedPrefetchSize());
  3966. // 16 large values and 16 small values. The result should be closer
  3967. // to the small value as the algorithm.
  3968. for (int i = 0; i < 16; i++) {
  3969. tpstats.RecordEffectiveSize(size_t{1000});
  3970. }
  3971. tpstats.RecordEffectiveSize(size_t{10});
  3972. tpstats.RecordEffectiveSize(size_t{20});
  3973. for (int i = 0; i < 6; i++) {
  3974. tpstats.RecordEffectiveSize(size_t{100});
  3975. }
  3976. ASSERT_LE(80, tpstats.GetSuggestedPrefetchSize());
  3977. ASSERT_GT(200, tpstats.GetSuggestedPrefetchSize());
  3978. }
  3979. TEST_F(BBTTailPrefetchTest, FilePrefetchBufferMinOffset) {
  3980. TailPrefetchStats tpstats;
  3981. FilePrefetchBuffer buffer(nullptr, 0, 0, false, true);
  3982. buffer.TryReadFromCache(500, 10, nullptr);
  3983. buffer.TryReadFromCache(480, 10, nullptr);
  3984. buffer.TryReadFromCache(490, 10, nullptr);
  3985. ASSERT_EQ(480, buffer.min_offset_read());
  3986. }
  3987. TEST_P(BlockBasedTableTest, DataBlockHashIndex) {
  3988. const int kNumKeys = 500;
  3989. const int kKeySize = 8;
  3990. const int kValSize = 40;
  3991. BlockBasedTableOptions table_options = GetBlockBasedTableOptions();
  3992. table_options.data_block_index_type =
  3993. BlockBasedTableOptions::kDataBlockBinaryAndHash;
  3994. Options options;
  3995. options.comparator = BytewiseComparator();
  3996. options.table_factory.reset(new BlockBasedTableFactory(table_options));
  3997. TableConstructor c(options.comparator);
  3998. static Random rnd(1048);
  3999. for (int i = 0; i < kNumKeys; i++) {
  4000. // padding one "0" to mark existent keys.
  4001. std::string random_key(RandomString(&rnd, kKeySize - 1) + "1");
  4002. InternalKey k(random_key, 0, kTypeValue);
  4003. c.Add(k.Encode().ToString(), RandomString(&rnd, kValSize));
  4004. }
  4005. std::vector<std::string> keys;
  4006. stl_wrappers::KVMap kvmap;
  4007. const ImmutableCFOptions ioptions(options);
  4008. const MutableCFOptions moptions(options);
  4009. const InternalKeyComparator internal_comparator(options.comparator);
  4010. c.Finish(options, ioptions, moptions, table_options, internal_comparator,
  4011. &keys, &kvmap);
  4012. auto reader = c.GetTableReader();
  4013. std::unique_ptr<InternalIterator> seek_iter;
  4014. seek_iter.reset(reader->NewIterator(
  4015. ReadOptions(), moptions.prefix_extractor.get(), /*arena=*/nullptr,
  4016. /*skip_filters=*/false, TableReaderCaller::kUncategorized));
  4017. for (int i = 0; i < 2; ++i) {
  4018. ReadOptions ro;
  4019. // for every kv, we seek using two method: Get() and Seek()
  4020. // Get() will use the SuffixIndexHash in Block. For non-existent key it
  4021. // will invalidate the iterator
  4022. // Seek() will use the default BinarySeek() in Block. So for non-existent
  4023. // key it will land at the closest key that is large than target.
  4024. // Search for existent keys
  4025. for (auto& kv : kvmap) {
  4026. if (i == 0) {
  4027. // Search using Seek()
  4028. seek_iter->Seek(kv.first);
  4029. ASSERT_OK(seek_iter->status());
  4030. ASSERT_TRUE(seek_iter->Valid());
  4031. ASSERT_EQ(seek_iter->key(), kv.first);
  4032. ASSERT_EQ(seek_iter->value(), kv.second);
  4033. } else {
  4034. // Search using Get()
  4035. PinnableSlice value;
  4036. std::string user_key = ExtractUserKey(kv.first).ToString();
  4037. GetContext get_context(options.comparator, nullptr, nullptr, nullptr,
  4038. GetContext::kNotFound, user_key, &value, nullptr,
  4039. nullptr, true, nullptr, nullptr);
  4040. ASSERT_OK(reader->Get(ro, kv.first, &get_context,
  4041. moptions.prefix_extractor.get()));
  4042. ASSERT_EQ(get_context.State(), GetContext::kFound);
  4043. ASSERT_EQ(value, Slice(kv.second));
  4044. value.Reset();
  4045. }
  4046. }
  4047. // Search for non-existent keys
  4048. for (auto& kv : kvmap) {
  4049. std::string user_key = ExtractUserKey(kv.first).ToString();
  4050. user_key.back() = '0'; // make it non-existent key
  4051. InternalKey internal_key(user_key, 0, kTypeValue);
  4052. std::string encoded_key = internal_key.Encode().ToString();
  4053. if (i == 0) { // Search using Seek()
  4054. seek_iter->Seek(encoded_key);
  4055. ASSERT_OK(seek_iter->status());
  4056. if (seek_iter->Valid()) {
  4057. ASSERT_TRUE(BytewiseComparator()->Compare(
  4058. user_key, ExtractUserKey(seek_iter->key())) < 0);
  4059. }
  4060. } else { // Search using Get()
  4061. PinnableSlice value;
  4062. GetContext get_context(options.comparator, nullptr, nullptr, nullptr,
  4063. GetContext::kNotFound, user_key, &value, nullptr,
  4064. nullptr, true, nullptr, nullptr);
  4065. ASSERT_OK(reader->Get(ro, encoded_key, &get_context,
  4066. moptions.prefix_extractor.get()));
  4067. ASSERT_EQ(get_context.State(), GetContext::kNotFound);
  4068. value.Reset();
  4069. }
  4070. }
  4071. }
  4072. }
  4073. // BlockBasedTableIterator should invalidate itself and return
  4074. // OutOfBound()=true immediately after Seek(), to allow LevelIterator
  4075. // filter out corresponding level.
  4076. TEST_P(BlockBasedTableTest, OutOfBoundOnSeek) {
  4077. TableConstructor c(BytewiseComparator(), true /*convert_to_internal_key*/);
  4078. c.Add("foo", "v1");
  4079. std::vector<std::string> keys;
  4080. stl_wrappers::KVMap kvmap;
  4081. Options options;
  4082. BlockBasedTableOptions table_opt(GetBlockBasedTableOptions());
  4083. options.table_factory.reset(NewBlockBasedTableFactory(table_opt));
  4084. const ImmutableCFOptions ioptions(options);
  4085. const MutableCFOptions moptions(options);
  4086. c.Finish(options, ioptions, moptions, table_opt,
  4087. GetPlainInternalComparator(BytewiseComparator()), &keys, &kvmap);
  4088. auto* reader = c.GetTableReader();
  4089. ReadOptions read_opt;
  4090. std::string upper_bound = "bar";
  4091. Slice upper_bound_slice(upper_bound);
  4092. read_opt.iterate_upper_bound = &upper_bound_slice;
  4093. std::unique_ptr<InternalIterator> iter;
  4094. iter.reset(new KeyConvertingIterator(reader->NewIterator(
  4095. read_opt, /*prefix_extractor=*/nullptr, /*arena=*/nullptr,
  4096. /*skip_filters=*/false, TableReaderCaller::kUncategorized)));
  4097. iter->SeekToFirst();
  4098. ASSERT_FALSE(iter->Valid());
  4099. ASSERT_TRUE(iter->IsOutOfBound());
  4100. iter.reset(new KeyConvertingIterator(reader->NewIterator(
  4101. read_opt, /*prefix_extractor=*/nullptr, /*arena=*/nullptr,
  4102. /*skip_filters=*/false, TableReaderCaller::kUncategorized)));
  4103. iter->Seek("foo");
  4104. ASSERT_FALSE(iter->Valid());
  4105. ASSERT_TRUE(iter->IsOutOfBound());
  4106. }
  4107. // BlockBasedTableIterator should invalidate itself and return
  4108. // OutOfBound()=true after Next(), if it finds current index key is no smaller
  4109. // than upper bound, unless it is pointing to the last data block.
  4110. TEST_P(BlockBasedTableTest, OutOfBoundOnNext) {
  4111. TableConstructor c(BytewiseComparator(), true /*convert_to_internal_key*/);
  4112. c.Add("bar", "v");
  4113. c.Add("foo", "v");
  4114. std::vector<std::string> keys;
  4115. stl_wrappers::KVMap kvmap;
  4116. Options options;
  4117. BlockBasedTableOptions table_opt(GetBlockBasedTableOptions());
  4118. table_opt.flush_block_policy_factory =
  4119. std::make_shared<FlushBlockEveryKeyPolicyFactory>();
  4120. options.table_factory.reset(NewBlockBasedTableFactory(table_opt));
  4121. const ImmutableCFOptions ioptions(options);
  4122. const MutableCFOptions moptions(options);
  4123. c.Finish(options, ioptions, moptions, table_opt,
  4124. GetPlainInternalComparator(BytewiseComparator()), &keys, &kvmap);
  4125. auto* reader = c.GetTableReader();
  4126. ReadOptions read_opt;
  4127. std::string ub1 = "bar_after";
  4128. Slice ub_slice1(ub1);
  4129. read_opt.iterate_upper_bound = &ub_slice1;
  4130. std::unique_ptr<InternalIterator> iter;
  4131. iter.reset(new KeyConvertingIterator(reader->NewIterator(
  4132. read_opt, /*prefix_extractor=*/nullptr, /*arena=*/nullptr,
  4133. /*skip_filters=*/false, TableReaderCaller::kUncategorized)));
  4134. iter->Seek("bar");
  4135. ASSERT_TRUE(iter->Valid());
  4136. ASSERT_EQ("bar", iter->key());
  4137. iter->Next();
  4138. ASSERT_FALSE(iter->Valid());
  4139. ASSERT_TRUE(iter->IsOutOfBound());
  4140. std::string ub2 = "foo_after";
  4141. Slice ub_slice2(ub2);
  4142. read_opt.iterate_upper_bound = &ub_slice2;
  4143. iter.reset(new KeyConvertingIterator(reader->NewIterator(
  4144. read_opt, /*prefix_extractor=*/nullptr, /*arena=*/nullptr,
  4145. /*skip_filters=*/false, TableReaderCaller::kUncategorized)));
  4146. iter->Seek("foo");
  4147. ASSERT_TRUE(iter->Valid());
  4148. ASSERT_EQ("foo", iter->key());
  4149. iter->Next();
  4150. ASSERT_FALSE(iter->Valid());
  4151. ASSERT_FALSE(iter->IsOutOfBound());
  4152. }
  4153. } // namespace ROCKSDB_NAMESPACE
  4154. int main(int argc, char** argv) {
  4155. ::testing::InitGoogleTest(&argc, argv);
  4156. return RUN_ALL_TESTS();
  4157. }