prefetch_test.cc 135 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. #include "db/db_test_util.h"
  6. #include "file/file_prefetch_buffer.h"
  7. #include "file/file_util.h"
  8. #include "rocksdb/file_system.h"
  9. #include "test_util/sync_point.h"
  10. #ifdef GFLAGS
  11. #include "tools/io_tracer_parser_tool.h"
  12. #endif
  13. #include "rocksdb/flush_block_policy.h"
  14. #include "util/random.h"
  15. namespace {
  16. static bool enable_io_uring = true;
  17. extern "C" bool RocksDbIOUringEnable() { return enable_io_uring; }
  18. } // namespace
  19. namespace ROCKSDB_NAMESPACE {
  20. class MockFS;
  21. class MockRandomAccessFile : public FSRandomAccessFileOwnerWrapper {
  22. public:
  23. MockRandomAccessFile(std::unique_ptr<FSRandomAccessFile>& file,
  24. bool support_prefetch, std::atomic_int& prefetch_count,
  25. bool small_buffer_alignment = false)
  26. : FSRandomAccessFileOwnerWrapper(std::move(file)),
  27. support_prefetch_(support_prefetch),
  28. prefetch_count_(prefetch_count),
  29. small_buffer_alignment_(small_buffer_alignment) {}
  30. IOStatus Prefetch(uint64_t offset, size_t n, const IOOptions& options,
  31. IODebugContext* dbg) override {
  32. if (support_prefetch_) {
  33. prefetch_count_.fetch_add(1);
  34. return target()->Prefetch(offset, n, options, dbg);
  35. } else {
  36. return IOStatus::NotSupported("Prefetch not supported");
  37. }
  38. }
  39. size_t GetRequiredBufferAlignment() const override {
  40. return small_buffer_alignment_
  41. ? 1
  42. : FSRandomAccessFileOwnerWrapper::GetRequiredBufferAlignment();
  43. }
  44. private:
  45. const bool support_prefetch_;
  46. std::atomic_int& prefetch_count_;
  47. const bool small_buffer_alignment_;
  48. };
  49. class MockFS : public FileSystemWrapper {
  50. public:
  51. explicit MockFS(const std::shared_ptr<FileSystem>& wrapped,
  52. bool support_prefetch, bool small_buffer_alignment = false)
  53. : FileSystemWrapper(wrapped),
  54. support_prefetch_(support_prefetch),
  55. small_buffer_alignment_(small_buffer_alignment) {}
  56. static const char* kClassName() { return "MockFS"; }
  57. const char* Name() const override { return kClassName(); }
  58. IOStatus NewRandomAccessFile(const std::string& fname,
  59. const FileOptions& opts,
  60. std::unique_ptr<FSRandomAccessFile>* result,
  61. IODebugContext* dbg) override {
  62. std::unique_ptr<FSRandomAccessFile> file;
  63. IOStatus s;
  64. s = target()->NewRandomAccessFile(fname, opts, &file, dbg);
  65. result->reset(new MockRandomAccessFile(
  66. file, support_prefetch_, prefetch_count_, small_buffer_alignment_));
  67. return s;
  68. }
  69. void ClearPrefetchCount() { prefetch_count_ = 0; }
  70. bool IsPrefetchCalled() { return prefetch_count_ > 0; }
  71. int GetPrefetchCount() {
  72. return prefetch_count_.load(std::memory_order_relaxed);
  73. }
  74. private:
  75. const bool support_prefetch_;
  76. const bool small_buffer_alignment_;
  77. std::atomic_int prefetch_count_{0};
  78. };
  79. class PrefetchTest
  80. : public DBTestBase,
  81. public ::testing::WithParamInterface<std::tuple<bool, bool>> {
  82. public:
  83. PrefetchTest() : DBTestBase("prefetch_test", true) {}
  84. virtual void SetGenericOptions(Env* env, bool use_direct_io,
  85. Options& options) {
  86. anon::OptionsOverride options_override;
  87. // for !disable_io in PrefetchTest.Basic
  88. options_override.full_block_cache = true;
  89. options = CurrentOptions(options_override);
  90. options.write_buffer_size = 1024;
  91. options.create_if_missing = true;
  92. options.compression = kNoCompression;
  93. options.env = env;
  94. options.disable_auto_compactions = true;
  95. if (use_direct_io) {
  96. options.use_direct_reads = true;
  97. options.use_direct_io_for_flush_and_compaction = true;
  98. }
  99. }
  100. void SetBlockBasedTableOptions(BlockBasedTableOptions& table_options) {
  101. table_options.no_block_cache = true;
  102. table_options.cache_index_and_filter_blocks = false;
  103. table_options.metadata_block_size = 1024;
  104. table_options.index_type =
  105. BlockBasedTableOptions::IndexType::kTwoLevelIndexSearch;
  106. }
  107. void VerifyScan(ReadOptions& iter_ro, ReadOptions& cmp_iter_ro,
  108. const Slice* seek_key, const Slice* iterate_upper_bound,
  109. bool prefix_same_as_start) const {
  110. assert(!(seek_key == nullptr));
  111. iter_ro.iterate_upper_bound = cmp_iter_ro.iterate_upper_bound =
  112. iterate_upper_bound;
  113. iter_ro.prefix_same_as_start = cmp_iter_ro.prefix_same_as_start =
  114. prefix_same_as_start;
  115. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(iter_ro));
  116. auto cmp_iter = std::unique_ptr<Iterator>(db_->NewIterator(cmp_iter_ro));
  117. iter->Seek(*seek_key);
  118. cmp_iter->Seek(*seek_key);
  119. while (iter->Valid() && cmp_iter->Valid()) {
  120. if (iter->key() != cmp_iter->key()) {
  121. // Error
  122. ASSERT_TRUE(false);
  123. }
  124. iter->Next();
  125. cmp_iter->Next();
  126. }
  127. ASSERT_TRUE(!cmp_iter->Valid() && !iter->Valid());
  128. ASSERT_TRUE(cmp_iter->status().ok() && iter->status().ok());
  129. }
  130. void VerifySeekPrevSeek(ReadOptions& iter_ro, ReadOptions& cmp_iter_ro,
  131. const Slice* seek_key,
  132. const Slice* iterate_upper_bound,
  133. bool prefix_same_as_start) {
  134. assert(!(seek_key == nullptr));
  135. iter_ro.iterate_upper_bound = cmp_iter_ro.iterate_upper_bound =
  136. iterate_upper_bound;
  137. iter_ro.prefix_same_as_start = cmp_iter_ro.prefix_same_as_start =
  138. prefix_same_as_start;
  139. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(iter_ro));
  140. auto cmp_iter = std::unique_ptr<Iterator>(db_->NewIterator(cmp_iter_ro));
  141. // Seek
  142. cmp_iter->Seek(*seek_key);
  143. ASSERT_TRUE(cmp_iter->Valid());
  144. ASSERT_OK(cmp_iter->status());
  145. iter->Seek(*seek_key);
  146. ASSERT_TRUE(iter->Valid());
  147. ASSERT_OK(iter->status());
  148. ASSERT_EQ(iter->key(), cmp_iter->key());
  149. // Prev op should pass
  150. cmp_iter->Prev();
  151. ASSERT_TRUE(cmp_iter->Valid());
  152. ASSERT_OK(cmp_iter->status());
  153. iter->Prev();
  154. ASSERT_TRUE(iter->Valid());
  155. ASSERT_OK(iter->status());
  156. ASSERT_EQ(iter->key(), cmp_iter->key());
  157. // Reseek would follow as usual
  158. cmp_iter->Seek(*seek_key);
  159. ASSERT_TRUE(cmp_iter->Valid());
  160. ASSERT_OK(cmp_iter->status());
  161. iter->Seek(*seek_key);
  162. ASSERT_TRUE(iter->Valid());
  163. ASSERT_OK(iter->status());
  164. ASSERT_EQ(iter->key(), cmp_iter->key());
  165. }
  166. };
  167. INSTANTIATE_TEST_CASE_P(PrefetchTest, PrefetchTest,
  168. ::testing::Combine(::testing::Bool(),
  169. ::testing::Bool()));
  170. std::string BuildKey(int num, std::string postfix = "") {
  171. return "my_key_" + std::to_string(num) + postfix;
  172. }
  173. // This test verifies the following basic functionalities of prefetching:
  174. // (1) If underline file system supports prefetch, and directIO is not enabled
  175. // make sure prefetch() is called and FilePrefetchBuffer is not used.
  176. // (2) If underline file system doesn't support prefetch, or directIO is
  177. // enabled, make sure prefetch() is not called and FilePrefetchBuffer is
  178. // used.
  179. // (3) Measure read bytes, hit and miss of SST's tail prefetching during table
  180. // open.
  181. TEST_P(PrefetchTest, Basic) {
  182. // First param is if the mockFS support_prefetch or not
  183. bool support_prefetch =
  184. std::get<0>(GetParam()) &&
  185. test::IsPrefetchSupported(env_->GetFileSystem(), dbname_);
  186. std::shared_ptr<MockFS> fs =
  187. std::make_shared<MockFS>(env_->GetFileSystem(), support_prefetch);
  188. // Second param is if directIO is enabled or not
  189. bool use_direct_io = std::get<1>(GetParam());
  190. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  191. Options options;
  192. SetGenericOptions(env.get(), use_direct_io, options);
  193. options.statistics = CreateDBStatistics();
  194. const int kNumKeys = 1100;
  195. int buff_prefetch_count = 0;
  196. SyncPoint::GetInstance()->SetCallBack("FilePrefetchBuffer::Prefetch:Start",
  197. [&](void*) { buff_prefetch_count++; });
  198. SyncPoint::GetInstance()->EnableProcessing();
  199. Status s = TryReopen(options);
  200. if (use_direct_io && (s.IsNotSupported() || s.IsInvalidArgument())) {
  201. // If direct IO is not supported, skip the test
  202. return;
  203. } else {
  204. ASSERT_OK(s);
  205. }
  206. // create first key range
  207. WriteBatch batch;
  208. for (int i = 0; i < kNumKeys; i++) {
  209. ASSERT_OK(batch.Put(BuildKey(i), "v1"));
  210. }
  211. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  212. ASSERT_OK(db_->Flush(FlushOptions()));
  213. // create second key range
  214. batch.Clear();
  215. for (int i = 0; i < kNumKeys; i++) {
  216. ASSERT_OK(batch.Put(BuildKey(i, "key2"), "v2"));
  217. }
  218. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  219. ASSERT_OK(db_->Flush(FlushOptions()));
  220. // delete second key range
  221. batch.Clear();
  222. for (int i = 0; i < kNumKeys; i++) {
  223. ASSERT_OK(batch.Delete(BuildKey(i, "key2")));
  224. }
  225. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  226. ASSERT_OK(db_->Flush(FlushOptions()));
  227. std::vector<LiveFileMetaData> metadata;
  228. db_->GetLiveFilesMetaData(&metadata);
  229. const size_t num_file = metadata.size();
  230. // To verify SST file tail prefetch (once per file) during flush output
  231. // verification
  232. if (support_prefetch && !use_direct_io) {
  233. ASSERT_TRUE(fs->IsPrefetchCalled());
  234. ASSERT_EQ(num_file, fs->GetPrefetchCount());
  235. ASSERT_EQ(0, buff_prefetch_count);
  236. fs->ClearPrefetchCount();
  237. } else {
  238. ASSERT_FALSE(fs->IsPrefetchCalled());
  239. ASSERT_EQ(buff_prefetch_count, num_file);
  240. buff_prefetch_count = 0;
  241. }
  242. // compact database
  243. std::string start_key = BuildKey(0);
  244. std::string end_key = BuildKey(kNumKeys - 1);
  245. Slice least(start_key.data(), start_key.size());
  246. Slice greatest(end_key.data(), end_key.size());
  247. HistogramData prev_table_open_prefetch_tail_read;
  248. options.statistics->histogramData(TABLE_OPEN_PREFETCH_TAIL_READ_BYTES,
  249. &prev_table_open_prefetch_tail_read);
  250. const uint64_t prev_table_open_prefetch_tail_miss =
  251. options.statistics->getTickerCount(TABLE_OPEN_PREFETCH_TAIL_MISS);
  252. const uint64_t prev_table_open_prefetch_tail_hit =
  253. options.statistics->getTickerCount(TABLE_OPEN_PREFETCH_TAIL_HIT);
  254. HistogramData pre_compaction_prefetch_bytes;
  255. options.statistics->histogramData(COMPACTION_PREFETCH_BYTES,
  256. &pre_compaction_prefetch_bytes);
  257. ASSERT_EQ(pre_compaction_prefetch_bytes.count, 0);
  258. // commenting out the line below causes the example to work correctly
  259. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &least, &greatest));
  260. HistogramData post_compaction_prefetch_bytes;
  261. options.statistics->histogramData(COMPACTION_PREFETCH_BYTES,
  262. &post_compaction_prefetch_bytes);
  263. HistogramData cur_table_open_prefetch_tail_read;
  264. options.statistics->histogramData(TABLE_OPEN_PREFETCH_TAIL_READ_BYTES,
  265. &cur_table_open_prefetch_tail_read);
  266. const uint64_t cur_table_open_prefetch_tail_miss =
  267. options.statistics->getTickerCount(TABLE_OPEN_PREFETCH_TAIL_MISS);
  268. const uint64_t cur_table_open_prefetch_tail_hit =
  269. options.statistics->getTickerCount(TABLE_OPEN_PREFETCH_TAIL_HIT);
  270. // To verify prefetch during compaction input read
  271. if (support_prefetch && !use_direct_io) {
  272. ASSERT_TRUE(fs->IsPrefetchCalled());
  273. // To rule out false positive by the SST file tail prefetch during
  274. // compaction output verification
  275. ASSERT_GT(fs->GetPrefetchCount(), 1);
  276. ASSERT_EQ(0, buff_prefetch_count);
  277. fs->ClearPrefetchCount();
  278. ASSERT_EQ(post_compaction_prefetch_bytes.count, 0);
  279. } else {
  280. ASSERT_FALSE(fs->IsPrefetchCalled());
  281. // To rule out false positive by the SST file tail prefetch during
  282. // compaction output verification
  283. ASSERT_GT(buff_prefetch_count, 1);
  284. buff_prefetch_count = 0;
  285. ASSERT_GT(cur_table_open_prefetch_tail_read.count,
  286. prev_table_open_prefetch_tail_read.count);
  287. ASSERT_GT(cur_table_open_prefetch_tail_hit,
  288. prev_table_open_prefetch_tail_hit);
  289. ASSERT_GE(cur_table_open_prefetch_tail_miss,
  290. prev_table_open_prefetch_tail_miss);
  291. ASSERT_GT(post_compaction_prefetch_bytes.count, 0);
  292. // Not an exact match due to potential roundup/down for alignment
  293. auto expected_compaction_readahead_size =
  294. Options().compaction_readahead_size;
  295. ASSERT_LE(post_compaction_prefetch_bytes.max,
  296. expected_compaction_readahead_size * 1.1);
  297. ASSERT_GE(post_compaction_prefetch_bytes.max,
  298. expected_compaction_readahead_size * 0.9);
  299. ASSERT_LE(post_compaction_prefetch_bytes.average,
  300. expected_compaction_readahead_size * 1.1);
  301. ASSERT_GE(post_compaction_prefetch_bytes.average,
  302. expected_compaction_readahead_size * 0.9);
  303. }
  304. for (bool disable_io : {false, true}) {
  305. SCOPED_TRACE("disable_io: " + std::to_string(disable_io));
  306. ReadOptions ro;
  307. if (disable_io) {
  308. // When this is set on the second iteration, all blocks should be in
  309. // block cache
  310. ro.read_tier = ReadTier::kBlockCacheTier;
  311. }
  312. // count the keys
  313. {
  314. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ro));
  315. int num_keys = 0;
  316. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  317. num_keys++;
  318. }
  319. ASSERT_OK(iter->status());
  320. ASSERT_EQ(num_keys, kNumKeys);
  321. }
  322. // To verify prefetch during user scan, when IO allowed
  323. if (disable_io) {
  324. ASSERT_FALSE(fs->IsPrefetchCalled());
  325. ASSERT_EQ(0, buff_prefetch_count);
  326. } else if (support_prefetch && !use_direct_io) {
  327. ASSERT_TRUE(fs->IsPrefetchCalled());
  328. fs->ClearPrefetchCount();
  329. ASSERT_EQ(0, buff_prefetch_count);
  330. } else {
  331. ASSERT_FALSE(fs->IsPrefetchCalled());
  332. ASSERT_GT(buff_prefetch_count, 0);
  333. buff_prefetch_count = 0;
  334. }
  335. }
  336. Close();
  337. }
  338. class PrefetchTailTest : public PrefetchTest {
  339. public:
  340. bool SupportPrefetch() const {
  341. return std::get<0>(GetParam()) &&
  342. test::IsPrefetchSupported(env_->GetFileSystem(), dbname_);
  343. }
  344. bool UseDirectIO() const { return std::get<1>(GetParam()); }
  345. bool UseFilePrefetchBuffer() const {
  346. return !SupportPrefetch() || UseDirectIO();
  347. }
  348. Env* GetEnv(bool small_buffer_alignment = false) const {
  349. std::shared_ptr<MockFS> fs = std::make_shared<MockFS>(
  350. env_->GetFileSystem(), SupportPrefetch(), small_buffer_alignment);
  351. return new CompositeEnvWrapper(env_, fs);
  352. }
  353. void SetGenericOptions(Env* env, bool use_direct_io,
  354. Options& options) override {
  355. PrefetchTest::SetGenericOptions(env, use_direct_io, options);
  356. options.statistics = CreateDBStatistics();
  357. }
  358. void SetBlockBasedTableOptions(
  359. BlockBasedTableOptions& table_options, bool partition_filters = true,
  360. uint64_t metadata_block_size =
  361. BlockBasedTableOptions().metadata_block_size,
  362. bool use_small_cache = false) {
  363. table_options.index_type = BlockBasedTableOptions::kTwoLevelIndexSearch;
  364. table_options.partition_filters = partition_filters;
  365. if (table_options.partition_filters) {
  366. table_options.filter_policy.reset(NewBloomFilterPolicy(10, false));
  367. }
  368. table_options.metadata_block_size = metadata_block_size;
  369. if (use_small_cache) {
  370. LRUCacheOptions co;
  371. co.capacity = 1;
  372. std::shared_ptr<Cache> cache = NewLRUCache(co);
  373. table_options.block_cache = cache;
  374. }
  375. }
  376. int64_t GetNumIndexPartition() const {
  377. int64_t index_partition_counts = 0;
  378. TablePropertiesCollection all_table_props;
  379. assert(db_->GetPropertiesOfAllTables(&all_table_props).ok());
  380. for (const auto& name_and_table_props : all_table_props) {
  381. const auto& table_props = name_and_table_props.second;
  382. index_partition_counts += table_props->index_partitions;
  383. }
  384. return index_partition_counts;
  385. }
  386. };
  387. INSTANTIATE_TEST_CASE_P(PrefetchTailTest, PrefetchTailTest,
  388. ::testing::Combine(::testing::Bool(),
  389. ::testing::Bool()));
  390. TEST_P(PrefetchTailTest, Basic) {
  391. std::unique_ptr<Env> env(GetEnv());
  392. Options options;
  393. SetGenericOptions(env.get(), UseDirectIO(), options);
  394. BlockBasedTableOptions bbto;
  395. SetBlockBasedTableOptions(bbto);
  396. options.table_factory.reset(NewBlockBasedTableFactory(bbto));
  397. Status s = TryReopen(options);
  398. if (UseDirectIO() && (s.IsNotSupported() || s.IsInvalidArgument())) {
  399. // If direct IO is not supported, skip the test
  400. ROCKSDB_GTEST_BYPASS("Direct IO is not supported");
  401. return;
  402. } else {
  403. ASSERT_OK(s);
  404. }
  405. ASSERT_OK(Put("k1", "v1"));
  406. HistogramData pre_flush_file_read;
  407. options.statistics->histogramData(FILE_READ_FLUSH_MICROS,
  408. &pre_flush_file_read);
  409. ASSERT_OK(Flush());
  410. HistogramData post_flush_file_read;
  411. options.statistics->histogramData(FILE_READ_FLUSH_MICROS,
  412. &post_flush_file_read);
  413. if (UseFilePrefetchBuffer()) {
  414. // `PartitionedFilterBlockReader/PartitionIndexReader::CacheDependencies()`
  415. // should read from the prefetched tail in file prefetch buffer instead of
  416. // initiating extra SST reads. Therefore `BlockBasedTable::PrefetchTail()`
  417. // should be the only SST read in table verification during flush.
  418. ASSERT_EQ(post_flush_file_read.count - pre_flush_file_read.count, 1);
  419. } else {
  420. // Without the prefetched tail in file prefetch buffer,
  421. // `PartitionedFilterBlockReader/PartitionIndexReader::CacheDependencies()`
  422. // will initiate extra SST reads
  423. ASSERT_GT(post_flush_file_read.count - pre_flush_file_read.count, 1);
  424. }
  425. ASSERT_OK(Put("k1", "v2"));
  426. ASSERT_OK(Put("k2", "v2"));
  427. ASSERT_OK(Flush());
  428. CompactRangeOptions cro;
  429. HistogramData pre_compaction_file_read;
  430. options.statistics->histogramData(FILE_READ_COMPACTION_MICROS,
  431. &pre_compaction_file_read);
  432. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  433. HistogramData post_compaction_file_read;
  434. options.statistics->histogramData(FILE_READ_COMPACTION_MICROS,
  435. &post_compaction_file_read);
  436. if (UseFilePrefetchBuffer()) {
  437. // `PartitionedFilterBlockReader/PartitionIndexReader::CacheDependencies()`
  438. // should read from the prefetched tail in file prefetch buffer instead of
  439. // initiating extra SST reads.
  440. //
  441. // Therefore the 3 reads are
  442. // (1) `ProcessKeyValueCompaction()` of input file 1
  443. // (2) `ProcessKeyValueCompaction()` of input file 2
  444. // (3) `BlockBasedTable::PrefetchTail()` of output file during table
  445. // verification in compaction
  446. ASSERT_EQ(post_compaction_file_read.count - pre_compaction_file_read.count,
  447. 3);
  448. } else {
  449. // Without the prefetched tail in file prefetch buffer,
  450. // `PartitionedFilterBlockReader/PartitionIndexReader::CacheDependencies()`
  451. // as well as reading other parts of the tail (e.g, footer, table
  452. // properties..) will initiate extra SST reads
  453. ASSERT_GT(post_compaction_file_read.count - pre_compaction_file_read.count,
  454. 3);
  455. }
  456. Close();
  457. }
  458. TEST_P(PrefetchTailTest, UpgradeToTailSizeInManifest) {
  459. if (!UseFilePrefetchBuffer()) {
  460. ROCKSDB_GTEST_BYPASS(
  461. "Upgrade to tail size in manifest is only relevant when RocksDB file "
  462. "prefetch buffer is used.");
  463. }
  464. if (UseDirectIO()) {
  465. ROCKSDB_GTEST_BYPASS(
  466. "To simplify testing logics with setting file's buffer alignment to "
  467. "be "
  468. "1, direct IO is required to be disabled.");
  469. }
  470. std::unique_ptr<Env> env(GetEnv(true /* small_buffer_alignment */));
  471. Options options;
  472. SetGenericOptions(env.get(), false /* use_direct_io*/, options);
  473. options.max_open_files = -1;
  474. options.write_buffer_size = 1024 * 1024;
  475. BlockBasedTableOptions table_options;
  476. SetBlockBasedTableOptions(table_options, false /* partition_filters */,
  477. 1 /* metadata_block_size*/,
  478. true /* use_small_cache */);
  479. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  480. SyncPoint::GetInstance()->EnableProcessing();
  481. // To simulate a pre-upgrade DB where file tail size is not recorded in
  482. // manifest
  483. SyncPoint::GetInstance()->SetCallBack(
  484. "FileMetaData::FileMetaData", [&](void* arg) {
  485. FileMetaData* meta = static_cast<FileMetaData*>(arg);
  486. meta->tail_size = 0;
  487. });
  488. ASSERT_OK(TryReopen(options));
  489. for (int i = 0; i < 10000; ++i) {
  490. ASSERT_OK(Put("k" + std::to_string(i), "v"));
  491. }
  492. ASSERT_OK(Flush());
  493. SyncPoint::GetInstance()->ClearAllCallBacks();
  494. // To simulate a DB undergoing the upgrade where tail size to prefetch is
  495. // inferred to be a small number for files with no tail size recorded in
  496. // manifest.
  497. // "1" is chosen to be such number so that with `small_buffer_alignment ==
  498. // true` and `use_small_cache == true`, it would have caused one file read
  499. // per index partition during db open if the upgrade is done wrong.
  500. SyncPoint::GetInstance()->SetCallBack(
  501. "BlockBasedTable::Open::TailPrefetchLen", [&](void* arg) {
  502. std::pair<size_t*, size_t*>* prefetch_off_len_pair =
  503. static_cast<std::pair<size_t*, size_t*>*>(arg);
  504. size_t* prefetch_off = prefetch_off_len_pair->first;
  505. size_t* tail_size = prefetch_off_len_pair->second;
  506. const size_t file_size = *prefetch_off + *tail_size;
  507. *tail_size = 1;
  508. *prefetch_off = file_size - (*tail_size);
  509. });
  510. ASSERT_OK(TryReopen(options));
  511. SyncPoint::GetInstance()->ClearAllCallBacks();
  512. SyncPoint::GetInstance()->DisableProcessing();
  513. HistogramData db_open_file_read;
  514. options.statistics->histogramData(FILE_READ_DB_OPEN_MICROS,
  515. &db_open_file_read);
  516. int64_t num_index_partition = GetNumIndexPartition();
  517. // If the upgrade is done right, db open will prefetch all the index
  518. // partitions at once, instead of doing one read per partition.
  519. // That is, together with `metadata_block_size == 1`, there will be more
  520. // index partitions than number of non index partitions reads.
  521. ASSERT_LT(db_open_file_read.count, num_index_partition);
  522. Close();
  523. }
  524. // This test verifies BlockBasedTableOptions.max_auto_readahead_size is
  525. // configured dynamically.
  526. TEST_P(PrefetchTest, ConfigureAutoMaxReadaheadSize) {
  527. // First param is if the mockFS support_prefetch or not
  528. bool support_prefetch =
  529. std::get<0>(GetParam()) &&
  530. test::IsPrefetchSupported(env_->GetFileSystem(), dbname_);
  531. std::shared_ptr<MockFS> fs =
  532. std::make_shared<MockFS>(env_->GetFileSystem(), support_prefetch);
  533. // Second param is if directIO is enabled or not
  534. bool use_direct_io = std::get<1>(GetParam());
  535. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  536. Options options;
  537. SetGenericOptions(env.get(), use_direct_io, options);
  538. BlockBasedTableOptions table_options;
  539. SetBlockBasedTableOptions(table_options);
  540. table_options.max_auto_readahead_size = 0;
  541. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  542. int buff_prefetch_count = 0;
  543. SyncPoint::GetInstance()->SetCallBack("FilePrefetchBuffer::Prefetch:Start",
  544. [&](void*) { buff_prefetch_count++; });
  545. // DB open will create table readers unless we reduce the table cache
  546. // capacity. SanitizeOptions will set max_open_files to minimum of 20. Table
  547. // cache is allocated with max_open_files - 10 as capacity. So override
  548. // max_open_files to 10 so table cache capacity will become 0. This will
  549. // prevent file open during DB open and force the file to be opened during
  550. // Iteration.
  551. SyncPoint::GetInstance()->SetCallBack(
  552. "SanitizeOptions::AfterChangeMaxOpenFiles", [&](void* arg) {
  553. int* max_open_files = (int*)arg;
  554. *max_open_files = 11;
  555. });
  556. SyncPoint::GetInstance()->EnableProcessing();
  557. Status s = TryReopen(options);
  558. if (use_direct_io && (s.IsNotSupported() || s.IsInvalidArgument())) {
  559. // If direct IO is not supported, skip the test
  560. return;
  561. } else {
  562. ASSERT_OK(s);
  563. }
  564. Random rnd(309);
  565. int key_count = 0;
  566. const int num_keys_per_level = 100;
  567. // Level 0 : Keys in range [0, 99], Level 1:[100, 199], Level 2:[200, 299].
  568. for (int level = 2; level >= 0; level--) {
  569. key_count = level * num_keys_per_level;
  570. for (int i = 0; i < num_keys_per_level; ++i) {
  571. ASSERT_OK(Put(Key(key_count++), rnd.RandomString(500)));
  572. }
  573. ASSERT_OK(Flush());
  574. MoveFilesToLevel(level);
  575. }
  576. Close();
  577. std::vector<int> buff_prefectch_level_count = {0, 0, 0};
  578. ASSERT_OK(TryReopen(options));
  579. {
  580. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ReadOptions()));
  581. fs->ClearPrefetchCount();
  582. buff_prefetch_count = 0;
  583. for (int level = 2; level >= 0; level--) {
  584. key_count = level * num_keys_per_level;
  585. switch (level) {
  586. case 0:
  587. // max_auto_readahead_size is set 0 so data and index blocks are not
  588. // prefetched.
  589. ASSERT_OK(db_->SetOptions(
  590. {{"block_based_table_factory", "{max_auto_readahead_size=0;}"}}));
  591. break;
  592. case 1:
  593. // max_auto_readahead_size is set less than
  594. // initial_auto_readahead_size. So readahead_size remains equal to
  595. // max_auto_readahead_size.
  596. ASSERT_OK(db_->SetOptions({{"block_based_table_factory",
  597. "{max_auto_readahead_size=4096;}"}}));
  598. break;
  599. case 2:
  600. ASSERT_OK(db_->SetOptions({{"block_based_table_factory",
  601. "{max_auto_readahead_size=65536;}"}}));
  602. break;
  603. default:
  604. assert(false);
  605. }
  606. ASSERT_OK(iter->status());
  607. ASSERT_OK(iter->Refresh()); // Update to latest mutable options
  608. for (int i = 0; i < num_keys_per_level; ++i) {
  609. iter->Seek(Key(key_count++));
  610. iter->Next();
  611. }
  612. buff_prefectch_level_count[level] = buff_prefetch_count;
  613. if (support_prefetch && !use_direct_io) {
  614. if (level == 0) {
  615. ASSERT_FALSE(fs->IsPrefetchCalled());
  616. } else {
  617. ASSERT_TRUE(fs->IsPrefetchCalled());
  618. }
  619. fs->ClearPrefetchCount();
  620. } else {
  621. ASSERT_FALSE(fs->IsPrefetchCalled());
  622. if (level == 0) {
  623. ASSERT_EQ(buff_prefetch_count, 0);
  624. } else {
  625. ASSERT_GT(buff_prefetch_count, 0);
  626. }
  627. buff_prefetch_count = 0;
  628. }
  629. }
  630. }
  631. if (!support_prefetch) {
  632. ASSERT_GT(buff_prefectch_level_count[1], buff_prefectch_level_count[2]);
  633. }
  634. SyncPoint::GetInstance()->DisableProcessing();
  635. SyncPoint::GetInstance()->ClearAllCallBacks();
  636. Close();
  637. }
  638. // This test verifies BlockBasedTableOptions.initial_auto_readahead_size is
  639. // configured dynamically.
  640. TEST_P(PrefetchTest, ConfigureInternalAutoReadaheadSize) {
  641. // First param is if the mockFS support_prefetch or not
  642. bool support_prefetch =
  643. std::get<0>(GetParam()) &&
  644. test::IsPrefetchSupported(env_->GetFileSystem(), dbname_);
  645. // Second param is if directIO is enabled or not
  646. bool use_direct_io = std::get<1>(GetParam());
  647. std::shared_ptr<MockFS> fs =
  648. std::make_shared<MockFS>(env_->GetFileSystem(), support_prefetch);
  649. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  650. Options options;
  651. SetGenericOptions(env.get(), use_direct_io, options);
  652. BlockBasedTableOptions table_options;
  653. SetBlockBasedTableOptions(table_options);
  654. table_options.initial_auto_readahead_size = 0;
  655. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  656. int buff_prefetch_count = 0;
  657. // DB open will create table readers unless we reduce the table cache
  658. // capacity. SanitizeOptions will set max_open_files to minimum of 20.
  659. // Table cache is allocated with max_open_files - 10 as capacity. So
  660. // override max_open_files to 10 so table cache capacity will become 0.
  661. // This will prevent file open during DB open and force the file to be
  662. // opened during Iteration.
  663. SyncPoint::GetInstance()->SetCallBack(
  664. "SanitizeOptions::AfterChangeMaxOpenFiles", [&](void* arg) {
  665. int* max_open_files = (int*)arg;
  666. *max_open_files = 11;
  667. });
  668. SyncPoint::GetInstance()->SetCallBack("FilePrefetchBuffer::Prefetch:Start",
  669. [&](void*) { buff_prefetch_count++; });
  670. SyncPoint::GetInstance()->EnableProcessing();
  671. Status s = TryReopen(options);
  672. if (use_direct_io && (s.IsNotSupported() || s.IsInvalidArgument())) {
  673. // If direct IO is not supported, skip the test
  674. return;
  675. } else {
  676. ASSERT_OK(s);
  677. }
  678. Random rnd(309);
  679. int key_count = 0;
  680. const int num_keys_per_level = 100;
  681. // Level 0 : Keys in range [0, 99], Level 1:[100, 199], Level 2:[200, 299].
  682. for (int level = 2; level >= 0; level--) {
  683. key_count = level * num_keys_per_level;
  684. for (int i = 0; i < num_keys_per_level; ++i) {
  685. ASSERT_OK(Put(Key(key_count++), rnd.RandomString(500)));
  686. }
  687. ASSERT_OK(Flush());
  688. MoveFilesToLevel(level);
  689. }
  690. Close();
  691. ASSERT_OK(TryReopen(options));
  692. {
  693. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ReadOptions()));
  694. fs->ClearPrefetchCount();
  695. buff_prefetch_count = 0;
  696. std::vector<int> buff_prefetch_level_count = {0, 0, 0};
  697. for (int level = 2; level >= 0; level--) {
  698. key_count = level * num_keys_per_level;
  699. switch (level) {
  700. case 0:
  701. // initial_auto_readahead_size is set 0 so data and index blocks are
  702. // not prefetched.
  703. ASSERT_OK(db_->SetOptions({{"block_based_table_factory",
  704. "{initial_auto_readahead_size=0;}"}}));
  705. break;
  706. case 1:
  707. // intial_auto_readahead_size and max_auto_readahead_size are set
  708. // same so readahead_size remains same.
  709. ASSERT_OK(db_->SetOptions({{"block_based_table_factory",
  710. "{initial_auto_readahead_size=4096;max_"
  711. "auto_readahead_size=4096;}"}}));
  712. break;
  713. case 2:
  714. ASSERT_OK(
  715. db_->SetOptions({{"block_based_table_factory",
  716. "{initial_auto_readahead_size=65536;}"}}));
  717. break;
  718. default:
  719. assert(false);
  720. }
  721. ASSERT_OK(iter->status());
  722. ASSERT_OK(iter->Refresh()); // Update to latest mutable options
  723. for (int i = 0; i < num_keys_per_level; ++i) {
  724. iter->Seek(Key(key_count++));
  725. iter->Next();
  726. }
  727. ASSERT_OK(iter->status());
  728. buff_prefetch_level_count[level] = buff_prefetch_count;
  729. if (support_prefetch && !use_direct_io) {
  730. if (level == 0) {
  731. ASSERT_FALSE(fs->IsPrefetchCalled());
  732. } else {
  733. ASSERT_TRUE(fs->IsPrefetchCalled());
  734. }
  735. fs->ClearPrefetchCount();
  736. } else {
  737. ASSERT_FALSE(fs->IsPrefetchCalled());
  738. if (level == 0) {
  739. ASSERT_EQ(buff_prefetch_count, 0);
  740. } else {
  741. ASSERT_GT(buff_prefetch_count, 0);
  742. }
  743. buff_prefetch_count = 0;
  744. }
  745. }
  746. if (!support_prefetch) {
  747. ASSERT_GT(buff_prefetch_level_count[1], buff_prefetch_level_count[2]);
  748. }
  749. }
  750. SyncPoint::GetInstance()->DisableProcessing();
  751. SyncPoint::GetInstance()->ClearAllCallBacks();
  752. Close();
  753. }
  754. // This test verifies BlockBasedTableOptions.num_file_reads_for_auto_readahead
  755. // is configured dynamically.
  756. TEST_P(PrefetchTest, ConfigureNumFilesReadsForReadaheadSize) {
  757. // First param is if the mockFS support_prefetch or not
  758. bool support_prefetch =
  759. std::get<0>(GetParam()) &&
  760. test::IsPrefetchSupported(env_->GetFileSystem(), dbname_);
  761. const int kNumKeys = 2000;
  762. std::shared_ptr<MockFS> fs =
  763. std::make_shared<MockFS>(env_->GetFileSystem(), support_prefetch);
  764. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  765. // Second param is if directIO is enabled or not
  766. bool use_direct_io = std::get<1>(GetParam());
  767. Options options;
  768. SetGenericOptions(env.get(), use_direct_io, options);
  769. BlockBasedTableOptions table_options;
  770. SetBlockBasedTableOptions(table_options);
  771. table_options.num_file_reads_for_auto_readahead = 0;
  772. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  773. int buff_prefetch_count = 0;
  774. SyncPoint::GetInstance()->SetCallBack("FilePrefetchBuffer::Prefetch:Start",
  775. [&](void*) { buff_prefetch_count++; });
  776. SyncPoint::GetInstance()->EnableProcessing();
  777. Status s = TryReopen(options);
  778. if (use_direct_io && (s.IsNotSupported() || s.IsInvalidArgument())) {
  779. // If direct IO is not supported, skip the test
  780. return;
  781. } else {
  782. ASSERT_OK(s);
  783. }
  784. WriteBatch batch;
  785. Random rnd(309);
  786. for (int i = 0; i < kNumKeys; i++) {
  787. ASSERT_OK(batch.Put(BuildKey(i), rnd.RandomString(1000)));
  788. }
  789. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  790. std::string start_key = BuildKey(0);
  791. std::string end_key = BuildKey(kNumKeys - 1);
  792. Slice least(start_key.data(), start_key.size());
  793. Slice greatest(end_key.data(), end_key.size());
  794. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &least, &greatest));
  795. Close();
  796. ASSERT_OK(TryReopen(options));
  797. fs->ClearPrefetchCount();
  798. buff_prefetch_count = 0;
  799. {
  800. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ReadOptions()));
  801. /*
  802. * Reseek keys from sequential Data Blocks within same partitioned
  803. * index. It will prefetch the data block at the first seek since
  804. * num_file_reads_for_auto_readahead = 0. Data Block size is nearly 4076
  805. * so readahead will fetch 8 * 1024 data more initially (2 more data
  806. * blocks).
  807. */
  808. iter->Seek(BuildKey(0)); // Prefetch data + index block since
  809. // num_file_reads_for_auto_readahead = 0.
  810. ASSERT_TRUE(iter->Valid());
  811. iter->Seek(BuildKey(1000)); // In buffer
  812. ASSERT_TRUE(iter->Valid());
  813. iter->Seek(BuildKey(1004)); // In buffer
  814. ASSERT_TRUE(iter->Valid());
  815. iter->Seek(BuildKey(1008)); // Prefetch Data
  816. ASSERT_TRUE(iter->Valid());
  817. iter->Seek(BuildKey(1011)); // In buffer
  818. ASSERT_TRUE(iter->Valid());
  819. iter->Seek(BuildKey(1015)); // In buffer
  820. ASSERT_TRUE(iter->Valid());
  821. iter->Seek(BuildKey(1019)); // In buffer
  822. ASSERT_TRUE(iter->Valid());
  823. // Missed 2 blocks but they are already in buffer so no reset.
  824. iter->Seek(BuildKey(103)); // Already in buffer.
  825. ASSERT_TRUE(iter->Valid());
  826. iter->Seek(BuildKey(1033)); // Prefetch Data.
  827. ASSERT_TRUE(iter->Valid());
  828. if (support_prefetch && !use_direct_io) {
  829. ASSERT_EQ(fs->GetPrefetchCount(), 4);
  830. fs->ClearPrefetchCount();
  831. } else {
  832. ASSERT_EQ(buff_prefetch_count, 4);
  833. buff_prefetch_count = 0;
  834. }
  835. }
  836. SyncPoint::GetInstance()->DisableProcessing();
  837. SyncPoint::GetInstance()->ClearAllCallBacks();
  838. Close();
  839. }
  840. // This test verifies the basic functionality of implicit autoreadahead:
  841. // - Enable implicit autoreadahead and prefetch only if sequential blocks are
  842. // read,
  843. // - If data is already in buffer and few blocks are not requested to read,
  844. // don't reset,
  845. // - If data blocks are sequential during read after enabling implicit
  846. // autoreadahead, reset readahead parameters.
  847. TEST_P(PrefetchTest, PrefetchWhenReseek) {
  848. // First param is if the mockFS support_prefetch or not
  849. bool support_prefetch =
  850. std::get<0>(GetParam()) &&
  851. test::IsPrefetchSupported(env_->GetFileSystem(), dbname_);
  852. const int kNumKeys = 2000;
  853. std::shared_ptr<MockFS> fs =
  854. std::make_shared<MockFS>(env_->GetFileSystem(), support_prefetch);
  855. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  856. // Second param is if directIO is enabled or not
  857. bool use_direct_io = std::get<1>(GetParam());
  858. Options options;
  859. SetGenericOptions(env.get(), use_direct_io, options);
  860. BlockBasedTableOptions table_options;
  861. SetBlockBasedTableOptions(table_options);
  862. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  863. int buff_prefetch_count = 0;
  864. SyncPoint::GetInstance()->SetCallBack("FilePrefetchBuffer::Prefetch:Start",
  865. [&](void*) { buff_prefetch_count++; });
  866. SyncPoint::GetInstance()->EnableProcessing();
  867. Status s = TryReopen(options);
  868. if (use_direct_io && (s.IsNotSupported() || s.IsInvalidArgument())) {
  869. // If direct IO is not supported, skip the test
  870. return;
  871. } else {
  872. ASSERT_OK(s);
  873. }
  874. WriteBatch batch;
  875. Random rnd(309);
  876. for (int i = 0; i < kNumKeys; i++) {
  877. ASSERT_OK(batch.Put(BuildKey(i), rnd.RandomString(1000)));
  878. }
  879. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  880. std::string start_key = BuildKey(0);
  881. std::string end_key = BuildKey(kNumKeys - 1);
  882. Slice least(start_key.data(), start_key.size());
  883. Slice greatest(end_key.data(), end_key.size());
  884. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &least, &greatest));
  885. fs->ClearPrefetchCount();
  886. buff_prefetch_count = 0;
  887. {
  888. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ReadOptions()));
  889. /*
  890. * Reseek keys from sequential Data Blocks within same partitioned
  891. * index. After 2 sequential reads it will prefetch the data block.
  892. * Data Block size is nearly 4076 so readahead will fetch 8 * 1024 data
  893. * more initially (2 more data blocks).
  894. */
  895. iter->Seek(BuildKey(0));
  896. ASSERT_TRUE(iter->Valid());
  897. iter->Seek(BuildKey(1000));
  898. ASSERT_TRUE(iter->Valid());
  899. iter->Seek(BuildKey(1004)); // Prefetch Data
  900. ASSERT_TRUE(iter->Valid());
  901. iter->Seek(BuildKey(1008));
  902. ASSERT_TRUE(iter->Valid());
  903. iter->Seek(BuildKey(1011));
  904. ASSERT_TRUE(iter->Valid());
  905. iter->Seek(BuildKey(1015)); // Prefetch Data
  906. ASSERT_TRUE(iter->Valid());
  907. iter->Seek(BuildKey(1019));
  908. ASSERT_TRUE(iter->Valid());
  909. // Missed 2 blocks but they are already in buffer so no reset.
  910. iter->Seek(BuildKey(103)); // Already in buffer.
  911. ASSERT_TRUE(iter->Valid());
  912. iter->Seek(BuildKey(1033)); // Prefetch Data
  913. ASSERT_TRUE(iter->Valid());
  914. if (support_prefetch && !use_direct_io) {
  915. ASSERT_EQ(fs->GetPrefetchCount(), 3);
  916. fs->ClearPrefetchCount();
  917. } else {
  918. ASSERT_EQ(buff_prefetch_count, 3);
  919. buff_prefetch_count = 0;
  920. }
  921. }
  922. {
  923. /*
  924. * Reseek keys from non sequential data blocks within same partitioned
  925. * index. buff_prefetch_count will be 0 in that case.
  926. */
  927. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ReadOptions()));
  928. iter->Seek(BuildKey(0));
  929. ASSERT_TRUE(iter->Valid());
  930. iter->Seek(BuildKey(1008));
  931. ASSERT_TRUE(iter->Valid());
  932. iter->Seek(BuildKey(1019));
  933. ASSERT_TRUE(iter->Valid());
  934. iter->Seek(BuildKey(1033));
  935. ASSERT_TRUE(iter->Valid());
  936. iter->Seek(BuildKey(1048));
  937. ASSERT_TRUE(iter->Valid());
  938. if (support_prefetch && !use_direct_io) {
  939. ASSERT_EQ(fs->GetPrefetchCount(), 0);
  940. fs->ClearPrefetchCount();
  941. } else {
  942. ASSERT_EQ(buff_prefetch_count, 0);
  943. buff_prefetch_count = 0;
  944. }
  945. }
  946. {
  947. /*
  948. * Reesek keys from Single Data Block.
  949. */
  950. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ReadOptions()));
  951. iter->Seek(BuildKey(0));
  952. ASSERT_TRUE(iter->Valid());
  953. iter->Seek(BuildKey(1));
  954. ASSERT_TRUE(iter->Valid());
  955. iter->Seek(BuildKey(10));
  956. ASSERT_TRUE(iter->Valid());
  957. iter->Seek(BuildKey(100));
  958. ASSERT_TRUE(iter->Valid());
  959. if (support_prefetch && !use_direct_io) {
  960. ASSERT_EQ(fs->GetPrefetchCount(), 0);
  961. fs->ClearPrefetchCount();
  962. } else {
  963. ASSERT_EQ(buff_prefetch_count, 0);
  964. buff_prefetch_count = 0;
  965. }
  966. }
  967. {
  968. /*
  969. * Reseek keys from sequential data blocks to set implicit auto readahead
  970. * and prefetch data but after that iterate over different (non
  971. * sequential) data blocks which won't prefetch any data further. So
  972. * buff_prefetch_count will be 1 for the first one.
  973. */
  974. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ReadOptions()));
  975. iter->Seek(BuildKey(0));
  976. ASSERT_TRUE(iter->Valid());
  977. iter->Seek(BuildKey(1000));
  978. ASSERT_TRUE(iter->Valid());
  979. iter->Seek(BuildKey(1004)); // This iteration will prefetch buffer
  980. ASSERT_TRUE(iter->Valid());
  981. iter->Seek(BuildKey(1008));
  982. ASSERT_TRUE(iter->Valid());
  983. iter->Seek(
  984. BuildKey(996)); // Reseek won't prefetch any data and
  985. // readahead_size will be initiallized to 8*1024.
  986. ASSERT_TRUE(iter->Valid());
  987. iter->Seek(BuildKey(992));
  988. ASSERT_TRUE(iter->Valid());
  989. iter->Seek(BuildKey(989));
  990. ASSERT_TRUE(iter->Valid());
  991. if (support_prefetch && !use_direct_io) {
  992. ASSERT_EQ(fs->GetPrefetchCount(), 1);
  993. fs->ClearPrefetchCount();
  994. } else {
  995. ASSERT_EQ(buff_prefetch_count, 1);
  996. buff_prefetch_count = 0;
  997. }
  998. // Read sequentially to confirm readahead_size is reset to initial value
  999. // (2 more data blocks)
  1000. iter->Seek(BuildKey(1011));
  1001. ASSERT_TRUE(iter->Valid());
  1002. iter->Seek(BuildKey(1015));
  1003. ASSERT_TRUE(iter->Valid());
  1004. iter->Seek(BuildKey(1019)); // Prefetch Data
  1005. ASSERT_TRUE(iter->Valid());
  1006. iter->Seek(BuildKey(1022));
  1007. ASSERT_TRUE(iter->Valid());
  1008. iter->Seek(BuildKey(1026));
  1009. ASSERT_TRUE(iter->Valid());
  1010. iter->Seek(BuildKey(103)); // Prefetch Data
  1011. ASSERT_TRUE(iter->Valid());
  1012. if (support_prefetch && !use_direct_io) {
  1013. ASSERT_EQ(fs->GetPrefetchCount(), 2);
  1014. fs->ClearPrefetchCount();
  1015. } else {
  1016. ASSERT_EQ(buff_prefetch_count, 2);
  1017. buff_prefetch_count = 0;
  1018. }
  1019. }
  1020. {
  1021. /* Reseek keys from sequential partitioned index block. Since partitioned
  1022. * index fetch are sequential, buff_prefetch_count will be 1.
  1023. */
  1024. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ReadOptions()));
  1025. iter->Seek(BuildKey(0));
  1026. ASSERT_TRUE(iter->Valid());
  1027. iter->Seek(BuildKey(1167));
  1028. ASSERT_TRUE(iter->Valid());
  1029. iter->Seek(BuildKey(1334)); // This iteration will prefetch buffer
  1030. ASSERT_TRUE(iter->Valid());
  1031. iter->Seek(BuildKey(1499));
  1032. ASSERT_TRUE(iter->Valid());
  1033. iter->Seek(BuildKey(1667));
  1034. ASSERT_TRUE(iter->Valid());
  1035. iter->Seek(BuildKey(1847));
  1036. ASSERT_TRUE(iter->Valid());
  1037. iter->Seek(BuildKey(1999));
  1038. ASSERT_TRUE(iter->Valid());
  1039. if (support_prefetch && !use_direct_io) {
  1040. ASSERT_EQ(fs->GetPrefetchCount(), 1);
  1041. fs->ClearPrefetchCount();
  1042. } else {
  1043. ASSERT_EQ(buff_prefetch_count, 1);
  1044. buff_prefetch_count = 0;
  1045. }
  1046. }
  1047. {
  1048. /*
  1049. * Reseek over different keys from different blocks. buff_prefetch_count
  1050. * is set 0.
  1051. */
  1052. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ReadOptions()));
  1053. int i = 0;
  1054. int j = 1000;
  1055. do {
  1056. iter->Seek(BuildKey(i));
  1057. if (!iter->Valid()) {
  1058. ASSERT_OK(iter->status());
  1059. break;
  1060. }
  1061. i = i + 100;
  1062. iter->Seek(BuildKey(j));
  1063. j = j + 100;
  1064. } while (i < 1000 && j < kNumKeys && iter->Valid());
  1065. if (support_prefetch && !use_direct_io) {
  1066. ASSERT_EQ(fs->GetPrefetchCount(), 0);
  1067. fs->ClearPrefetchCount();
  1068. } else {
  1069. ASSERT_EQ(buff_prefetch_count, 0);
  1070. buff_prefetch_count = 0;
  1071. }
  1072. }
  1073. {
  1074. /* Iterates sequentially over all keys. It will prefetch the buffer.*/
  1075. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ReadOptions()));
  1076. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  1077. }
  1078. ASSERT_OK(iter->status());
  1079. if (support_prefetch && !use_direct_io) {
  1080. ASSERT_EQ(fs->GetPrefetchCount(), 13);
  1081. fs->ClearPrefetchCount();
  1082. } else {
  1083. ASSERT_EQ(buff_prefetch_count, 13);
  1084. buff_prefetch_count = 0;
  1085. }
  1086. }
  1087. SyncPoint::GetInstance()->DisableProcessing();
  1088. SyncPoint::GetInstance()->ClearAllCallBacks();
  1089. Close();
  1090. }
  1091. // This test verifies the functionality of implicit autoreadahead when caching
  1092. // is enabled:
  1093. // - If data is already in buffer and few blocks are not requested to read,
  1094. // don't reset,
  1095. // - If block was eligible for prefetching/in buffer but found in cache, don't
  1096. // prefetch and reset.
  1097. TEST_P(PrefetchTest, PrefetchWhenReseekwithCache) {
  1098. // First param is if the mockFS support_prefetch or not
  1099. bool support_prefetch =
  1100. std::get<0>(GetParam()) &&
  1101. test::IsPrefetchSupported(env_->GetFileSystem(), dbname_);
  1102. const int kNumKeys = 2000;
  1103. std::shared_ptr<MockFS> fs =
  1104. std::make_shared<MockFS>(env_->GetFileSystem(), support_prefetch);
  1105. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  1106. // Second param is if directIO is enabled or not
  1107. bool use_direct_io = std::get<1>(GetParam());
  1108. Options options;
  1109. SetGenericOptions(env.get(), use_direct_io, options);
  1110. BlockBasedTableOptions table_options;
  1111. SetBlockBasedTableOptions(table_options);
  1112. std::shared_ptr<Cache> cache = NewLRUCache(4 * 1024 * 1024, 2); // 8MB
  1113. table_options.block_cache = cache;
  1114. table_options.no_block_cache = false;
  1115. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1116. int buff_prefetch_count = 0;
  1117. SyncPoint::GetInstance()->SetCallBack("FilePrefetchBuffer::Prefetch:Start",
  1118. [&](void*) { buff_prefetch_count++; });
  1119. SyncPoint::GetInstance()->EnableProcessing();
  1120. Status s = TryReopen(options);
  1121. if (use_direct_io && (s.IsNotSupported() || s.IsInvalidArgument())) {
  1122. // If direct IO is not supported, skip the test
  1123. return;
  1124. } else {
  1125. ASSERT_OK(s);
  1126. }
  1127. WriteBatch batch;
  1128. Random rnd(309);
  1129. for (int i = 0; i < kNumKeys; i++) {
  1130. ASSERT_OK(batch.Put(BuildKey(i), rnd.RandomString(1000)));
  1131. }
  1132. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  1133. std::string start_key = BuildKey(0);
  1134. std::string end_key = BuildKey(kNumKeys - 1);
  1135. Slice least(start_key.data(), start_key.size());
  1136. Slice greatest(end_key.data(), end_key.size());
  1137. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &least, &greatest));
  1138. fs->ClearPrefetchCount();
  1139. buff_prefetch_count = 0;
  1140. {
  1141. /*
  1142. * Reseek keys from sequential Data Blocks within same partitioned
  1143. * index. After 2 sequential reads it will prefetch the data block.
  1144. * Data Block size is nearly 4076 so readahead will fetch 8 * 1024 data
  1145. * more initially (2 more data blocks).
  1146. */
  1147. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ReadOptions()));
  1148. // Warm up the cache
  1149. iter->Seek(BuildKey(1011));
  1150. ASSERT_TRUE(iter->Valid());
  1151. iter->Seek(BuildKey(1015));
  1152. ASSERT_TRUE(iter->Valid());
  1153. iter->Seek(BuildKey(1019));
  1154. ASSERT_TRUE(iter->Valid());
  1155. if (support_prefetch && !use_direct_io) {
  1156. ASSERT_EQ(fs->GetPrefetchCount(), 1);
  1157. fs->ClearPrefetchCount();
  1158. } else {
  1159. ASSERT_EQ(buff_prefetch_count, 1);
  1160. buff_prefetch_count = 0;
  1161. }
  1162. }
  1163. {
  1164. // After caching, blocks will be read from cache (Sequential blocks)
  1165. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ReadOptions()));
  1166. iter->Seek(BuildKey(0));
  1167. ASSERT_TRUE(iter->Valid());
  1168. iter->Seek(BuildKey(1000));
  1169. ASSERT_TRUE(iter->Valid());
  1170. iter->Seek(BuildKey(1004)); // Prefetch data (not in cache).
  1171. ASSERT_TRUE(iter->Valid());
  1172. // Missed one sequential block but next is in already in buffer so
  1173. // readahead will not be reset.
  1174. iter->Seek(BuildKey(1011));
  1175. ASSERT_TRUE(iter->Valid());
  1176. // Prefetch data but blocks are in cache so no prefetch and reset.
  1177. iter->Seek(BuildKey(1015));
  1178. ASSERT_TRUE(iter->Valid());
  1179. iter->Seek(BuildKey(1019));
  1180. ASSERT_TRUE(iter->Valid());
  1181. iter->Seek(BuildKey(1022));
  1182. ASSERT_TRUE(iter->Valid());
  1183. // Prefetch data with readahead_size = 4 blocks.
  1184. iter->Seek(BuildKey(1026));
  1185. ASSERT_TRUE(iter->Valid());
  1186. iter->Seek(BuildKey(103));
  1187. ASSERT_TRUE(iter->Valid());
  1188. iter->Seek(BuildKey(1033));
  1189. ASSERT_TRUE(iter->Valid());
  1190. iter->Seek(BuildKey(1037));
  1191. ASSERT_TRUE(iter->Valid());
  1192. if (support_prefetch && !use_direct_io) {
  1193. ASSERT_EQ(fs->GetPrefetchCount(), 3);
  1194. fs->ClearPrefetchCount();
  1195. } else {
  1196. ASSERT_EQ(buff_prefetch_count, 2);
  1197. buff_prefetch_count = 0;
  1198. }
  1199. }
  1200. SyncPoint::GetInstance()->DisableProcessing();
  1201. SyncPoint::GetInstance()->ClearAllCallBacks();
  1202. Close();
  1203. }
  1204. TEST_P(PrefetchTest, PrefetchWithBlockLookupAutoTuneTest) {
  1205. if (mem_env_ || encrypted_env_) {
  1206. ROCKSDB_GTEST_SKIP("Test requires non-mem or non-encrypted environment");
  1207. return;
  1208. }
  1209. std::shared_ptr<MockFS> fs =
  1210. std::make_shared<MockFS>(FileSystem::Default(), false);
  1211. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  1212. Options options;
  1213. SetGenericOptions(env.get(), /*use_direct_io=*/false, options);
  1214. options.statistics = CreateDBStatistics();
  1215. const std::string prefix = "my_key_";
  1216. options.prefix_extractor.reset(NewFixedPrefixTransform(prefix.size()));
  1217. BlockBasedTableOptions table_options;
  1218. SetBlockBasedTableOptions(table_options);
  1219. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1220. Status s = TryReopen(options);
  1221. ASSERT_OK(s);
  1222. Random rnd(309);
  1223. WriteBatch batch;
  1224. // Create the DB with keys from "my_key_aaaaaaaaaa" to "my_key_zzzzzzzzzz"
  1225. for (int i = 0; i < 26; i++) {
  1226. std::string key = prefix;
  1227. for (int j = 0; j < 10; j++) {
  1228. key += char('a' + i);
  1229. ASSERT_OK(batch.Put(key, rnd.RandomString(1000)));
  1230. }
  1231. }
  1232. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  1233. std::string start_key = prefix + "a";
  1234. std::string end_key = prefix;
  1235. for (int j = 0; j < 10; j++) {
  1236. end_key += char('a' + 25);
  1237. }
  1238. Slice least(start_key.data(), start_key.size());
  1239. Slice greatest(end_key.data(), end_key.size());
  1240. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &least, &greatest));
  1241. // Try with different num_file_reads_for_auto_readahead from 0 to 3.
  1242. for (size_t i = 0; i < 3; i++) {
  1243. std::shared_ptr<Cache> cache = NewLRUCache(1024 * 1024, 2);
  1244. table_options.block_cache = cache;
  1245. table_options.no_block_cache = false;
  1246. table_options.num_file_reads_for_auto_readahead = i;
  1247. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1248. s = TryReopen(options);
  1249. ASSERT_OK(s);
  1250. // Warm up the cache.
  1251. {
  1252. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ReadOptions()));
  1253. iter->Seek(prefix + "bbb");
  1254. ASSERT_TRUE(iter->Valid());
  1255. iter->Seek(prefix + "ccccccccc");
  1256. ASSERT_TRUE(iter->Valid());
  1257. iter->Seek(prefix + "ddd");
  1258. ASSERT_TRUE(iter->Valid());
  1259. iter->Seek(prefix + "ddddddd");
  1260. ASSERT_TRUE(iter->Valid());
  1261. iter->Seek(prefix + "e");
  1262. ASSERT_TRUE(iter->Valid());
  1263. iter->Seek(prefix + "eeeee");
  1264. ASSERT_TRUE(iter->Valid());
  1265. iter->Seek(prefix + "eeeeeeeee");
  1266. ASSERT_TRUE(iter->Valid());
  1267. }
  1268. ReadOptions ropts;
  1269. ReadOptions cmp_ro;
  1270. if (std::get<0>(GetParam())) {
  1271. ropts.readahead_size = cmp_ro.readahead_size = 32768;
  1272. }
  1273. if (std::get<1>(GetParam())) {
  1274. ropts.async_io = true;
  1275. }
  1276. // With and without tuning readahead_size.
  1277. ropts.auto_readahead_size = true;
  1278. cmp_ro.auto_readahead_size = false;
  1279. ASSERT_OK(options.statistics->Reset());
  1280. // Seek with a upper bound
  1281. const std::string seek_key_str = prefix + "aaa";
  1282. const Slice seek_key(seek_key_str);
  1283. const std::string ub_str = prefix + "uuu";
  1284. const Slice ub(ub_str);
  1285. VerifyScan(ropts /* iter_ro */, cmp_ro /* cmp_iter_ro */,
  1286. &seek_key /* seek_key */, &ub /* iterate_upper_bound */,
  1287. false /* prefix_same_as_start */);
  1288. // Seek with a new seek key and upper bound
  1289. const std::string seek_key_new_str = prefix + "v";
  1290. const Slice seek_key_new(seek_key_new_str);
  1291. const std::string ub_new_str = prefix + "y";
  1292. const Slice ub_new(ub_new_str);
  1293. VerifyScan(ropts /* iter_ro */, cmp_ro /* cmp_iter_ro */,
  1294. &seek_key_new /* seek_key */, &ub_new /* iterate_upper_bound */,
  1295. false /* prefix_same_as_start */);
  1296. // Seek with no upper bound, prefix_same_as_start = true
  1297. VerifyScan(ropts /* iter_ro */, cmp_ro /* cmp_iter_ro */,
  1298. &seek_key /* seek_key */, nullptr /* iterate_upper_bound */,
  1299. true /* prefix_same_as_start */);
  1300. Close();
  1301. }
  1302. }
  1303. TEST_F(PrefetchTest, PrefetchWithBlockLookupAutoTuneWithPrev) {
  1304. if (mem_env_ || encrypted_env_) {
  1305. ROCKSDB_GTEST_SKIP("Test requires non-mem or non-encrypted environment");
  1306. return;
  1307. }
  1308. // First param is if the mockFS support_prefetch or not
  1309. std::shared_ptr<MockFS> fs =
  1310. std::make_shared<MockFS>(FileSystem::Default(), false);
  1311. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  1312. Options options;
  1313. SetGenericOptions(env.get(), /*use_direct_io=*/false, options);
  1314. options.statistics = CreateDBStatistics();
  1315. const std::string prefix = "my_key_";
  1316. options.prefix_extractor.reset(NewFixedPrefixTransform(prefix.size()));
  1317. BlockBasedTableOptions table_options;
  1318. SetBlockBasedTableOptions(table_options);
  1319. std::shared_ptr<Cache> cache = NewLRUCache(1024 * 1024, 2);
  1320. table_options.block_cache = cache;
  1321. table_options.no_block_cache = false;
  1322. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1323. Status s = TryReopen(options);
  1324. ASSERT_OK(s);
  1325. Random rnd(309);
  1326. WriteBatch batch;
  1327. for (int i = 0; i < 26; i++) {
  1328. std::string key = prefix;
  1329. for (int j = 0; j < 10; j++) {
  1330. key += char('a' + i);
  1331. ASSERT_OK(batch.Put(key, rnd.RandomString(1000)));
  1332. }
  1333. }
  1334. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  1335. std::string start_key = prefix + "a";
  1336. std::string end_key = prefix;
  1337. for (int j = 0; j < 10; j++) {
  1338. end_key += char('a' + 25);
  1339. }
  1340. Slice least(start_key.data(), start_key.size());
  1341. Slice greatest(end_key.data(), end_key.size());
  1342. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &least, &greatest));
  1343. ReadOptions ropts;
  1344. ropts.auto_readahead_size = true;
  1345. ReadOptions cmp_readopts = ropts;
  1346. cmp_readopts.auto_readahead_size = false;
  1347. const std::string seek_key_str = prefix + "bbb";
  1348. const Slice seek_key(seek_key_str);
  1349. const std::string ub_key = prefix + "uuu";
  1350. const Slice ub(ub_key);
  1351. VerifySeekPrevSeek(ropts /* iter_ro */, cmp_readopts /* cmp_iter_ro */,
  1352. &seek_key /* seek_key */, &ub /* iterate_upper_bound */,
  1353. false /* prefix_same_as_start */);
  1354. VerifySeekPrevSeek(ropts /* iter_ro */, cmp_readopts /* cmp_iter_ro */,
  1355. &seek_key /* seek_key */,
  1356. nullptr /* iterate_upper_bound */,
  1357. true /* prefix_same_as_start */);
  1358. Close();
  1359. }
  1360. class PrefetchTrimReadaheadTestParam
  1361. : public DBTestBase,
  1362. public ::testing::WithParamInterface<
  1363. std::tuple<BlockBasedTableOptions::IndexShorteningMode, bool>> {
  1364. public:
  1365. const std::string kPrefix = "a_prefix_";
  1366. Random rnd = Random(309);
  1367. PrefetchTrimReadaheadTestParam()
  1368. : DBTestBase("prefetch_trim_readahead_test_param", true) {}
  1369. virtual void SetGenericOptions(Env* env, Options& options) {
  1370. options = CurrentOptions();
  1371. options.env = env;
  1372. options.create_if_missing = true;
  1373. options.disable_auto_compactions = true;
  1374. options.statistics = CreateDBStatistics();
  1375. // To make all the data bocks fit in one file for testing purpose
  1376. options.write_buffer_size = 1024 * 1024 * 1024;
  1377. options.prefix_extractor.reset(NewFixedPrefixTransform(kPrefix.size()));
  1378. }
  1379. void SetBlockBasedTableOptions(BlockBasedTableOptions& table_options) {
  1380. table_options.no_block_cache = false;
  1381. table_options.index_shortening = std::get<0>(GetParam());
  1382. // To force keys with different prefixes are in different data blocks of the
  1383. // file for testing purpose
  1384. table_options.block_size = 1;
  1385. table_options.flush_block_policy_factory.reset(
  1386. new FlushBlockBySizePolicyFactory());
  1387. }
  1388. };
  1389. INSTANTIATE_TEST_CASE_P(
  1390. PrefetchTrimReadaheadTestParam, PrefetchTrimReadaheadTestParam,
  1391. ::testing::Combine(
  1392. // Params are as follows -
  1393. // Param 0 - TableOptions::index_shortening
  1394. // Param 2 - ReadOptinos::auto_readahead_size
  1395. ::testing::Values(
  1396. BlockBasedTableOptions::IndexShorteningMode::kNoShortening,
  1397. BlockBasedTableOptions::IndexShorteningMode::kShortenSeparators,
  1398. BlockBasedTableOptions::IndexShorteningMode::
  1399. kShortenSeparatorsAndSuccessor),
  1400. ::testing::Bool()));
  1401. TEST_P(PrefetchTrimReadaheadTestParam, PrefixSameAsStart) {
  1402. if (mem_env_ || encrypted_env_) {
  1403. ROCKSDB_GTEST_SKIP("Test requires non-mem or non-encrypted environment");
  1404. return;
  1405. }
  1406. const bool auto_readahead_size = std::get<1>(GetParam());
  1407. std::shared_ptr<MockFS> fs = std::make_shared<MockFS>(
  1408. FileSystem::Default(), false /* support_prefetch */,
  1409. true /* small_buffer_alignment */);
  1410. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  1411. Options options;
  1412. SetGenericOptions(env.get(), options);
  1413. BlockBasedTableOptions table_optoins;
  1414. SetBlockBasedTableOptions(table_optoins);
  1415. options.table_factory.reset(NewBlockBasedTableFactory(table_optoins));
  1416. Status s = TryReopen(options);
  1417. ASSERT_OK(s);
  1418. // To create a DB with data block layout (denoted as "[...]" below ) as the
  1419. // following:
  1420. // ["a_prefix_0": random value]
  1421. // ["a_prefix_1": random value]
  1422. // ...
  1423. // ["a_prefix_9": random value]
  1424. // ["c_prefix_0": random value]
  1425. // ["d_prefix_1": random value]
  1426. // ...
  1427. // ["l_prefix_9": random value]
  1428. //
  1429. // We want to verify keys not with prefix "a_prefix_" are not prefetched due
  1430. // to trimming
  1431. WriteBatch prefix_batch;
  1432. for (int i = 0; i < 10; i++) {
  1433. std::string key = kPrefix + std::to_string(i);
  1434. ASSERT_OK(prefix_batch.Put(key, rnd.RandomString(100)));
  1435. }
  1436. ASSERT_OK(db_->Write(WriteOptions(), &prefix_batch));
  1437. WriteBatch diff_prefix_batch;
  1438. for (int i = 0; i < 10; i++) {
  1439. std::string diff_prefix = std::string(1, char('c' + i)) + kPrefix.substr(1);
  1440. std::string key = diff_prefix + std::to_string(i);
  1441. ASSERT_OK(diff_prefix_batch.Put(key, rnd.RandomString(100)));
  1442. }
  1443. ASSERT_OK(db_->Write(WriteOptions(), &diff_prefix_batch));
  1444. ASSERT_OK(db_->Flush(FlushOptions()));
  1445. // To verify readahead is trimmed based on prefix by checking the counter
  1446. // READAHEAD_TRIMMED
  1447. ReadOptions ro;
  1448. ro.prefix_same_as_start = true;
  1449. ro.auto_readahead_size = auto_readahead_size;
  1450. // Set a large readahead size to introduce readahead waste when without
  1451. // trimming based on prefix
  1452. ro.readahead_size = 1024 * 1024 * 1024;
  1453. ASSERT_OK(options.statistics->Reset());
  1454. {
  1455. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ro));
  1456. for (iter->Seek(kPrefix); iter->status().ok() && iter->Valid();
  1457. iter->Next()) {
  1458. }
  1459. }
  1460. auto readahead_trimmed =
  1461. options.statistics->getTickerCount(READAHEAD_TRIMMED);
  1462. if (auto_readahead_size) {
  1463. ASSERT_GT(readahead_trimmed, 0);
  1464. } else {
  1465. ASSERT_EQ(readahead_trimmed, 0);
  1466. }
  1467. Close();
  1468. }
  1469. // This test verifies the functionality of ReadOptions.adaptive_readahead.
  1470. TEST_P(PrefetchTest, DBIterLevelReadAhead) {
  1471. const int kNumKeys = 1000;
  1472. // Set options
  1473. std::shared_ptr<MockFS> fs =
  1474. std::make_shared<MockFS>(env_->GetFileSystem(), false);
  1475. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  1476. bool use_direct_io = std::get<0>(GetParam());
  1477. bool is_adaptive_readahead = std::get<1>(GetParam());
  1478. Options options;
  1479. SetGenericOptions(env.get(), use_direct_io, options);
  1480. options.statistics = CreateDBStatistics();
  1481. BlockBasedTableOptions table_options;
  1482. SetBlockBasedTableOptions(table_options);
  1483. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1484. Status s = TryReopen(options);
  1485. if (use_direct_io && (s.IsNotSupported() || s.IsInvalidArgument())) {
  1486. // If direct IO is not supported, skip the test
  1487. return;
  1488. } else {
  1489. ASSERT_OK(s);
  1490. }
  1491. WriteBatch batch;
  1492. Random rnd(309);
  1493. int total_keys = 0;
  1494. for (int j = 0; j < 5; j++) {
  1495. for (int i = j * kNumKeys; i < (j + 1) * kNumKeys; i++) {
  1496. ASSERT_OK(batch.Put(BuildKey(i), rnd.RandomString(1000)));
  1497. total_keys++;
  1498. }
  1499. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  1500. ASSERT_OK(Flush());
  1501. }
  1502. MoveFilesToLevel(2);
  1503. int buff_prefetch_count = 0;
  1504. int readahead_carry_over_count = 0;
  1505. int num_sst_files = NumTableFilesAtLevel(2);
  1506. size_t current_readahead_size = 0;
  1507. // Test - Iterate over the keys sequentially.
  1508. {
  1509. SyncPoint::GetInstance()->SetCallBack(
  1510. "FilePrefetchBuffer::Prefetch:Start",
  1511. [&](void*) { buff_prefetch_count++; });
  1512. // The callback checks, since reads are sequential, readahead_size doesn't
  1513. // start from 8KB when iterator moves to next file and its called
  1514. // num_sst_files-1 times (excluding for first file).
  1515. SyncPoint::GetInstance()->SetCallBack(
  1516. "BlockPrefetcher::SetReadaheadState", [&](void* arg) {
  1517. readahead_carry_over_count++;
  1518. size_t readahead_size = *static_cast<size_t*>(arg);
  1519. if (readahead_carry_over_count) {
  1520. ASSERT_GT(readahead_size, 8 * 1024);
  1521. }
  1522. });
  1523. SyncPoint::GetInstance()->SetCallBack(
  1524. "FilePrefetchBuffer::TryReadFromCache", [&](void* arg) {
  1525. current_readahead_size = *static_cast<size_t*>(arg);
  1526. ASSERT_GT(current_readahead_size, 0);
  1527. });
  1528. SyncPoint::GetInstance()->EnableProcessing();
  1529. ReadOptions ro;
  1530. if (is_adaptive_readahead) {
  1531. ro.adaptive_readahead = true;
  1532. }
  1533. ASSERT_OK(options.statistics->Reset());
  1534. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ro));
  1535. int num_keys = 0;
  1536. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  1537. ASSERT_OK(iter->status());
  1538. num_keys++;
  1539. }
  1540. ASSERT_OK(iter->status());
  1541. ASSERT_EQ(num_keys, total_keys);
  1542. // For index and data blocks.
  1543. if (is_adaptive_readahead) {
  1544. ASSERT_EQ(readahead_carry_over_count, 2 * (num_sst_files - 1));
  1545. } else {
  1546. ASSERT_GT(buff_prefetch_count, 0);
  1547. ASSERT_EQ(readahead_carry_over_count, 0);
  1548. }
  1549. SyncPoint::GetInstance()->DisableProcessing();
  1550. SyncPoint::GetInstance()->ClearAllCallBacks();
  1551. }
  1552. Close();
  1553. }
  1554. // This test verifies the functionality of ReadOptions.adaptive_readahead when
  1555. // async_io is enabled.
  1556. TEST_P(PrefetchTest, DBIterLevelReadAheadWithAsyncIO) {
  1557. if (mem_env_ || encrypted_env_) {
  1558. ROCKSDB_GTEST_BYPASS("Test requires non-mem or non-encrypted environment");
  1559. return;
  1560. }
  1561. const int kNumKeys = 1000;
  1562. // Set options
  1563. std::shared_ptr<MockFS> fs =
  1564. std::make_shared<MockFS>(FileSystem::Default(), false);
  1565. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  1566. bool use_direct_io = std::get<0>(GetParam());
  1567. bool is_adaptive_readahead = std::get<1>(GetParam());
  1568. Options options;
  1569. SetGenericOptions(env.get(), use_direct_io, options);
  1570. options.statistics = CreateDBStatistics();
  1571. BlockBasedTableOptions table_options;
  1572. SetBlockBasedTableOptions(table_options);
  1573. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1574. Status s = TryReopen(options);
  1575. if (use_direct_io && (s.IsNotSupported() || s.IsInvalidArgument())) {
  1576. // If direct IO is not supported, skip the test
  1577. return;
  1578. } else {
  1579. ASSERT_OK(s);
  1580. }
  1581. WriteBatch batch;
  1582. Random rnd(309);
  1583. int total_keys = 0;
  1584. for (int j = 0; j < 5; j++) {
  1585. for (int i = j * kNumKeys; i < (j + 1) * kNumKeys; i++) {
  1586. ASSERT_OK(batch.Put(BuildKey(i), rnd.RandomString(1000)));
  1587. total_keys++;
  1588. }
  1589. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  1590. ASSERT_OK(Flush());
  1591. }
  1592. MoveFilesToLevel(2);
  1593. int buff_prefetch_count = 0;
  1594. int readahead_carry_over_count = 0;
  1595. int num_sst_files = NumTableFilesAtLevel(2);
  1596. size_t current_readahead_size = 0;
  1597. bool read_async_called = false;
  1598. // Test - Iterate over the keys sequentially.
  1599. {
  1600. SyncPoint::GetInstance()->SetCallBack(
  1601. "FilePrefetchBuffer::Prefetch:Start",
  1602. [&](void*) { buff_prefetch_count++; });
  1603. SyncPoint::GetInstance()->SetCallBack(
  1604. "UpdateResults::io_uring_result",
  1605. [&](void* /*arg*/) { read_async_called = true; });
  1606. // The callback checks, since reads are sequential, readahead_size doesn't
  1607. // start from 8KB when iterator moves to next file and its called
  1608. // num_sst_files-1 times (excluding for first file).
  1609. SyncPoint::GetInstance()->SetCallBack(
  1610. "BlockPrefetcher::SetReadaheadState", [&](void* arg) {
  1611. readahead_carry_over_count++;
  1612. size_t readahead_size = *static_cast<size_t*>(arg);
  1613. if (readahead_carry_over_count) {
  1614. ASSERT_GT(readahead_size, 8 * 1024);
  1615. }
  1616. });
  1617. SyncPoint::GetInstance()->SetCallBack(
  1618. "FilePrefetchBuffer::TryReadFromCache", [&](void* arg) {
  1619. current_readahead_size = *static_cast<size_t*>(arg);
  1620. ASSERT_GT(current_readahead_size, 0);
  1621. });
  1622. SyncPoint::GetInstance()->EnableProcessing();
  1623. ReadOptions ro;
  1624. if (is_adaptive_readahead) {
  1625. ro.adaptive_readahead = true;
  1626. }
  1627. ro.async_io = true;
  1628. ASSERT_OK(options.statistics->Reset());
  1629. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ro));
  1630. int num_keys = 0;
  1631. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  1632. ASSERT_OK(iter->status());
  1633. num_keys++;
  1634. }
  1635. ASSERT_OK(iter->status());
  1636. ASSERT_EQ(num_keys, total_keys);
  1637. // For index and data blocks.
  1638. if (is_adaptive_readahead) {
  1639. ASSERT_EQ(readahead_carry_over_count, 2 * (num_sst_files - 1));
  1640. } else {
  1641. ASSERT_EQ(readahead_carry_over_count, 0);
  1642. }
  1643. // Check stats to make sure async prefetch is done.
  1644. {
  1645. HistogramData async_read_bytes;
  1646. options.statistics->histogramData(ASYNC_READ_BYTES, &async_read_bytes);
  1647. // Not all platforms support iouring. In that case, ReadAsync in posix
  1648. // won't submit async requests.
  1649. if (read_async_called) {
  1650. ASSERT_GT(buff_prefetch_count, 0);
  1651. ASSERT_GT(async_read_bytes.count, 0);
  1652. } else {
  1653. ASSERT_GT(buff_prefetch_count, 0);
  1654. ASSERT_EQ(async_read_bytes.count, 0);
  1655. }
  1656. }
  1657. SyncPoint::GetInstance()->DisableProcessing();
  1658. SyncPoint::GetInstance()->ClearAllCallBacks();
  1659. }
  1660. Close();
  1661. }
  1662. TEST_P(PrefetchTest, AvoidBlockCacheLookupTwice) {
  1663. const int kNumKeys = 1000;
  1664. // Set options
  1665. std::shared_ptr<MockFS> fs =
  1666. std::make_shared<MockFS>(env_->GetFileSystem(), false);
  1667. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  1668. bool use_direct_io = std::get<0>(GetParam());
  1669. bool async_io = std::get<1>(GetParam());
  1670. Options options;
  1671. SetGenericOptions(env.get(), use_direct_io, options);
  1672. options.statistics = CreateDBStatistics();
  1673. BlockBasedTableOptions table_options;
  1674. SetBlockBasedTableOptions(table_options);
  1675. std::shared_ptr<Cache> cache = NewLRUCache(4 * 1024 * 1024, 2); // 8MB
  1676. table_options.block_cache = cache;
  1677. table_options.no_block_cache = false;
  1678. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1679. Status s = TryReopen(options);
  1680. if (use_direct_io && (s.IsNotSupported() || s.IsInvalidArgument())) {
  1681. // If direct IO is not supported, skip the test
  1682. return;
  1683. } else {
  1684. ASSERT_OK(s);
  1685. }
  1686. // Write to DB.
  1687. {
  1688. WriteBatch batch;
  1689. Random rnd(309);
  1690. for (int i = 0; i < kNumKeys; i++) {
  1691. ASSERT_OK(batch.Put(BuildKey(i), rnd.RandomString(1000)));
  1692. }
  1693. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  1694. std::string start_key = BuildKey(0);
  1695. std::string end_key = BuildKey(kNumKeys - 1);
  1696. Slice least(start_key.data(), start_key.size());
  1697. Slice greatest(end_key.data(), end_key.size());
  1698. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &least, &greatest));
  1699. }
  1700. ReadOptions ro;
  1701. ro.async_io = async_io;
  1702. // Iterate over the keys.
  1703. {
  1704. // Each block contains around 4 keys.
  1705. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ro));
  1706. ASSERT_OK(options.statistics->Reset());
  1707. iter->Seek(BuildKey(99)); // Prefetch data because of seek parallelization.
  1708. ASSERT_TRUE(iter->Valid());
  1709. ASSERT_EQ(options.statistics->getAndResetTickerCount(BLOCK_CACHE_DATA_MISS),
  1710. 1);
  1711. }
  1712. Close();
  1713. }
  1714. TEST_P(PrefetchTest, DBIterAsyncIONoIOUring) {
  1715. if (mem_env_ || encrypted_env_) {
  1716. ROCKSDB_GTEST_SKIP("Test requires non-mem or non-encrypted environment");
  1717. return;
  1718. }
  1719. const int kNumKeys = 1000;
  1720. // Set options
  1721. bool use_direct_io = std::get<0>(GetParam());
  1722. bool is_adaptive_readahead = std::get<1>(GetParam());
  1723. Options options;
  1724. SetGenericOptions(Env::Default(), use_direct_io, options);
  1725. options.statistics = CreateDBStatistics();
  1726. BlockBasedTableOptions table_options;
  1727. SetBlockBasedTableOptions(table_options);
  1728. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1729. enable_io_uring = false;
  1730. Status s = TryReopen(options);
  1731. if (use_direct_io && (s.IsNotSupported() || s.IsInvalidArgument())) {
  1732. // If direct IO is not supported, skip the test
  1733. enable_io_uring = true;
  1734. return;
  1735. } else {
  1736. ASSERT_OK(s);
  1737. }
  1738. WriteBatch batch;
  1739. Random rnd(309);
  1740. int total_keys = 0;
  1741. for (int j = 0; j < 5; j++) {
  1742. for (int i = j * kNumKeys; i < (j + 1) * kNumKeys; i++) {
  1743. ASSERT_OK(batch.Put(BuildKey(i), rnd.RandomString(1000)));
  1744. total_keys++;
  1745. }
  1746. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  1747. ASSERT_OK(Flush());
  1748. }
  1749. MoveFilesToLevel(2);
  1750. // Test - Iterate over the keys sequentially.
  1751. {
  1752. ReadOptions ro;
  1753. if (is_adaptive_readahead) {
  1754. ro.adaptive_readahead = true;
  1755. }
  1756. ro.async_io = true;
  1757. ASSERT_OK(options.statistics->Reset());
  1758. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ro));
  1759. int num_keys = 0;
  1760. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  1761. ASSERT_OK(iter->status());
  1762. num_keys++;
  1763. }
  1764. ASSERT_OK(iter->status());
  1765. ASSERT_EQ(num_keys, total_keys);
  1766. // Check stats to make sure async prefetch is done.
  1767. {
  1768. HistogramData async_read_bytes;
  1769. options.statistics->histogramData(ASYNC_READ_BYTES, &async_read_bytes);
  1770. ASSERT_EQ(async_read_bytes.count, 0);
  1771. ASSERT_EQ(options.statistics->getTickerCount(READ_ASYNC_MICROS), 0);
  1772. }
  1773. }
  1774. {
  1775. ReadOptions ro;
  1776. if (is_adaptive_readahead) {
  1777. ro.adaptive_readahead = true;
  1778. }
  1779. ro.async_io = true;
  1780. ro.tailing = true;
  1781. ASSERT_OK(options.statistics->Reset());
  1782. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ro));
  1783. int num_keys = 0;
  1784. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  1785. ASSERT_OK(iter->status());
  1786. num_keys++;
  1787. }
  1788. ASSERT_OK(iter->status());
  1789. ASSERT_EQ(num_keys, total_keys);
  1790. // Check stats to make sure async prefetch is done.
  1791. {
  1792. HistogramData async_read_bytes;
  1793. options.statistics->histogramData(ASYNC_READ_BYTES, &async_read_bytes);
  1794. ASSERT_EQ(async_read_bytes.count, 0);
  1795. ASSERT_EQ(options.statistics->getTickerCount(READ_ASYNC_MICROS), 0);
  1796. }
  1797. }
  1798. Close();
  1799. enable_io_uring = true;
  1800. }
  1801. class PrefetchTest1 : public DBTestBase,
  1802. public ::testing::WithParamInterface<bool> {
  1803. public:
  1804. PrefetchTest1() : DBTestBase("prefetch_test1", true) {}
  1805. virtual void SetGenericOptions(Env* env, bool use_direct_io,
  1806. Options& options) {
  1807. options = CurrentOptions();
  1808. options.write_buffer_size = 1024;
  1809. options.create_if_missing = true;
  1810. options.compression = kNoCompression;
  1811. options.env = env;
  1812. options.disable_auto_compactions = true;
  1813. if (use_direct_io) {
  1814. options.use_direct_reads = true;
  1815. options.use_direct_io_for_flush_and_compaction = true;
  1816. }
  1817. }
  1818. void SetBlockBasedTableOptions(BlockBasedTableOptions& table_options) {
  1819. table_options.no_block_cache = true;
  1820. table_options.cache_index_and_filter_blocks = false;
  1821. table_options.metadata_block_size = 1024;
  1822. table_options.index_type =
  1823. BlockBasedTableOptions::IndexType::kTwoLevelIndexSearch;
  1824. }
  1825. };
  1826. INSTANTIATE_TEST_CASE_P(PrefetchTest1, PrefetchTest1, ::testing::Bool());
  1827. TEST_P(PrefetchTest1, SeekWithExtraPrefetchAsyncIO) {
  1828. const int kNumKeys = 2000;
  1829. // Set options
  1830. std::shared_ptr<MockFS> fs =
  1831. std::make_shared<MockFS>(env_->GetFileSystem(), false);
  1832. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  1833. Options options;
  1834. SetGenericOptions(env.get(), GetParam(), options);
  1835. options.statistics = CreateDBStatistics();
  1836. BlockBasedTableOptions table_options;
  1837. SetBlockBasedTableOptions(table_options);
  1838. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1839. Status s = TryReopen(options);
  1840. if (GetParam() && (s.IsNotSupported() || s.IsInvalidArgument())) {
  1841. // If direct IO is not supported, skip the test
  1842. return;
  1843. } else {
  1844. ASSERT_OK(s);
  1845. }
  1846. WriteBatch batch;
  1847. Random rnd(309);
  1848. for (int i = 0; i < kNumKeys; i++) {
  1849. ASSERT_OK(batch.Put(BuildKey(i), rnd.RandomString(1000)));
  1850. }
  1851. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  1852. std::string start_key = BuildKey(0);
  1853. std::string end_key = BuildKey(kNumKeys - 1);
  1854. Slice least(start_key.data(), start_key.size());
  1855. Slice greatest(end_key.data(), end_key.size());
  1856. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &least, &greatest));
  1857. Close();
  1858. int buff_prefetch_count = 0, extra_prefetch_buff_cnt = 0;
  1859. for (size_t i = 0; i < 3; i++) {
  1860. table_options.num_file_reads_for_auto_readahead = i;
  1861. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1862. s = TryReopen(options);
  1863. ASSERT_OK(s);
  1864. buff_prefetch_count = 0;
  1865. extra_prefetch_buff_cnt = 0;
  1866. SyncPoint::GetInstance()->SetCallBack(
  1867. "FilePrefetchBuffer::PrefetchAsync:ExtraPrefetching",
  1868. [&](void*) { extra_prefetch_buff_cnt++; });
  1869. SyncPoint::GetInstance()->SetCallBack(
  1870. "FilePrefetchBuffer::Prefetch:Start",
  1871. [&](void*) { buff_prefetch_count++; });
  1872. SyncPoint::GetInstance()->EnableProcessing();
  1873. ReadOptions ro;
  1874. ro.async_io = true;
  1875. {
  1876. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ro));
  1877. // First Seek
  1878. iter->Seek(BuildKey(
  1879. 0)); // Prefetch data on seek because of seek parallelization.
  1880. ASSERT_TRUE(iter->Valid());
  1881. // Do extra prefetching in Seek only if
  1882. // num_file_reads_for_auto_readahead = 0.
  1883. ASSERT_EQ(extra_prefetch_buff_cnt, (i == 0 ? 1 : 0));
  1884. // buff_prefetch_count is 2 because of index block when
  1885. // num_file_reads_for_auto_readahead = 0.
  1886. // If num_file_reads_for_auto_readahead > 0, index block isn't
  1887. // prefetched.
  1888. ASSERT_EQ(buff_prefetch_count, i == 0 ? 2 : 1);
  1889. extra_prefetch_buff_cnt = 0;
  1890. buff_prefetch_count = 0;
  1891. // Reset all values of FilePrefetchBuffer on new seek.
  1892. iter->Seek(
  1893. BuildKey(22)); // Prefetch data because of seek parallelization.
  1894. ASSERT_TRUE(iter->Valid());
  1895. // Do extra prefetching in Seek only if
  1896. // num_file_reads_for_auto_readahead = 0.
  1897. ASSERT_EQ(extra_prefetch_buff_cnt, (i == 0 ? 1 : 0));
  1898. ASSERT_EQ(buff_prefetch_count, 1);
  1899. extra_prefetch_buff_cnt = 0;
  1900. buff_prefetch_count = 0;
  1901. // Reset all values of FilePrefetchBuffer on new seek.
  1902. iter->Seek(
  1903. BuildKey(33)); // Prefetch data because of seek parallelization.
  1904. ASSERT_TRUE(iter->Valid());
  1905. // Do extra prefetching in Seek only if
  1906. // num_file_reads_for_auto_readahead = 0.
  1907. ASSERT_EQ(extra_prefetch_buff_cnt, (i == 0 ? 1 : 0));
  1908. ASSERT_EQ(buff_prefetch_count, 1);
  1909. }
  1910. Close();
  1911. }
  1912. }
  1913. // This test verifies the functionality of ReadOptions.adaptive_readahead when
  1914. // reads are not sequential.
  1915. TEST_P(PrefetchTest1, NonSequentialReadsWithAdaptiveReadahead) {
  1916. const int kNumKeys = 1000;
  1917. // Set options
  1918. std::shared_ptr<MockFS> fs =
  1919. std::make_shared<MockFS>(env_->GetFileSystem(), false);
  1920. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  1921. Options options;
  1922. SetGenericOptions(env.get(), GetParam(), options);
  1923. BlockBasedTableOptions table_options;
  1924. SetBlockBasedTableOptions(table_options);
  1925. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1926. Status s = TryReopen(options);
  1927. if (GetParam() && (s.IsNotSupported() || s.IsInvalidArgument())) {
  1928. // If direct IO is not supported, skip the test
  1929. return;
  1930. } else {
  1931. ASSERT_OK(s);
  1932. }
  1933. WriteBatch batch;
  1934. Random rnd(309);
  1935. for (int j = 0; j < 5; j++) {
  1936. for (int i = j * kNumKeys; i < (j + 1) * kNumKeys; i++) {
  1937. ASSERT_OK(batch.Put(BuildKey(i), rnd.RandomString(1000)));
  1938. }
  1939. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  1940. ASSERT_OK(Flush());
  1941. }
  1942. MoveFilesToLevel(2);
  1943. int buff_prefetch_count = 0;
  1944. int set_readahead = 0;
  1945. size_t readahead_size = 0;
  1946. SyncPoint::GetInstance()->SetCallBack("FilePrefetchBuffer::Prefetch:Start",
  1947. [&](void*) { buff_prefetch_count++; });
  1948. SyncPoint::GetInstance()->SetCallBack(
  1949. "BlockPrefetcher::SetReadaheadState",
  1950. [&](void* /*arg*/) { set_readahead++; });
  1951. SyncPoint::GetInstance()->SetCallBack(
  1952. "FilePrefetchBuffer::TryReadFromCache",
  1953. [&](void* arg) { readahead_size = *static_cast<size_t*>(arg); });
  1954. SyncPoint::GetInstance()->EnableProcessing();
  1955. {
  1956. // Iterate until prefetch is done.
  1957. ReadOptions ro;
  1958. ro.adaptive_readahead = true;
  1959. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ro));
  1960. iter->SeekToFirst();
  1961. ASSERT_TRUE(iter->Valid());
  1962. while (iter->Valid() && buff_prefetch_count == 0) {
  1963. iter->Next();
  1964. }
  1965. ASSERT_EQ(readahead_size, 8 * 1024);
  1966. ASSERT_EQ(buff_prefetch_count, 1);
  1967. ASSERT_EQ(set_readahead, 0);
  1968. buff_prefetch_count = 0;
  1969. // Move to last file and check readahead size fallbacks to 8KB. So next
  1970. // readahead size after prefetch should be 8 * 1024;
  1971. iter->Seek(BuildKey(4004));
  1972. ASSERT_TRUE(iter->Valid());
  1973. while (iter->Valid() && buff_prefetch_count == 0) {
  1974. iter->Next();
  1975. }
  1976. ASSERT_EQ(readahead_size, 8 * 1024);
  1977. ASSERT_EQ(set_readahead, 0);
  1978. ASSERT_EQ(buff_prefetch_count, 1);
  1979. }
  1980. Close();
  1981. }
  1982. // This test verifies the functionality of adaptive_readaheadsize with cache
  1983. // and if block is found in cache, decrease the readahead_size if
  1984. // - its enabled internally by RocksDB (implicit_auto_readahead_) and,
  1985. // - readahead_size is greater than 0 and,
  1986. // - the block would have called prefetch API if not found in cache for
  1987. // which conditions are:
  1988. // - few/no bytes are in buffer and,
  1989. // - block is sequential with the previous read and,
  1990. // - num_file_reads_ + 1 (including this read) >
  1991. // num_file_reads_for_auto_readahead_
  1992. TEST_P(PrefetchTest1, DecreaseReadAheadIfInCache) {
  1993. const int kNumKeys = 2000;
  1994. // Set options
  1995. std::shared_ptr<MockFS> fs =
  1996. std::make_shared<MockFS>(env_->GetFileSystem(), false);
  1997. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  1998. Options options;
  1999. SetGenericOptions(env.get(), GetParam(), options);
  2000. options.statistics = CreateDBStatistics();
  2001. BlockBasedTableOptions table_options;
  2002. SetBlockBasedTableOptions(table_options);
  2003. std::shared_ptr<Cache> cache = NewLRUCache(4 * 1024 * 1024, 2); // 8MB
  2004. table_options.block_cache = cache;
  2005. table_options.no_block_cache = false;
  2006. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2007. Status s = TryReopen(options);
  2008. if (GetParam() && (s.IsNotSupported() || s.IsInvalidArgument())) {
  2009. // If direct IO is not supported, skip the test
  2010. return;
  2011. } else {
  2012. ASSERT_OK(s);
  2013. }
  2014. WriteBatch batch;
  2015. Random rnd(309);
  2016. for (int i = 0; i < kNumKeys; i++) {
  2017. ASSERT_OK(batch.Put(BuildKey(i), rnd.RandomString(1000)));
  2018. }
  2019. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  2020. std::string start_key = BuildKey(0);
  2021. std::string end_key = BuildKey(kNumKeys - 1);
  2022. Slice least(start_key.data(), start_key.size());
  2023. Slice greatest(end_key.data(), end_key.size());
  2024. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &least, &greatest));
  2025. int buff_prefetch_count = 0;
  2026. size_t current_readahead_size = 0;
  2027. size_t expected_current_readahead_size = 8 * 1024;
  2028. size_t decrease_readahead_size = 8 * 1024;
  2029. SyncPoint::GetInstance()->SetCallBack("FilePrefetchBuffer::Prefetch:Start",
  2030. [&](void*) { buff_prefetch_count++; });
  2031. SyncPoint::GetInstance()->SetCallBack(
  2032. "FilePrefetchBuffer::TryReadFromCache",
  2033. [&](void* arg) { current_readahead_size = *static_cast<size_t*>(arg); });
  2034. SyncPoint::GetInstance()->EnableProcessing();
  2035. ReadOptions ro;
  2036. ro.adaptive_readahead = true;
  2037. {
  2038. /*
  2039. * Reseek keys from sequential Data Blocks within same partitioned
  2040. * index. After 2 sequential reads it will prefetch the data block.
  2041. * Data Block size is nearly 4076 so readahead will fetch 8 * 1024 data
  2042. * more initially (2 more data blocks).
  2043. */
  2044. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ro));
  2045. // Warm up the cache
  2046. iter->Seek(BuildKey(1011));
  2047. ASSERT_TRUE(iter->Valid());
  2048. iter->Seek(BuildKey(1015));
  2049. ASSERT_TRUE(iter->Valid());
  2050. iter->Seek(BuildKey(1019));
  2051. ASSERT_TRUE(iter->Valid());
  2052. buff_prefetch_count = 0;
  2053. }
  2054. {
  2055. ASSERT_OK(options.statistics->Reset());
  2056. // After caching, blocks will be read from cache (Sequential blocks)
  2057. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ro));
  2058. iter->Seek(
  2059. BuildKey(0)); // In cache so it will decrease the readahead_size.
  2060. ASSERT_TRUE(iter->Valid());
  2061. expected_current_readahead_size = std::max(
  2062. decrease_readahead_size,
  2063. (expected_current_readahead_size >= decrease_readahead_size
  2064. ? (expected_current_readahead_size - decrease_readahead_size)
  2065. : 0));
  2066. iter->Seek(BuildKey(1000)); // Won't prefetch the block.
  2067. ASSERT_TRUE(iter->Valid());
  2068. ASSERT_EQ(current_readahead_size, expected_current_readahead_size);
  2069. iter->Seek(BuildKey(1004)); // Prefetch the block.
  2070. ASSERT_TRUE(iter->Valid());
  2071. ASSERT_EQ(current_readahead_size, expected_current_readahead_size);
  2072. expected_current_readahead_size *= 2;
  2073. iter->Seek(BuildKey(1011));
  2074. ASSERT_TRUE(iter->Valid());
  2075. // Eligible to Prefetch data (not in buffer) but block is in cache so no
  2076. // prefetch will happen and will result in decrease in readahead_size.
  2077. // readahead_size will be 8 * 1024
  2078. iter->Seek(BuildKey(1015));
  2079. ASSERT_TRUE(iter->Valid());
  2080. expected_current_readahead_size = std::max(
  2081. decrease_readahead_size,
  2082. (expected_current_readahead_size >= decrease_readahead_size
  2083. ? (expected_current_readahead_size - decrease_readahead_size)
  2084. : 0));
  2085. // 1016 is the same block as 1015. So no change in readahead_size.
  2086. iter->Seek(BuildKey(1016));
  2087. ASSERT_TRUE(iter->Valid());
  2088. // Prefetch data (not in buffer) but found in cache. So decrease
  2089. // readahead_size. Since it will 0 after decrementing so readahead_size
  2090. // will be set to initial value.
  2091. iter->Seek(BuildKey(1019));
  2092. ASSERT_TRUE(iter->Valid());
  2093. expected_current_readahead_size = std::max(
  2094. decrease_readahead_size,
  2095. (expected_current_readahead_size >= decrease_readahead_size
  2096. ? (expected_current_readahead_size - decrease_readahead_size)
  2097. : 0));
  2098. // Prefetch next sequential data.
  2099. iter->Seek(BuildKey(1022));
  2100. ASSERT_TRUE(iter->Valid());
  2101. ASSERT_EQ(current_readahead_size, expected_current_readahead_size);
  2102. ASSERT_EQ(buff_prefetch_count, 2);
  2103. buff_prefetch_count = 0;
  2104. }
  2105. Close();
  2106. }
  2107. // This test verifies the basic functionality of seek parallelization for
  2108. // async_io.
  2109. TEST_P(PrefetchTest1, SeekParallelizationTest) {
  2110. if (mem_env_ || encrypted_env_) {
  2111. ROCKSDB_GTEST_BYPASS("Test requires non-mem or non-encrypted environment");
  2112. return;
  2113. }
  2114. const int kNumKeys = 2000;
  2115. // Set options
  2116. std::shared_ptr<MockFS> fs = std::make_shared<MockFS>(
  2117. FileSystem::Default(), /*support_prefetch=*/false);
  2118. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  2119. Options options;
  2120. SetGenericOptions(env.get(), GetParam(), options);
  2121. options.statistics = CreateDBStatistics();
  2122. BlockBasedTableOptions table_options;
  2123. SetBlockBasedTableOptions(table_options);
  2124. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2125. Status s = TryReopen(options);
  2126. if (GetParam() && (s.IsNotSupported() || s.IsInvalidArgument())) {
  2127. // If direct IO is not supported, skip the test
  2128. return;
  2129. } else {
  2130. ASSERT_OK(s);
  2131. }
  2132. WriteBatch batch;
  2133. Random rnd(309);
  2134. for (int i = 0; i < kNumKeys; i++) {
  2135. ASSERT_OK(batch.Put(BuildKey(i), rnd.RandomString(1000)));
  2136. }
  2137. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  2138. std::string start_key = BuildKey(0);
  2139. std::string end_key = BuildKey(kNumKeys - 1);
  2140. Slice least(start_key.data(), start_key.size());
  2141. Slice greatest(end_key.data(), end_key.size());
  2142. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &least, &greatest));
  2143. int buff_prefetch_count = 0;
  2144. SyncPoint::GetInstance()->SetCallBack("FilePrefetchBuffer::Prefetch:Start",
  2145. [&](void*) { buff_prefetch_count++; });
  2146. bool read_async_called = false;
  2147. SyncPoint::GetInstance()->SetCallBack(
  2148. "UpdateResults::io_uring_result",
  2149. [&](void* /*arg*/) { read_async_called = true; });
  2150. SyncPoint::GetInstance()->EnableProcessing();
  2151. ReadOptions ro;
  2152. ro.adaptive_readahead = true;
  2153. ro.async_io = true;
  2154. {
  2155. ASSERT_OK(options.statistics->Reset());
  2156. // Each block contains around 4 keys.
  2157. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ro));
  2158. iter->Seek(BuildKey(0)); // Prefetch data because of seek parallelization.
  2159. ASSERT_TRUE(iter->Valid());
  2160. iter->Next();
  2161. ASSERT_TRUE(iter->Valid());
  2162. iter->Next();
  2163. ASSERT_TRUE(iter->Valid());
  2164. iter->Next();
  2165. ASSERT_TRUE(iter->Valid());
  2166. // New data block. Since num_file_reads in FilePrefetch after this read is
  2167. // 2, it won't go for prefetching.
  2168. iter->Next();
  2169. ASSERT_TRUE(iter->Valid());
  2170. iter->Next();
  2171. ASSERT_TRUE(iter->Valid());
  2172. iter->Next();
  2173. ASSERT_TRUE(iter->Valid());
  2174. iter->Next();
  2175. ASSERT_TRUE(iter->Valid());
  2176. // Prefetch data.
  2177. iter->Next();
  2178. ASSERT_TRUE(iter->Valid());
  2179. HistogramData async_read_bytes;
  2180. options.statistics->histogramData(ASYNC_READ_BYTES, &async_read_bytes);
  2181. // not all platforms support io_uring. In that case it'll fallback to
  2182. // normal prefetching without async_io.
  2183. if (read_async_called) {
  2184. ASSERT_EQ(buff_prefetch_count, 2);
  2185. ASSERT_GT(async_read_bytes.count, 0);
  2186. ASSERT_GT(get_perf_context()->number_async_seek, 0);
  2187. } else {
  2188. ASSERT_EQ(buff_prefetch_count, 1);
  2189. }
  2190. }
  2191. Close();
  2192. }
  2193. namespace {
  2194. #ifdef GFLAGS
  2195. const int kMaxArgCount = 100;
  2196. const size_t kArgBufferSize = 100000;
  2197. void RunIOTracerParserTool(std::string trace_file) {
  2198. std::vector<std::string> params = {"./io_tracer_parser",
  2199. "-io_trace_file=" + trace_file};
  2200. char arg_buffer[kArgBufferSize];
  2201. char* argv[kMaxArgCount];
  2202. int argc = 0;
  2203. int cursor = 0;
  2204. for (const auto& arg : params) {
  2205. ASSERT_LE(cursor + arg.size() + 1, kArgBufferSize);
  2206. ASSERT_LE(argc + 1, kMaxArgCount);
  2207. snprintf(arg_buffer + cursor, arg.size() + 1, "%s", arg.c_str());
  2208. argv[argc++] = arg_buffer + cursor;
  2209. cursor += static_cast<int>(arg.size()) + 1;
  2210. }
  2211. ASSERT_EQ(0, ROCKSDB_NAMESPACE::io_tracer_parser(argc, argv));
  2212. }
  2213. #endif // GFLAGS
  2214. } // namespace
  2215. // Tests the default implementation of ReadAsync API with PosixFileSystem during
  2216. // prefetching.
  2217. TEST_P(PrefetchTest, ReadAsyncWithPosixFS) {
  2218. if (mem_env_ || encrypted_env_) {
  2219. ROCKSDB_GTEST_SKIP("Test requires non-mem or non-encrypted environment");
  2220. return;
  2221. }
  2222. const int kNumKeys = 1000;
  2223. std::shared_ptr<MockFS> fs = std::make_shared<MockFS>(
  2224. FileSystem::Default(), /*support_prefetch=*/false);
  2225. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  2226. bool use_direct_io = std::get<0>(GetParam());
  2227. Options options;
  2228. SetGenericOptions(env.get(), use_direct_io, options);
  2229. options.statistics = CreateDBStatistics();
  2230. BlockBasedTableOptions table_options;
  2231. SetBlockBasedTableOptions(table_options);
  2232. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2233. Status s = TryReopen(options);
  2234. if (use_direct_io && (s.IsNotSupported() || s.IsInvalidArgument())) {
  2235. // If direct IO is not supported, skip the test
  2236. return;
  2237. } else {
  2238. ASSERT_OK(s);
  2239. }
  2240. int total_keys = 0;
  2241. // Write the keys.
  2242. {
  2243. WriteBatch batch;
  2244. Random rnd(309);
  2245. for (int j = 0; j < 5; j++) {
  2246. for (int i = j * kNumKeys; i < (j + 1) * kNumKeys; i++) {
  2247. ASSERT_OK(batch.Put(BuildKey(i), rnd.RandomString(1000)));
  2248. total_keys++;
  2249. }
  2250. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  2251. ASSERT_OK(Flush());
  2252. }
  2253. MoveFilesToLevel(2);
  2254. }
  2255. int buff_prefetch_count = 0;
  2256. bool read_async_called = false;
  2257. ReadOptions ro;
  2258. ro.adaptive_readahead = true;
  2259. ro.async_io = true;
  2260. if (std::get<1>(GetParam())) {
  2261. ro.readahead_size = 16 * 1024;
  2262. }
  2263. SyncPoint::GetInstance()->SetCallBack("FilePrefetchBuffer::Prefetch:Start",
  2264. [&](void*) { buff_prefetch_count++; });
  2265. SyncPoint::GetInstance()->SetCallBack(
  2266. "UpdateResults::io_uring_result",
  2267. [&](void* /*arg*/) { read_async_called = true; });
  2268. SyncPoint::GetInstance()->EnableProcessing();
  2269. // Read the keys.
  2270. {
  2271. ASSERT_OK(options.statistics->Reset());
  2272. get_perf_context()->Reset();
  2273. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ro));
  2274. int num_keys = 0;
  2275. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  2276. ASSERT_OK(iter->status());
  2277. num_keys++;
  2278. }
  2279. ASSERT_OK(iter->status());
  2280. if (read_async_called) {
  2281. ASSERT_EQ(num_keys, total_keys);
  2282. // Check stats to make sure async prefetch is done.
  2283. HistogramData async_read_bytes;
  2284. options.statistics->histogramData(ASYNC_READ_BYTES, &async_read_bytes);
  2285. HistogramData prefetched_bytes_discarded;
  2286. options.statistics->histogramData(PREFETCHED_BYTES_DISCARDED,
  2287. &prefetched_bytes_discarded);
  2288. ASSERT_GT(async_read_bytes.count, 0);
  2289. ASSERT_GT(prefetched_bytes_discarded.count, 0);
  2290. ASSERT_EQ(get_perf_context()->number_async_seek, 0);
  2291. } else {
  2292. // Not all platforms support iouring. In that case, ReadAsync in posix
  2293. // won't submit async requests.
  2294. ASSERT_EQ(num_keys, total_keys);
  2295. }
  2296. ASSERT_GT(buff_prefetch_count, 0);
  2297. }
  2298. SyncPoint::GetInstance()->DisableProcessing();
  2299. SyncPoint::GetInstance()->ClearAllCallBacks();
  2300. Close();
  2301. }
  2302. // This test verifies implementation of seek parallelization with
  2303. // PosixFileSystem during prefetching.
  2304. TEST_P(PrefetchTest, MultipleSeekWithPosixFS) {
  2305. if (mem_env_ || encrypted_env_) {
  2306. ROCKSDB_GTEST_SKIP("Test requires non-mem or non-encrypted environment");
  2307. return;
  2308. }
  2309. const int kNumKeys = 1000;
  2310. std::shared_ptr<MockFS> fs = std::make_shared<MockFS>(
  2311. FileSystem::Default(), /*support_prefetch=*/false);
  2312. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  2313. bool use_direct_io = std::get<0>(GetParam());
  2314. Options options;
  2315. SetGenericOptions(env.get(), use_direct_io, options);
  2316. options.statistics = CreateDBStatistics();
  2317. BlockBasedTableOptions table_options;
  2318. SetBlockBasedTableOptions(table_options);
  2319. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2320. Status s = TryReopen(options);
  2321. if (use_direct_io && (s.IsNotSupported() || s.IsInvalidArgument())) {
  2322. // If direct IO is not supported, skip the test
  2323. return;
  2324. } else {
  2325. ASSERT_OK(s);
  2326. }
  2327. int total_keys = 0;
  2328. // Write the keys.
  2329. {
  2330. WriteBatch batch;
  2331. Random rnd(309);
  2332. for (int j = 0; j < 5; j++) {
  2333. for (int i = j * kNumKeys; i < (j + 1) * kNumKeys; i++) {
  2334. ASSERT_OK(batch.Put(BuildKey(i), rnd.RandomString(1000)));
  2335. total_keys++;
  2336. }
  2337. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  2338. ASSERT_OK(Flush());
  2339. }
  2340. MoveFilesToLevel(2);
  2341. }
  2342. (void)total_keys;
  2343. int num_keys_first_batch = 0;
  2344. int num_keys_second_batch = 0;
  2345. // Calculate number of keys without async_io for correctness validation.
  2346. {
  2347. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ReadOptions()));
  2348. // First Seek.
  2349. iter->Seek(BuildKey(450));
  2350. while (iter->Valid() && num_keys_first_batch < 100) {
  2351. ASSERT_OK(iter->status());
  2352. num_keys_first_batch++;
  2353. iter->Next();
  2354. }
  2355. ASSERT_OK(iter->status());
  2356. iter->Seek(BuildKey(942));
  2357. while (iter->Valid()) {
  2358. ASSERT_OK(iter->status());
  2359. num_keys_second_batch++;
  2360. iter->Next();
  2361. }
  2362. ASSERT_OK(iter->status());
  2363. }
  2364. int buff_prefetch_count = 0;
  2365. bool read_async_called = false;
  2366. ReadOptions ro;
  2367. ro.adaptive_readahead = true;
  2368. ro.async_io = true;
  2369. if (std::get<1>(GetParam())) {
  2370. ro.readahead_size = 16 * 1024;
  2371. }
  2372. SyncPoint::GetInstance()->SetCallBack("FilePrefetchBuffer::Prefetch:Start",
  2373. [&](void*) { buff_prefetch_count++; });
  2374. SyncPoint::GetInstance()->SetCallBack(
  2375. "UpdateResults::io_uring_result",
  2376. [&](void* /*arg*/) { read_async_called = true; });
  2377. SyncPoint::GetInstance()->EnableProcessing();
  2378. // Read the keys using seek.
  2379. {
  2380. ASSERT_OK(options.statistics->Reset());
  2381. get_perf_context()->Reset();
  2382. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ro));
  2383. int num_keys = 0;
  2384. // First Seek.
  2385. {
  2386. iter->Seek(BuildKey(450));
  2387. while (iter->Valid() && num_keys < 100) {
  2388. ASSERT_OK(iter->status());
  2389. num_keys++;
  2390. iter->Next();
  2391. }
  2392. ASSERT_OK(iter->status());
  2393. ASSERT_EQ(num_keys, num_keys_first_batch);
  2394. // Check stats to make sure async prefetch is done.
  2395. HistogramData async_read_bytes;
  2396. options.statistics->histogramData(ASYNC_READ_BYTES, &async_read_bytes);
  2397. if (read_async_called) {
  2398. ASSERT_GT(async_read_bytes.count, 0);
  2399. ASSERT_GT(get_perf_context()->number_async_seek, 0);
  2400. } else {
  2401. // Not all platforms support iouring. In that case, ReadAsync in posix
  2402. // won't submit async requests.
  2403. ASSERT_EQ(async_read_bytes.count, 0);
  2404. ASSERT_EQ(get_perf_context()->number_async_seek, 0);
  2405. }
  2406. }
  2407. // Second Seek.
  2408. {
  2409. num_keys = 0;
  2410. ASSERT_OK(options.statistics->Reset());
  2411. get_perf_context()->Reset();
  2412. iter->Seek(BuildKey(942));
  2413. while (iter->Valid()) {
  2414. ASSERT_OK(iter->status());
  2415. num_keys++;
  2416. iter->Next();
  2417. }
  2418. ASSERT_OK(iter->status());
  2419. ASSERT_EQ(num_keys, num_keys_second_batch);
  2420. HistogramData async_read_bytes;
  2421. options.statistics->histogramData(ASYNC_READ_BYTES, &async_read_bytes);
  2422. HistogramData prefetched_bytes_discarded;
  2423. options.statistics->histogramData(PREFETCHED_BYTES_DISCARDED,
  2424. &prefetched_bytes_discarded);
  2425. ASSERT_GT(prefetched_bytes_discarded.count, 0);
  2426. if (read_async_called) {
  2427. ASSERT_GT(buff_prefetch_count, 0);
  2428. // Check stats to make sure async prefetch is done.
  2429. ASSERT_GT(async_read_bytes.count, 0);
  2430. ASSERT_GT(get_perf_context()->number_async_seek, 0);
  2431. } else {
  2432. // Not all platforms support iouring. In that case, ReadAsync in posix
  2433. // won't submit async requests.
  2434. ASSERT_EQ(async_read_bytes.count, 0);
  2435. ASSERT_EQ(get_perf_context()->number_async_seek, 0);
  2436. }
  2437. }
  2438. }
  2439. SyncPoint::GetInstance()->DisableProcessing();
  2440. SyncPoint::GetInstance()->ClearAllCallBacks();
  2441. Close();
  2442. }
  2443. // This test verifies implementation of seek parallelization with
  2444. // PosixFileSystem during prefetching.
  2445. TEST_P(PrefetchTest, SeekParallelizationTestWithPosix) {
  2446. if (mem_env_ || encrypted_env_) {
  2447. ROCKSDB_GTEST_SKIP("Test requires non-mem or non-encrypted environment");
  2448. return;
  2449. }
  2450. const int kNumKeys = 2000;
  2451. // Set options
  2452. std::shared_ptr<MockFS> fs = std::make_shared<MockFS>(
  2453. FileSystem::Default(), /*support_prefetch=*/false);
  2454. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  2455. bool use_direct_io = std::get<0>(GetParam());
  2456. Options options;
  2457. SetGenericOptions(env.get(), use_direct_io, options);
  2458. options.statistics = CreateDBStatistics();
  2459. BlockBasedTableOptions table_options;
  2460. SetBlockBasedTableOptions(table_options);
  2461. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2462. Status s = TryReopen(options);
  2463. if (use_direct_io && (s.IsNotSupported() || s.IsInvalidArgument())) {
  2464. // If direct IO is not supported, skip the test
  2465. return;
  2466. } else {
  2467. ASSERT_OK(s);
  2468. }
  2469. WriteBatch batch;
  2470. Random rnd(309);
  2471. for (int i = 0; i < kNumKeys; i++) {
  2472. ASSERT_OK(batch.Put(BuildKey(i), rnd.RandomString(1000)));
  2473. }
  2474. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  2475. std::string start_key = BuildKey(0);
  2476. std::string end_key = BuildKey(kNumKeys - 1);
  2477. Slice least(start_key.data(), start_key.size());
  2478. Slice greatest(end_key.data(), end_key.size());
  2479. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &least, &greatest));
  2480. int buff_prefetch_count = 0;
  2481. SyncPoint::GetInstance()->SetCallBack("FilePrefetchBuffer::Prefetch:Start",
  2482. [&](void*) { buff_prefetch_count++; });
  2483. bool read_async_called = false;
  2484. SyncPoint::GetInstance()->SetCallBack(
  2485. "UpdateResults::io_uring_result",
  2486. [&](void* /*arg*/) { read_async_called = true; });
  2487. SyncPoint::GetInstance()->EnableProcessing();
  2488. SyncPoint::GetInstance()->EnableProcessing();
  2489. ReadOptions ro;
  2490. ro.adaptive_readahead = true;
  2491. ro.async_io = true;
  2492. if (std::get<1>(GetParam())) {
  2493. ro.readahead_size = 16 * 1024;
  2494. }
  2495. {
  2496. ASSERT_OK(options.statistics->Reset());
  2497. // Each block contains around 4 keys.
  2498. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ro));
  2499. iter->Seek(BuildKey(0)); // Prefetch data because of seek parallelization.
  2500. ASSERT_TRUE(iter->Valid());
  2501. iter->Next();
  2502. ASSERT_TRUE(iter->Valid());
  2503. iter->Next();
  2504. ASSERT_TRUE(iter->Valid());
  2505. iter->Next();
  2506. ASSERT_TRUE(iter->Valid());
  2507. // New data block. Since num_file_reads in FilePrefetch after this read is
  2508. // 2, it won't go for prefetching.
  2509. iter->Next();
  2510. ASSERT_TRUE(iter->Valid());
  2511. iter->Next();
  2512. ASSERT_TRUE(iter->Valid());
  2513. iter->Next();
  2514. ASSERT_TRUE(iter->Valid());
  2515. iter->Next();
  2516. ASSERT_TRUE(iter->Valid());
  2517. // Prefetch data.
  2518. iter->Next();
  2519. ASSERT_TRUE(iter->Valid());
  2520. HistogramData async_read_bytes;
  2521. options.statistics->histogramData(ASYNC_READ_BYTES, &async_read_bytes);
  2522. if (read_async_called) {
  2523. ASSERT_GT(async_read_bytes.count, 0);
  2524. ASSERT_GT(get_perf_context()->number_async_seek, 0);
  2525. if (std::get<1>(GetParam())) {
  2526. ASSERT_EQ(buff_prefetch_count, 1);
  2527. } else {
  2528. ASSERT_EQ(buff_prefetch_count, 2);
  2529. }
  2530. } else {
  2531. // Not all platforms support iouring. In that case, ReadAsync in posix
  2532. // won't submit async requests.
  2533. ASSERT_EQ(async_read_bytes.count, 0);
  2534. ASSERT_EQ(get_perf_context()->number_async_seek, 0);
  2535. }
  2536. }
  2537. Close();
  2538. }
  2539. #ifdef GFLAGS
  2540. // This test verifies io_tracing with PosixFileSystem during prefetching.
  2541. TEST_P(PrefetchTest, TraceReadAsyncWithCallbackWrapper) {
  2542. if (mem_env_ || encrypted_env_) {
  2543. ROCKSDB_GTEST_SKIP("Test requires non-mem or non-encrypted environment");
  2544. return;
  2545. }
  2546. const int kNumKeys = 1000;
  2547. std::shared_ptr<MockFS> fs = std::make_shared<MockFS>(
  2548. FileSystem::Default(), /*support_prefetch=*/false);
  2549. std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, fs));
  2550. bool use_direct_io = std::get<0>(GetParam());
  2551. Options options;
  2552. SetGenericOptions(env.get(), use_direct_io, options);
  2553. options.statistics = CreateDBStatistics();
  2554. BlockBasedTableOptions table_options;
  2555. SetBlockBasedTableOptions(table_options);
  2556. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  2557. Status s = TryReopen(options);
  2558. if (use_direct_io && (s.IsNotSupported() || s.IsInvalidArgument())) {
  2559. // If direct IO is not supported, skip the test
  2560. return;
  2561. } else {
  2562. ASSERT_OK(s);
  2563. }
  2564. int total_keys = 0;
  2565. // Write the keys.
  2566. {
  2567. WriteBatch batch;
  2568. Random rnd(309);
  2569. for (int j = 0; j < 5; j++) {
  2570. for (int i = j * kNumKeys; i < (j + 1) * kNumKeys; i++) {
  2571. ASSERT_OK(batch.Put(BuildKey(i), rnd.RandomString(1000)));
  2572. total_keys++;
  2573. }
  2574. ASSERT_OK(db_->Write(WriteOptions(), &batch));
  2575. ASSERT_OK(Flush());
  2576. }
  2577. MoveFilesToLevel(2);
  2578. }
  2579. int buff_prefetch_count = 0;
  2580. bool read_async_called = false;
  2581. ReadOptions ro;
  2582. ro.adaptive_readahead = true;
  2583. ro.async_io = true;
  2584. if (std::get<1>(GetParam())) {
  2585. ro.readahead_size = 16 * 1024;
  2586. }
  2587. SyncPoint::GetInstance()->SetCallBack("FilePrefetchBuffer::Prefetch:Start",
  2588. [&](void*) { buff_prefetch_count++; });
  2589. SyncPoint::GetInstance()->SetCallBack(
  2590. "UpdateResults::io_uring_result",
  2591. [&](void* /*arg*/) { read_async_called = true; });
  2592. SyncPoint::GetInstance()->EnableProcessing();
  2593. // Read the keys.
  2594. {
  2595. // Start io_tracing.
  2596. WriteOptions write_opt;
  2597. TraceOptions trace_opt;
  2598. std::unique_ptr<TraceWriter> trace_writer;
  2599. std::string trace_file_path = dbname_ + "/io_trace_file";
  2600. ASSERT_OK(
  2601. NewFileTraceWriter(env_, EnvOptions(), trace_file_path, &trace_writer));
  2602. ASSERT_OK(db_->StartIOTrace(trace_opt, std::move(trace_writer)));
  2603. ASSERT_OK(options.statistics->Reset());
  2604. auto iter = std::unique_ptr<Iterator>(db_->NewIterator(ro));
  2605. int num_keys = 0;
  2606. for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
  2607. ASSERT_OK(iter->status());
  2608. num_keys++;
  2609. }
  2610. ASSERT_OK(iter->status());
  2611. // End the tracing.
  2612. ASSERT_OK(db_->EndIOTrace());
  2613. ASSERT_OK(env_->FileExists(trace_file_path));
  2614. ASSERT_EQ(num_keys, total_keys);
  2615. HistogramData async_read_bytes;
  2616. options.statistics->histogramData(ASYNC_READ_BYTES, &async_read_bytes);
  2617. if (read_async_called) {
  2618. ASSERT_GT(buff_prefetch_count, 0);
  2619. // Check stats to make sure async prefetch is done.
  2620. ASSERT_GT(async_read_bytes.count, 0);
  2621. } else {
  2622. // Not all platforms support iouring. In that case, ReadAsync in posix
  2623. // won't submit async requests.
  2624. ASSERT_EQ(async_read_bytes.count, 0);
  2625. }
  2626. // Check the file to see if ReadAsync is logged.
  2627. RunIOTracerParserTool(trace_file_path);
  2628. }
  2629. SyncPoint::GetInstance()->DisableProcessing();
  2630. SyncPoint::GetInstance()->ClearAllCallBacks();
  2631. Close();
  2632. }
  2633. #endif // GFLAGS
  2634. class FilePrefetchBufferTest : public testing::Test {
  2635. public:
  2636. void SetUp() override {
  2637. SetupSyncPointsToMockDirectIO();
  2638. env_ = Env::Default();
  2639. fs_ = FileSystem::Default();
  2640. test_dir_ = test::PerThreadDBPath("file_prefetch_buffer_test");
  2641. ASSERT_OK(fs_->CreateDir(test_dir_, IOOptions(), nullptr));
  2642. stats_ = CreateDBStatistics();
  2643. }
  2644. void TearDown() override { EXPECT_OK(DestroyDir(env_, test_dir_)); }
  2645. void Write(const std::string& fname, const std::string& content) {
  2646. std::unique_ptr<FSWritableFile> f;
  2647. ASSERT_OK(fs_->NewWritableFile(Path(fname), FileOptions(), &f, nullptr));
  2648. ASSERT_OK(f->Append(content, IOOptions(), nullptr));
  2649. ASSERT_OK(f->Close(IOOptions(), nullptr));
  2650. }
  2651. void Read(const std::string& fname, const FileOptions& opts,
  2652. std::unique_ptr<RandomAccessFileReader>* reader) {
  2653. std::string fpath = Path(fname);
  2654. std::unique_ptr<FSRandomAccessFile> f;
  2655. ASSERT_OK(fs_->NewRandomAccessFile(fpath, opts, &f, nullptr));
  2656. reader->reset(new RandomAccessFileReader(
  2657. std::move(f), fpath, env_->GetSystemClock().get(),
  2658. /*io_tracer=*/nullptr, stats_.get()));
  2659. }
  2660. void AssertResult(const std::string& content,
  2661. const std::vector<FSReadRequest>& reqs) {
  2662. for (const auto& r : reqs) {
  2663. ASSERT_OK(r.status);
  2664. ASSERT_EQ(r.len, r.result.size());
  2665. ASSERT_EQ(content.substr(r.offset, r.len), r.result.ToString());
  2666. }
  2667. }
  2668. FileSystem* fs() { return fs_.get(); }
  2669. Statistics* stats() { return stats_.get(); }
  2670. private:
  2671. Env* env_;
  2672. std::shared_ptr<FileSystem> fs_;
  2673. std::string test_dir_;
  2674. std::shared_ptr<Statistics> stats_;
  2675. std::string Path(const std::string& fname) { return test_dir_ + "/" + fname; }
  2676. };
  2677. TEST_F(FilePrefetchBufferTest, SeekWithBlockCacheHit) {
  2678. std::string fname = "seek-with-block-cache-hit";
  2679. Random rand(0);
  2680. std::string content = rand.RandomString(32768);
  2681. Write(fname, content);
  2682. FileOptions opts;
  2683. std::unique_ptr<RandomAccessFileReader> r;
  2684. Read(fname, opts, &r);
  2685. ReadaheadParams readahead_params;
  2686. readahead_params.initial_readahead_size = 16384;
  2687. readahead_params.max_readahead_size = 16384;
  2688. FilePrefetchBuffer fpb(readahead_params, true, false, fs());
  2689. Slice result;
  2690. // Simulate a seek of 4096 bytes at offset 0. Due to the readahead settings,
  2691. // it will do two reads of 4096+8192 and 8192
  2692. Status s = fpb.PrefetchAsync(IOOptions(), r.get(), 0, 4096, &result);
  2693. // Platforms that don't have IO uring may not support async IO.
  2694. if (s.IsNotSupported()) {
  2695. return;
  2696. }
  2697. ASSERT_TRUE(s.IsTryAgain());
  2698. // Simulate a block cache hit
  2699. fpb.UpdateReadPattern(0, 4096, false);
  2700. // Now read some data that straddles the two prefetch buffers - offset 8192 to
  2701. // 16384
  2702. IOOptions io_opts;
  2703. io_opts.rate_limiter_priority = Env::IOPriority::IO_LOW;
  2704. ASSERT_TRUE(fpb.TryReadFromCache(io_opts, r.get(), 8192, 8192, &result, &s));
  2705. }
  2706. // Test to ensure when PrefetchAsync is called during seek, it doesn't do any
  2707. // alignment or prefetch extra if readahead is not enabled during seek.
  2708. TEST_F(FilePrefetchBufferTest, SeekWithoutAlignment) {
  2709. std::string fname = "seek-without-alignment";
  2710. Random rand(0);
  2711. std::string content = rand.RandomString(32768);
  2712. Write(fname, content);
  2713. FileOptions opts;
  2714. std::unique_ptr<RandomAccessFileReader> r;
  2715. Read(fname, opts, &r);
  2716. size_t alignment = r->file()->GetRequiredBufferAlignment();
  2717. size_t n = alignment / 2;
  2718. int read_async_called = 0;
  2719. SyncPoint::GetInstance()->SetCallBack(
  2720. "FilePrefetchBuffer::ReadAsync",
  2721. [&](void* /*arg*/) { read_async_called++; });
  2722. SyncPoint::GetInstance()->EnableProcessing();
  2723. // Without readahead enabled, there will be no alignment and offset of buffer
  2724. // will be n.
  2725. {
  2726. ReadaheadParams readahead_params;
  2727. readahead_params.initial_readahead_size = 8192;
  2728. readahead_params.max_readahead_size = 16384;
  2729. readahead_params.implicit_auto_readahead = true;
  2730. readahead_params.num_file_reads_for_auto_readahead = 2;
  2731. readahead_params.num_buffers = 2;
  2732. FilePrefetchBuffer fpb(readahead_params, /*enable=*/true,
  2733. /*track_min_offset=*/false, fs(), nullptr, nullptr,
  2734. nullptr, FilePrefetchBufferUsage::kUnknown);
  2735. Slice result;
  2736. // Simulate a seek of half of alignment bytes at offset n. Due to the
  2737. // readahead settings, it won't prefetch extra or do any alignment and
  2738. // offset of buffer will be n.
  2739. Status s = fpb.PrefetchAsync(IOOptions(), r.get(), n, n, &result);
  2740. // Platforms that don't have IO uring may not support async IO.
  2741. if (s.IsNotSupported()) {
  2742. return;
  2743. }
  2744. ASSERT_TRUE(s.IsTryAgain());
  2745. IOOptions io_opts;
  2746. io_opts.rate_limiter_priority = Env::IOPriority::IO_LOW;
  2747. ASSERT_TRUE(fpb.TryReadFromCache(io_opts, r.get(), n, n, &result, &s));
  2748. if (read_async_called) {
  2749. ASSERT_EQ(fpb.GetPrefetchOffset(), n);
  2750. }
  2751. }
  2752. // With readahead enabled, it will do the alignment and prefetch and offset of
  2753. // buffer will be 0.
  2754. {
  2755. read_async_called = false;
  2756. ReadaheadParams readahead_params;
  2757. readahead_params.initial_readahead_size = 16384;
  2758. readahead_params.max_readahead_size = 16384;
  2759. readahead_params.num_file_reads_for_auto_readahead = 2;
  2760. readahead_params.num_buffers = 2;
  2761. FilePrefetchBuffer fpb(readahead_params, /*enable=*/true,
  2762. /*track_min_offset=*/false, fs(), nullptr, nullptr,
  2763. nullptr, FilePrefetchBufferUsage::kUnknown);
  2764. Slice result;
  2765. // Simulate a seek of half of alignment bytes at offset n.
  2766. Status s = fpb.PrefetchAsync(IOOptions(), r.get(), n, n, &result);
  2767. // Platforms that don't have IO uring may not support async IO.
  2768. if (s.IsNotSupported()) {
  2769. return;
  2770. }
  2771. ASSERT_TRUE(s.IsTryAgain());
  2772. IOOptions io_opts;
  2773. io_opts.rate_limiter_priority = Env::IOPriority::IO_LOW;
  2774. ASSERT_TRUE(fpb.TryReadFromCache(io_opts, r.get(), n, n, &result, &s));
  2775. if (read_async_called) {
  2776. ASSERT_EQ(fpb.GetPrefetchOffset(), 0);
  2777. }
  2778. }
  2779. }
  2780. TEST_F(FilePrefetchBufferTest, NoSyncWithAsyncIO) {
  2781. std::string fname = "seek-with-block-cache-hit";
  2782. Random rand(0);
  2783. std::string content = rand.RandomString(32768);
  2784. Write(fname, content);
  2785. FileOptions opts;
  2786. std::unique_ptr<RandomAccessFileReader> r;
  2787. Read(fname, opts, &r);
  2788. ReadaheadParams readahead_params;
  2789. readahead_params.initial_readahead_size = 8192;
  2790. readahead_params.max_readahead_size = 16384;
  2791. readahead_params.num_buffers = 2;
  2792. FilePrefetchBuffer fpb(readahead_params, /*enable=*/true,
  2793. /*track_min_offset=*/false, fs(), nullptr, nullptr,
  2794. nullptr, FilePrefetchBufferUsage::kUnknown);
  2795. int read_async_called = 0;
  2796. SyncPoint::GetInstance()->SetCallBack(
  2797. "FilePrefetchBuffer::ReadAsync",
  2798. [&](void* /*arg*/) { read_async_called++; });
  2799. SyncPoint::GetInstance()->EnableProcessing();
  2800. Slice async_result;
  2801. // Simulate a seek of 4000 bytes at offset 3000. Due to the readahead
  2802. // settings, it will do two reads of 4000+4096 and 4096
  2803. Status s = fpb.PrefetchAsync(IOOptions(), r.get(), 3000, 4000, &async_result);
  2804. // Platforms that don't have IO uring may not support async IO
  2805. if (s.IsNotSupported()) {
  2806. return;
  2807. }
  2808. ASSERT_TRUE(s.IsTryAgain());
  2809. IOOptions io_opts;
  2810. io_opts.rate_limiter_priority = Env::IOPriority::IO_LOW;
  2811. ASSERT_TRUE(fpb.TryReadFromCache(io_opts, r.get(), /*offset=*/3000,
  2812. /*length=*/4000, &async_result, &s));
  2813. // No sync call should be made.
  2814. HistogramData sst_read_micros;
  2815. stats()->histogramData(SST_READ_MICROS, &sst_read_micros);
  2816. ASSERT_EQ(sst_read_micros.count, 0);
  2817. // Number of async calls should be.
  2818. ASSERT_EQ(read_async_called, 2);
  2819. // Length should be 4000.
  2820. ASSERT_EQ(async_result.size(), 4000);
  2821. // Data correctness.
  2822. Slice result(&content[3000], 4000);
  2823. ASSERT_EQ(result.size(), 4000);
  2824. ASSERT_EQ(result, async_result);
  2825. }
  2826. TEST_F(FilePrefetchBufferTest, SyncReadaheadStats) {
  2827. std::string fname = "seek-with-block-cache-hit";
  2828. Random rand(0);
  2829. std::string content = rand.RandomString(32768);
  2830. Write(fname, content);
  2831. FileOptions opts;
  2832. std::unique_ptr<RandomAccessFileReader> r;
  2833. Read(fname, opts, &r);
  2834. std::shared_ptr<Statistics> stats = CreateDBStatistics();
  2835. ReadaheadParams readahead_params;
  2836. readahead_params.initial_readahead_size = 8192;
  2837. readahead_params.max_readahead_size = 8192;
  2838. FilePrefetchBuffer fpb(
  2839. readahead_params, true, false, fs(), nullptr, stats.get(),
  2840. nullptr /* cb */, FilePrefetchBufferUsage::kUserScanPrefetch /* usage */);
  2841. Slice result;
  2842. // Simulate a seek of 4096 bytes at offset 0. Due to the readahead settings,
  2843. // it will do a read of offset 0 and length - (4096 + 8192) 12288.
  2844. Status s;
  2845. ASSERT_TRUE(fpb.TryReadFromCache(IOOptions(), r.get(), 0, 4096, &result, &s));
  2846. ASSERT_EQ(s, Status::OK());
  2847. ASSERT_EQ(stats->getTickerCount(PREFETCH_HITS), 0);
  2848. ASSERT_EQ(stats->getTickerCount(PREFETCH_BYTES_USEFUL), 0);
  2849. // Simulate a block cache hit
  2850. fpb.UpdateReadPattern(4096, 4096, false);
  2851. // Now read some data that'll prefetch additional data from 12288 to 24576.
  2852. // (8192) + 8192 (readahead_size).
  2853. ASSERT_TRUE(
  2854. fpb.TryReadFromCache(IOOptions(), r.get(), 8192, 8192, &result, &s));
  2855. ASSERT_EQ(s, Status::OK());
  2856. ASSERT_EQ(stats->getTickerCount(PREFETCH_HITS), 0);
  2857. ASSERT_EQ(stats->getTickerCount(PREFETCH_BYTES_USEFUL), 4096);
  2858. ASSERT_TRUE(
  2859. fpb.TryReadFromCache(IOOptions(), r.get(), 12288, 4096, &result, &s));
  2860. ASSERT_EQ(s, Status::OK());
  2861. ASSERT_EQ(stats->getAndResetTickerCount(PREFETCH_HITS), 1);
  2862. ASSERT_EQ(stats->getAndResetTickerCount(PREFETCH_BYTES_USEFUL), 8192);
  2863. // Now read some data with length doesn't align with aligment and it needs
  2864. // prefetching. Read from 16000 with length 10000 (i.e. requested end offset -
  2865. // 26000).
  2866. ASSERT_TRUE(
  2867. fpb.TryReadFromCache(IOOptions(), r.get(), 16000, 10000, &result, &s));
  2868. ASSERT_EQ(s, Status::OK());
  2869. ASSERT_EQ(stats->getAndResetTickerCount(PREFETCH_HITS), 0);
  2870. ASSERT_EQ(
  2871. stats->getAndResetTickerCount(PREFETCH_BYTES_USEFUL),
  2872. /* 24576(end offset of the buffer) - 16000(requested offset) =*/8576);
  2873. }
  2874. TEST_F(FilePrefetchBufferTest, ForCompaction) {
  2875. // Make sure TryReadWithCache with for_compaction=true works without file
  2876. // system buffer reuse optimization
  2877. std::string fname = "fs-prefetch-buffer-for-compaction";
  2878. Random rand(0);
  2879. std::string content = rand.RandomString(64 * 1024);
  2880. Write(fname, content);
  2881. FileOptions opts;
  2882. std::unique_ptr<RandomAccessFileReader> r;
  2883. Read(fname, opts, &r);
  2884. std::shared_ptr<Statistics> stats = CreateDBStatistics();
  2885. ReadaheadParams readahead_params;
  2886. readahead_params.initial_readahead_size = 8192;
  2887. readahead_params.max_readahead_size = 8192;
  2888. readahead_params.num_buffers = 1;
  2889. FilePrefetchBuffer fpb(readahead_params, true /* enable */,
  2890. false /* track_min_offset */, fs(), nullptr,
  2891. stats.get());
  2892. Slice result;
  2893. Status s;
  2894. ASSERT_TRUE(fpb.TryReadFromCache(IOOptions(), r.get(), 0 /* offset */,
  2895. 3000 /* n */, &result, &s, true));
  2896. ASSERT_EQ(s, Status::OK());
  2897. ASSERT_EQ(result.size(), 3000);
  2898. ASSERT_EQ(strncmp(result.data(), content.substr(0, 3000).c_str(), 3000), 0);
  2899. ASSERT_TRUE(fpb.TryReadFromCache(IOOptions(), r.get(), 3000 /* offset */,
  2900. 10000 /* n */, &result, &s, true));
  2901. ASSERT_EQ(s, Status::OK());
  2902. ASSERT_EQ(result.size(), 10000);
  2903. ASSERT_EQ(strncmp(result.data(), content.substr(3000, 10000).c_str(), 10000),
  2904. 0);
  2905. ASSERT_TRUE(fpb.TryReadFromCache(IOOptions(), r.get(), 15000 /* offset */,
  2906. 4096 /* n */, &result, &s, true));
  2907. ASSERT_EQ(s, Status::OK());
  2908. ASSERT_EQ(result.size(), 4096);
  2909. ASSERT_EQ(strncmp(result.data(), content.substr(15000, 4096).c_str(), 4096),
  2910. 0);
  2911. ASSERT_TRUE(fpb.TryReadFromCache(IOOptions(), r.get(), 40000 /* offset */,
  2912. 20000 /* n */, &result, &s, true));
  2913. ASSERT_EQ(s, Status::OK());
  2914. ASSERT_EQ(result.size(), 20000);
  2915. ASSERT_EQ(strncmp(result.data(), content.substr(40000, 20000).c_str(), 20000),
  2916. 0);
  2917. // Try reading past end of file
  2918. ASSERT_TRUE(fpb.TryReadFromCache(IOOptions(), r.get(), 60000 /* offset */,
  2919. 10000 /* n */, &result, &s, true));
  2920. ASSERT_EQ(s, Status::OK());
  2921. ASSERT_EQ(result.size(), 64 * 1024 - 60000);
  2922. ASSERT_EQ(
  2923. strncmp(result.data(), content.substr(60000, 64 * 1024 - 60000).c_str(),
  2924. 64 * 1024 - 60000),
  2925. 0);
  2926. }
  2927. class FSBufferPrefetchTest
  2928. : public testing::Test,
  2929. public ::testing::WithParamInterface<std::tuple<bool, bool>> {
  2930. public:
  2931. // Mock file system supporting the kFSBuffer buffer reuse operation
  2932. class BufferReuseFS : public FileSystemWrapper {
  2933. public:
  2934. explicit BufferReuseFS(const std::shared_ptr<FileSystem>& _target)
  2935. : FileSystemWrapper(_target) {}
  2936. ~BufferReuseFS() override {}
  2937. const char* Name() const override { return "BufferReuseFS"; }
  2938. IOStatus NewRandomAccessFile(const std::string& fname,
  2939. const FileOptions& opts,
  2940. std::unique_ptr<FSRandomAccessFile>* result,
  2941. IODebugContext* dbg) override {
  2942. class WrappedRandomAccessFile : public FSRandomAccessFileOwnerWrapper {
  2943. public:
  2944. explicit WrappedRandomAccessFile(
  2945. std::unique_ptr<FSRandomAccessFile>& file)
  2946. : FSRandomAccessFileOwnerWrapper(std::move(file)) {}
  2947. IOStatus MultiRead(FSReadRequest* reqs, size_t num_reqs,
  2948. const IOOptions& options,
  2949. IODebugContext* dbg) override {
  2950. for (size_t i = 0; i < num_reqs; ++i) {
  2951. FSReadRequest& req = reqs[i];
  2952. // We cannot assume that fs_scratch points to the start of
  2953. // the read data. We can have the FSAllocationPtr point to a
  2954. // wrapper around the result buffer in our test implementation so
  2955. // that we can catch whenever we incorrectly make this assumption.
  2956. // See https://github.com/facebook/rocksdb/pull/13189 for more
  2957. // context.
  2958. char* internalData = new char[req.len];
  2959. req.status = Read(req.offset, req.len, options, &req.result,
  2960. internalData, dbg);
  2961. Slice* internalSlice = new Slice(internalData, req.len);
  2962. FSAllocationPtr internalPtr(internalSlice, [](void* ptr) {
  2963. delete[] static_cast<const char*>(
  2964. static_cast<Slice*>(ptr)->data_);
  2965. delete static_cast<Slice*>(ptr);
  2966. });
  2967. req.fs_scratch = std::move(internalPtr);
  2968. }
  2969. return IOStatus::OK();
  2970. }
  2971. };
  2972. std::unique_ptr<FSRandomAccessFile> file;
  2973. IOStatus s = target()->NewRandomAccessFile(fname, opts, &file, dbg);
  2974. EXPECT_OK(s);
  2975. result->reset(new WrappedRandomAccessFile(file));
  2976. return s;
  2977. }
  2978. void SupportedOps(int64_t& supported_ops) override {
  2979. supported_ops = 1 << FSSupportedOps::kAsyncIO;
  2980. supported_ops |= 1 << FSSupportedOps::kFSBuffer;
  2981. }
  2982. };
  2983. void SetUp() override {
  2984. SetupSyncPointsToMockDirectIO();
  2985. env_ = Env::Default();
  2986. bool use_async_prefetch = std::get<0>(GetParam());
  2987. if (use_async_prefetch) {
  2988. fs_ = FileSystem::Default();
  2989. } else {
  2990. fs_ = std::make_shared<BufferReuseFS>(FileSystem::Default());
  2991. }
  2992. test_dir_ = test::PerThreadDBPath("fs_buffer_prefetch_test");
  2993. ASSERT_OK(fs_->CreateDir(test_dir_, IOOptions(), nullptr));
  2994. stats_ = CreateDBStatistics();
  2995. }
  2996. void TearDown() override { EXPECT_OK(DestroyDir(env_, test_dir_)); }
  2997. void Write(const std::string& fname, const std::string& content) {
  2998. std::unique_ptr<FSWritableFile> f;
  2999. ASSERT_OK(fs_->NewWritableFile(Path(fname), FileOptions(), &f, nullptr));
  3000. ASSERT_OK(f->Append(content, IOOptions(), nullptr));
  3001. ASSERT_OK(f->Close(IOOptions(), nullptr));
  3002. }
  3003. void Read(const std::string& fname, const FileOptions& opts,
  3004. std::unique_ptr<RandomAccessFileReader>* reader) {
  3005. std::string fpath = Path(fname);
  3006. std::unique_ptr<FSRandomAccessFile> f;
  3007. ASSERT_OK(fs_->NewRandomAccessFile(fpath, opts, &f, nullptr));
  3008. reader->reset(new RandomAccessFileReader(
  3009. std::move(f), fpath, env_->GetSystemClock().get(),
  3010. /*io_tracer=*/nullptr, stats_.get()));
  3011. }
  3012. FileSystem* fs() { return fs_.get(); }
  3013. Statistics* stats() { return stats_.get(); }
  3014. SystemClock* clock() { return env_->GetSystemClock().get(); }
  3015. private:
  3016. Env* env_;
  3017. std::shared_ptr<FileSystem> fs_;
  3018. std::string test_dir_;
  3019. std::shared_ptr<Statistics> stats_;
  3020. std::string Path(const std::string& fname) { return test_dir_ + "/" + fname; }
  3021. };
  3022. // param 1: whether async IO is enabled (num_buffers_ > 1)
  3023. // param 2: whether for_compaction is set to true for TryReadFromCache requests
  3024. // 3 out of these 4 combinations are tested (async IO is not allowed for
  3025. // compaction reads)
  3026. INSTANTIATE_TEST_CASE_P(FSBufferPrefetchTest, FSBufferPrefetchTest,
  3027. ::testing::Combine(::testing::Bool(),
  3028. ::testing::Bool()));
  3029. TEST_P(FSBufferPrefetchTest, FSBufferPrefetchStatsInternals) {
  3030. // Check that the main buffer, the overlap_buf_, and the secondary buffer (in
  3031. // the case of num_buffers_ > 1) are populated correctly while reading a 32
  3032. // KiB file
  3033. std::string fname = "fs-buffer-prefetch-stats-internals";
  3034. Random rand(0);
  3035. std::string content = rand.RandomString(32768);
  3036. Write(fname, content);
  3037. FileOptions opts;
  3038. std::unique_ptr<RandomAccessFileReader> r;
  3039. Read(fname, opts, &r);
  3040. std::shared_ptr<Statistics> stats = CreateDBStatistics();
  3041. ReadaheadParams readahead_params;
  3042. readahead_params.initial_readahead_size = 8192;
  3043. readahead_params.max_readahead_size = 8192;
  3044. bool use_async_prefetch = std::get<0>(GetParam());
  3045. bool for_compaction = std::get<1>(GetParam());
  3046. // We disallow async IO for compaction reads since they are background
  3047. // operations anyways and not as latency sensitive as user-initiated reads
  3048. if (use_async_prefetch && for_compaction) {
  3049. return;
  3050. }
  3051. size_t num_buffers = use_async_prefetch ? 2 : 1;
  3052. readahead_params.num_buffers = num_buffers;
  3053. FilePrefetchBuffer fpb(
  3054. readahead_params, true /* enable */, false /* track_min_offset */, fs(),
  3055. clock(), stats.get(), nullptr /* cb */,
  3056. FilePrefetchBufferUsage::kUserScanPrefetch /* usage */);
  3057. int overlap_buffer_write_ct = 0;
  3058. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  3059. "FilePrefetchBuffer::CopyDataToOverlapBuffer:Complete",
  3060. [&](void* /*arg*/) { overlap_buffer_write_ct++; });
  3061. SyncPoint::GetInstance()->EnableProcessing();
  3062. Slice result;
  3063. // Read 4096 bytes at offset 0.
  3064. Status s;
  3065. std::vector<std::tuple<uint64_t, size_t, bool>> buffer_info(num_buffers);
  3066. std::pair<uint64_t, size_t> overlap_buffer_info;
  3067. bool could_read_from_cache =
  3068. fpb.TryReadFromCache(IOOptions(), r.get(), 0 /* offset */, 4096 /* n */,
  3069. &result, &s, for_compaction);
  3070. // Platforms that don't have IO uring may not support async IO.
  3071. if (use_async_prefetch && s.IsNotSupported()) {
  3072. return;
  3073. }
  3074. ASSERT_TRUE(could_read_from_cache);
  3075. ASSERT_EQ(s, Status::OK());
  3076. ASSERT_EQ(stats->getAndResetTickerCount(PREFETCH_HITS), 0);
  3077. ASSERT_EQ(stats->getAndResetTickerCount(PREFETCH_BYTES_USEFUL), 0);
  3078. ASSERT_EQ(strncmp(result.data(), content.substr(0, 4096).c_str(), 4096), 0);
  3079. fpb.TEST_GetOverlapBufferOffsetandSize(overlap_buffer_info);
  3080. fpb.TEST_GetBufferOffsetandSize(buffer_info);
  3081. if (use_async_prefetch) {
  3082. // Cut the readahead of 8192 in half.
  3083. // Overlap buffer is not used
  3084. ASSERT_EQ(overlap_buffer_info.first, 0);
  3085. ASSERT_EQ(overlap_buffer_info.second, 0);
  3086. // Buffers: 0-8192, 8192-12288
  3087. ASSERT_EQ(std::get<0>(buffer_info[0]), 0);
  3088. ASSERT_EQ(std::get<1>(buffer_info[0]), 4096 + 8192 / 2);
  3089. ASSERT_EQ(std::get<0>(buffer_info[1]), 4096 + 8192 / 2);
  3090. ASSERT_EQ(std::get<1>(buffer_info[1]), 8192 / 2);
  3091. } else {
  3092. // Read at offset 0 with length 4096 + 8192 = 12288.
  3093. // Overlap buffer is not used
  3094. ASSERT_EQ(overlap_buffer_info.first, 0);
  3095. ASSERT_EQ(overlap_buffer_info.second, 0);
  3096. // Main buffer contains the requested data + the 8192 of prefetched data
  3097. ASSERT_EQ(std::get<0>(buffer_info[0]), 0);
  3098. ASSERT_EQ(std::get<1>(buffer_info[0]), 4096 + 8192);
  3099. }
  3100. // Simulate a block cache hit
  3101. fpb.UpdateReadPattern(4096, 4096, false);
  3102. ASSERT_TRUE(fpb.TryReadFromCache(IOOptions(), r.get(), 8192 /* offset */,
  3103. 8192 /* n */, &result, &s, for_compaction));
  3104. ASSERT_EQ(s, Status::OK());
  3105. if (!for_compaction) {
  3106. ASSERT_EQ(stats->getAndResetTickerCount(PREFETCH_HITS), 0);
  3107. ASSERT_EQ(stats->getAndResetTickerCount(PREFETCH_BYTES_USEFUL),
  3108. 4096); // 8192-12288
  3109. }
  3110. ASSERT_EQ(strncmp(result.data(), content.substr(8192, 8192).c_str(), 8192),
  3111. 0);
  3112. fpb.TEST_GetOverlapBufferOffsetandSize(overlap_buffer_info);
  3113. fpb.TEST_GetBufferOffsetandSize(buffer_info);
  3114. if (use_async_prefetch) {
  3115. // Our buffers were 0-8192, 8192-12288 at the start so we had some
  3116. // overlapping data in the second buffer
  3117. // We clean up outdated buffers so 0-8192 gets freed for more prefetching.
  3118. // Our remaining buffer 8192-12288 has data that we want, so we can reuse it
  3119. // We end up with: 8192-20480, 20480-24576
  3120. ASSERT_EQ(overlap_buffer_info.first, 0);
  3121. ASSERT_EQ(overlap_buffer_info.second, 0);
  3122. ASSERT_EQ(std::get<0>(buffer_info[0]), 8192);
  3123. ASSERT_EQ(std::get<1>(buffer_info[0]), 8192 + 8192 / 2);
  3124. ASSERT_EQ(std::get<0>(buffer_info[1]), 8192 + (8192 + 8192 / 2));
  3125. ASSERT_EQ(std::get<1>(buffer_info[1]), 8192 / 2);
  3126. } else {
  3127. // We only have 0-12288 cached, so reading from 8192-16384 will trigger a
  3128. // prefetch up through 16384 + 8192 = 24576.
  3129. // Overlap buffer reuses bytes 8192 to 12288
  3130. ASSERT_EQ(overlap_buffer_info.first, 8192);
  3131. ASSERT_EQ(overlap_buffer_info.second, 8192);
  3132. ASSERT_EQ(overlap_buffer_write_ct, 2);
  3133. // We spill to the overlap buffer so the remaining buffer only has the
  3134. // missing and prefetched part
  3135. ASSERT_EQ(std::get<0>(buffer_info[0]), 12288);
  3136. ASSERT_EQ(std::get<1>(buffer_info[0]), 12288);
  3137. }
  3138. ASSERT_TRUE(fpb.TryReadFromCache(IOOptions(), r.get(), 12288 /* offset */,
  3139. 4096 /* n */, &result, &s, for_compaction));
  3140. ASSERT_EQ(s, Status::OK());
  3141. if (!for_compaction) {
  3142. ASSERT_EQ(stats->getAndResetTickerCount(PREFETCH_HITS), 1);
  3143. ASSERT_EQ(stats->getAndResetTickerCount(PREFETCH_BYTES_USEFUL),
  3144. 4096); // 12288-16384
  3145. }
  3146. ASSERT_EQ(strncmp(result.data(), content.substr(12288, 4096).c_str(), 4096),
  3147. 0);
  3148. fpb.TEST_GetOverlapBufferOffsetandSize(overlap_buffer_info);
  3149. fpb.TEST_GetBufferOffsetandSize(buffer_info);
  3150. if (use_async_prefetch) {
  3151. // Same as before: 8192-20480, 20480-24576 (cache hit in first buffer)
  3152. ASSERT_EQ(overlap_buffer_info.first, 0);
  3153. ASSERT_EQ(overlap_buffer_info.second, 0);
  3154. ASSERT_EQ(std::get<0>(buffer_info[0]), 8192);
  3155. ASSERT_EQ(std::get<1>(buffer_info[0]), 8192 + 8192 / 2);
  3156. ASSERT_EQ(std::get<0>(buffer_info[1]), 8192 + (8192 + 8192 / 2));
  3157. ASSERT_EQ(std::get<1>(buffer_info[1]), 8192 / 2);
  3158. } else {
  3159. // The main buffer has 12288-24576, so 12288-16384 is a cache hit.
  3160. // Overlap buffer does not get used
  3161. fpb.TEST_GetOverlapBufferOffsetandSize(overlap_buffer_info);
  3162. ASSERT_EQ(overlap_buffer_info.first, 8192);
  3163. ASSERT_EQ(overlap_buffer_info.second, 8192);
  3164. ASSERT_EQ(overlap_buffer_write_ct, 2);
  3165. // Main buffer stays the same
  3166. ASSERT_EQ(std::get<0>(buffer_info[0]), 12288);
  3167. ASSERT_EQ(std::get<1>(buffer_info[0]), 12288);
  3168. }
  3169. // Read from 16000-26000 (start and end do not meet normal alignment)
  3170. ASSERT_TRUE(fpb.TryReadFromCache(IOOptions(), r.get(), 16000 /* offset */,
  3171. 10000 /* n */, &result, &s, for_compaction));
  3172. ASSERT_EQ(s, Status::OK());
  3173. if (!for_compaction) {
  3174. ASSERT_EQ(stats->getAndResetTickerCount(PREFETCH_HITS), 0);
  3175. ASSERT_EQ(
  3176. stats->getAndResetTickerCount(PREFETCH_BYTES_USEFUL),
  3177. /* 24576(end offset of the buffer) - 16000(requested offset) =*/8576);
  3178. }
  3179. ASSERT_EQ(strncmp(result.data(), content.substr(16000, 10000).c_str(), 10000),
  3180. 0);
  3181. fpb.TEST_GetOverlapBufferOffsetandSize(overlap_buffer_info);
  3182. fpb.TEST_GetBufferOffsetandSize(buffer_info);
  3183. if (use_async_prefetch) {
  3184. // Overlap buffer reuses bytes 16000 to 20480
  3185. ASSERT_EQ(overlap_buffer_info.first, 16000);
  3186. ASSERT_EQ(overlap_buffer_info.second, 10000);
  3187. // First 2 writes are reusing existing 2 buffers. Last write fills in
  3188. // what could not be found in either.
  3189. ASSERT_EQ(overlap_buffer_write_ct, 3);
  3190. ASSERT_EQ(std::get<0>(buffer_info[0]), 24576);
  3191. ASSERT_EQ(std::get<1>(buffer_info[0]), 32768 - 24576);
  3192. ASSERT_EQ(std::get<0>(buffer_info[1]), 32768);
  3193. ASSERT_EQ(std::get<1>(buffer_info[1]), 4096);
  3194. ASSERT_TRUE(std::get<2>(
  3195. buffer_info[1])); // in progress async request (otherwise we should not
  3196. // be getting 4096 for the size)
  3197. } else {
  3198. // Overlap buffer reuses bytes 16000 to 24576
  3199. ASSERT_EQ(overlap_buffer_info.first, 16000);
  3200. ASSERT_EQ(overlap_buffer_info.second, 10000);
  3201. ASSERT_EQ(overlap_buffer_write_ct, 4);
  3202. // Even if you try to readahead to offset 16000 + 10000 + 8192, there are
  3203. // only 32768 bytes in the original file
  3204. ASSERT_EQ(std::get<0>(buffer_info[0]), 12288 + 12288);
  3205. ASSERT_EQ(std::get<1>(buffer_info[0]), 8192);
  3206. }
  3207. }
  3208. TEST_P(FSBufferPrefetchTest, FSBufferPrefetchUnalignedReads) {
  3209. // Check that the main buffer, the overlap_buf_, and the secondary buffer (in
  3210. // the case of num_buffers_ > 1) are populated correctly
  3211. // while reading with no regard to alignment
  3212. std::string fname = "fs-buffer-prefetch-unaligned-reads";
  3213. Random rand(0);
  3214. std::string content = rand.RandomString(1000);
  3215. Write(fname, content);
  3216. FileOptions opts;
  3217. std::unique_ptr<RandomAccessFileReader> r;
  3218. Read(fname, opts, &r);
  3219. std::shared_ptr<Statistics> stats = CreateDBStatistics();
  3220. ReadaheadParams readahead_params;
  3221. // Readahead size will double each time
  3222. readahead_params.initial_readahead_size = 5;
  3223. readahead_params.max_readahead_size = 100;
  3224. bool use_async_prefetch = std::get<0>(GetParam());
  3225. bool for_compaction = std::get<1>(GetParam());
  3226. // We disallow async IO for compaction reads since they are background
  3227. // operations anyways and their latencies are not visible to the end user
  3228. if (use_async_prefetch && for_compaction) {
  3229. return;
  3230. }
  3231. size_t num_buffers = use_async_prefetch ? 2 : 1;
  3232. readahead_params.num_buffers = num_buffers;
  3233. FilePrefetchBuffer fpb(readahead_params, true /* enable */,
  3234. false /* track_min_offset */, fs(), clock(),
  3235. stats.get());
  3236. int overlap_buffer_write_ct = 0;
  3237. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  3238. "FilePrefetchBuffer::CopyDataToOverlapBuffer:Complete",
  3239. [&](void* /*arg*/) { overlap_buffer_write_ct++; });
  3240. SyncPoint::GetInstance()->EnableProcessing();
  3241. Slice result;
  3242. // Read 3 bytes at offset 5
  3243. Status s;
  3244. std::vector<std::tuple<uint64_t, size_t, bool>> buffer_info(num_buffers);
  3245. std::pair<uint64_t, size_t> overlap_buffer_info;
  3246. bool could_read_from_cache =
  3247. fpb.TryReadFromCache(IOOptions(), r.get(), 5 /* offset */, 3 /* n */,
  3248. &result, &s, for_compaction);
  3249. // Platforms that don't have IO uring may not support async IO.
  3250. if (use_async_prefetch && s.IsNotSupported()) {
  3251. return;
  3252. }
  3253. ASSERT_TRUE(could_read_from_cache);
  3254. ASSERT_EQ(s, Status::OK());
  3255. ASSERT_EQ(strncmp(result.data(), content.substr(5, 3).c_str(), 3), 0);
  3256. fpb.TEST_GetOverlapBufferOffsetandSize(overlap_buffer_info);
  3257. fpb.TEST_GetBufferOffsetandSize(buffer_info);
  3258. if (use_async_prefetch) {
  3259. // Overlap buffer is not used
  3260. ASSERT_EQ(overlap_buffer_info.first, 0);
  3261. ASSERT_EQ(overlap_buffer_info.second, 0);
  3262. // With async prefetching, we still try to align to 4096 bytes, so
  3263. // our main buffer read and secondary buffer prefetch are rounded up
  3264. ASSERT_EQ(std::get<0>(buffer_info[0]), 0);
  3265. ASSERT_EQ(std::get<1>(buffer_info[0]), 1000);
  3266. // This buffer won't actually get filled up with data since there is nothing
  3267. // after 1000
  3268. ASSERT_EQ(std::get<0>(buffer_info[1]), 4096);
  3269. ASSERT_EQ(std::get<1>(buffer_info[1]), 4096);
  3270. ASSERT_TRUE(std::get<2>(buffer_info[1])); // in progress async request
  3271. } else {
  3272. // Overlap buffer is not used
  3273. ASSERT_EQ(overlap_buffer_info.first, 0);
  3274. ASSERT_EQ(overlap_buffer_info.second, 0);
  3275. // Main buffer contains the requested data + 5 of prefetched data (5 - 13)
  3276. ASSERT_EQ(std::get<0>(buffer_info[0]), 5);
  3277. ASSERT_EQ(std::get<1>(buffer_info[0]), 3 + 5);
  3278. }
  3279. ASSERT_TRUE(fpb.TryReadFromCache(IOOptions(), r.get(), 16 /* offset */,
  3280. 7 /* n */, &result, &s, for_compaction));
  3281. ASSERT_EQ(s, Status::OK());
  3282. ASSERT_EQ(strncmp(result.data(), content.substr(16, 7).c_str(), 7), 0);
  3283. fpb.TEST_GetOverlapBufferOffsetandSize(overlap_buffer_info);
  3284. fpb.TEST_GetBufferOffsetandSize(buffer_info);
  3285. if (use_async_prefetch) {
  3286. // Complete hit since we have the entire file loaded in the main buffer
  3287. // The remaining requests will be the same when use_async_prefetch is true
  3288. ASSERT_EQ(overlap_buffer_info.first, 0);
  3289. ASSERT_EQ(overlap_buffer_info.second, 0);
  3290. ASSERT_EQ(std::get<0>(buffer_info[0]), 0);
  3291. ASSERT_EQ(std::get<1>(buffer_info[0]), 1000);
  3292. } else {
  3293. // Complete miss: read 7 bytes at offset 16
  3294. // Overlap buffer is not used (no partial hit)
  3295. ASSERT_EQ(overlap_buffer_info.first, 0);
  3296. ASSERT_EQ(overlap_buffer_info.second, 0);
  3297. // Main buffer contains the requested data + 10 of prefetched data (16 - 33)
  3298. ASSERT_EQ(std::get<0>(buffer_info[0]), 16);
  3299. ASSERT_EQ(std::get<1>(buffer_info[0]), 7 + 10);
  3300. }
  3301. // Go backwards
  3302. if (use_async_prefetch) {
  3303. ASSERT_TRUE(fpb.TryReadFromCache(IOOptions(), r.get(), 10 /* offset */,
  3304. 8 /* n */, &result, &s, for_compaction));
  3305. } else {
  3306. // TryReadFromCacheUntracked returns false since the offset
  3307. // requested is less than the start of our buffer
  3308. ASSERT_FALSE(fpb.TryReadFromCache(IOOptions(), r.get(), 10 /* offset */,
  3309. 8 /* n */, &result, &s, for_compaction));
  3310. }
  3311. ASSERT_EQ(s, Status::OK());
  3312. ASSERT_TRUE(fpb.TryReadFromCache(IOOptions(), r.get(), 27 /* offset */,
  3313. 6 /* n */, &result, &s, for_compaction));
  3314. ASSERT_EQ(s, Status::OK());
  3315. ASSERT_EQ(strncmp(result.data(), content.substr(27, 6).c_str(), 6), 0);
  3316. fpb.TEST_GetOverlapBufferOffsetandSize(overlap_buffer_info);
  3317. fpb.TEST_GetBufferOffsetandSize(buffer_info);
  3318. if (use_async_prefetch) {
  3319. // Complete hit since we have the entire file loaded in the main buffer
  3320. ASSERT_EQ(overlap_buffer_info.first, 0);
  3321. ASSERT_EQ(overlap_buffer_info.second, 0);
  3322. ASSERT_EQ(std::get<0>(buffer_info[0]), 0);
  3323. ASSERT_EQ(std::get<1>(buffer_info[0]), 1000);
  3324. } else {
  3325. // Complete hit
  3326. // Overlap buffer still not used
  3327. ASSERT_EQ(overlap_buffer_info.first, 0);
  3328. ASSERT_EQ(overlap_buffer_info.second, 0);
  3329. // Main buffer unchanged
  3330. ASSERT_EQ(std::get<0>(buffer_info[0]), 16);
  3331. ASSERT_EQ(std::get<1>(buffer_info[0]), 7 + 10);
  3332. }
  3333. ASSERT_TRUE(fpb.TryReadFromCache(IOOptions(), r.get(), 30 /* offset */,
  3334. 20 /* n */, &result, &s, for_compaction));
  3335. ASSERT_EQ(s, Status::OK());
  3336. ASSERT_EQ(strncmp(result.data(), content.substr(30, 20).c_str(), 20), 0);
  3337. fpb.TEST_GetOverlapBufferOffsetandSize(overlap_buffer_info);
  3338. fpb.TEST_GetBufferOffsetandSize(buffer_info);
  3339. if (use_async_prefetch) {
  3340. // Complete hit since we have the entire file loaded in the main buffer
  3341. ASSERT_EQ(overlap_buffer_info.first, 0);
  3342. ASSERT_EQ(overlap_buffer_info.second, 0);
  3343. ASSERT_EQ(std::get<0>(buffer_info[0]), 0);
  3344. ASSERT_EQ(std::get<1>(buffer_info[0]), 1000);
  3345. } else {
  3346. // Partial hit (overlapping with end of main buffer)
  3347. // Overlap buffer is used because we already had 30-33
  3348. ASSERT_EQ(overlap_buffer_info.first, 30);
  3349. ASSERT_EQ(overlap_buffer_info.second, 20);
  3350. ASSERT_EQ(overlap_buffer_write_ct, 2);
  3351. // Main buffer has up to offset 50 + 20 of prefetched data
  3352. ASSERT_EQ(std::get<0>(buffer_info[0]), 33);
  3353. ASSERT_EQ(std::get<1>(buffer_info[0]), (50 - 33) + 20);
  3354. }
  3355. }
  3356. TEST_P(FSBufferPrefetchTest, FSBufferPrefetchRandomized) {
  3357. // This test is meant to find untested code paths. It does very simple
  3358. // verifications and relies on debug assertions to catch invariant violations
  3359. // We scan through a file reading between 0 and 16 KiB at a time
  3360. std::string fname = "fs-buffer-prefetch-randomized";
  3361. Random rand(0);
  3362. std::string content = rand.RandomString(16 * 1024 * 1024);
  3363. Write(fname, content);
  3364. FileOptions opts;
  3365. std::unique_ptr<RandomAccessFileReader> r;
  3366. Read(fname, opts, &r);
  3367. std::shared_ptr<Statistics> stats = CreateDBStatistics();
  3368. ReadaheadParams readahead_params;
  3369. readahead_params.initial_readahead_size = 512;
  3370. readahead_params.max_readahead_size = 2048;
  3371. bool use_async_prefetch = std::get<0>(GetParam());
  3372. bool for_compaction = std::get<1>(GetParam());
  3373. // Async IO is not enabled for compaction prefetching
  3374. if (use_async_prefetch && for_compaction) {
  3375. return;
  3376. }
  3377. size_t num_buffers = use_async_prefetch ? 2 : 1;
  3378. readahead_params.num_buffers = num_buffers;
  3379. FilePrefetchBuffer fpb(readahead_params, true /* enable */,
  3380. false /* track_min_offset */, fs(), clock(),
  3381. stats.get());
  3382. Slice result;
  3383. Status s;
  3384. uint64_t offset = 0;
  3385. Random rnd(987654);
  3386. for (int i = 0; i < 1000; i++) {
  3387. size_t len = rnd.Uniform(16 * 1024);
  3388. if (offset >= content.size()) {
  3389. std::cout << "Stopped early after " << i << " iterations" << std::endl;
  3390. break;
  3391. }
  3392. bool could_read_from_cache = fpb.TryReadFromCache(
  3393. IOOptions(), r.get(), offset, len, &result, &s, for_compaction);
  3394. // Platforms that don't have IO uring may not support async IO.
  3395. if (use_async_prefetch && s.IsNotSupported()) {
  3396. return;
  3397. }
  3398. ASSERT_TRUE(could_read_from_cache);
  3399. ASSERT_EQ(s, Status::OK());
  3400. ASSERT_EQ(result.size(),
  3401. std::min(len, content.size() - static_cast<size_t>(offset)));
  3402. ASSERT_EQ(strncmp(result.data(),
  3403. content.substr(offset, offset + len).c_str(), len),
  3404. 0);
  3405. if (i % 4 == 0) {
  3406. // Test reads where we "skip forward" in the file more than we could read
  3407. // ahead
  3408. offset += len + 2 * readahead_params.max_readahead_size;
  3409. } else if (i % 4 == 1) {
  3410. // Test reads where we "skip forward" in the file but should have some
  3411. // overlap with the read ahead data
  3412. offset += len + readahead_params.max_readahead_size / 2;
  3413. } else {
  3414. // Test "back to back" reads (next read starts right at end of previous
  3415. // one)
  3416. offset += len;
  3417. }
  3418. }
  3419. }
  3420. } // namespace ROCKSDB_NAMESPACE
  3421. int main(int argc, char** argv) {
  3422. ROCKSDB_NAMESPACE::port::InstallStackTraceHandler();
  3423. ::testing::InitGoogleTest(&argc, argv);
  3424. return RUN_ALL_TESTS();
  3425. }