write_prepared_transaction_test.cc 137 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524
  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. #ifndef ROCKSDB_LITE
  6. #include "utilities/transactions/transaction_test.h"
  7. #include <algorithm>
  8. #include <atomic>
  9. #include <cinttypes>
  10. #include <functional>
  11. #include <string>
  12. #include <thread>
  13. #include "db/db_impl/db_impl.h"
  14. #include "db/dbformat.h"
  15. #include "rocksdb/db.h"
  16. #include "rocksdb/options.h"
  17. #include "rocksdb/types.h"
  18. #include "rocksdb/utilities/debug.h"
  19. #include "rocksdb/utilities/transaction.h"
  20. #include "rocksdb/utilities/transaction_db.h"
  21. #include "table/mock_table.h"
  22. #include "test_util/fault_injection_test_env.h"
  23. #include "test_util/sync_point.h"
  24. #include "test_util/testharness.h"
  25. #include "test_util/testutil.h"
  26. #include "test_util/transaction_test_util.h"
  27. #include "util/mutexlock.h"
  28. #include "util/random.h"
  29. #include "util/string_util.h"
  30. #include "utilities/merge_operators.h"
  31. #include "utilities/merge_operators/string_append/stringappend.h"
  32. #include "utilities/transactions/pessimistic_transaction_db.h"
  33. #include "utilities/transactions/write_prepared_txn_db.h"
  34. #include "port/port.h"
  35. using std::string;
  36. namespace ROCKSDB_NAMESPACE {
  37. using CommitEntry = WritePreparedTxnDB::CommitEntry;
  38. using CommitEntry64b = WritePreparedTxnDB::CommitEntry64b;
  39. using CommitEntry64bFormat = WritePreparedTxnDB::CommitEntry64bFormat;
  40. TEST(PreparedHeap, BasicsTest) {
  41. WritePreparedTxnDB::PreparedHeap heap;
  42. {
  43. MutexLock ml(heap.push_pop_mutex());
  44. heap.push(14l);
  45. // Test with one element
  46. ASSERT_EQ(14l, heap.top());
  47. heap.push(24l);
  48. heap.push(34l);
  49. // Test that old min is still on top
  50. ASSERT_EQ(14l, heap.top());
  51. heap.push(44l);
  52. heap.push(54l);
  53. heap.push(64l);
  54. heap.push(74l);
  55. heap.push(84l);
  56. }
  57. // Test that old min is still on top
  58. ASSERT_EQ(14l, heap.top());
  59. heap.erase(24l);
  60. // Test that old min is still on top
  61. ASSERT_EQ(14l, heap.top());
  62. heap.erase(14l);
  63. // Test that the new comes to the top after multiple erase
  64. ASSERT_EQ(34l, heap.top());
  65. heap.erase(34l);
  66. // Test that the new comes to the top after single erase
  67. ASSERT_EQ(44l, heap.top());
  68. heap.erase(54l);
  69. ASSERT_EQ(44l, heap.top());
  70. heap.pop(); // pop 44l
  71. // Test that the erased items are ignored after pop
  72. ASSERT_EQ(64l, heap.top());
  73. heap.erase(44l);
  74. // Test that erasing an already popped item would work
  75. ASSERT_EQ(64l, heap.top());
  76. heap.erase(84l);
  77. ASSERT_EQ(64l, heap.top());
  78. {
  79. MutexLock ml(heap.push_pop_mutex());
  80. heap.push(85l);
  81. heap.push(86l);
  82. heap.push(87l);
  83. heap.push(88l);
  84. heap.push(89l);
  85. }
  86. heap.erase(87l);
  87. heap.erase(85l);
  88. heap.erase(89l);
  89. heap.erase(86l);
  90. heap.erase(88l);
  91. // Test top remains the same after a random order of many erases
  92. ASSERT_EQ(64l, heap.top());
  93. heap.pop();
  94. // Test that pop works with a series of random pending erases
  95. ASSERT_EQ(74l, heap.top());
  96. ASSERT_FALSE(heap.empty());
  97. heap.pop();
  98. // Test that empty works
  99. ASSERT_TRUE(heap.empty());
  100. }
  101. // This is a scenario reconstructed from a buggy trace. Test that the bug does
  102. // not resurface again.
  103. TEST(PreparedHeap, EmptyAtTheEnd) {
  104. WritePreparedTxnDB::PreparedHeap heap;
  105. {
  106. MutexLock ml(heap.push_pop_mutex());
  107. heap.push(40l);
  108. }
  109. ASSERT_EQ(40l, heap.top());
  110. // Although not a recommended scenario, we must be resilient against erase
  111. // without a prior push.
  112. heap.erase(50l);
  113. ASSERT_EQ(40l, heap.top());
  114. {
  115. MutexLock ml(heap.push_pop_mutex());
  116. heap.push(60l);
  117. }
  118. ASSERT_EQ(40l, heap.top());
  119. heap.erase(60l);
  120. ASSERT_EQ(40l, heap.top());
  121. heap.erase(40l);
  122. ASSERT_TRUE(heap.empty());
  123. {
  124. MutexLock ml(heap.push_pop_mutex());
  125. heap.push(40l);
  126. }
  127. ASSERT_EQ(40l, heap.top());
  128. heap.erase(50l);
  129. ASSERT_EQ(40l, heap.top());
  130. {
  131. MutexLock ml(heap.push_pop_mutex());
  132. heap.push(60l);
  133. }
  134. ASSERT_EQ(40l, heap.top());
  135. heap.erase(40l);
  136. // Test that the erase has not emptied the heap (we had a bug doing that)
  137. ASSERT_FALSE(heap.empty());
  138. ASSERT_EQ(60l, heap.top());
  139. heap.erase(60l);
  140. ASSERT_TRUE(heap.empty());
  141. }
  142. // Generate random order of PreparedHeap access and test that the heap will be
  143. // successfully emptied at the end.
  144. TEST(PreparedHeap, Concurrent) {
  145. const size_t t_cnt = 10;
  146. ROCKSDB_NAMESPACE::port::Thread t[t_cnt + 1];
  147. WritePreparedTxnDB::PreparedHeap heap;
  148. port::RWMutex prepared_mutex;
  149. std::atomic<size_t> last;
  150. for (size_t n = 0; n < 100; n++) {
  151. last = 0;
  152. t[0] = ROCKSDB_NAMESPACE::port::Thread([&]() {
  153. Random rnd(1103);
  154. for (size_t seq = 1; seq <= t_cnt; seq++) {
  155. // This is not recommended usage but we should be resilient against it.
  156. bool skip_push = rnd.OneIn(5);
  157. if (!skip_push) {
  158. MutexLock ml(heap.push_pop_mutex());
  159. std::this_thread::yield();
  160. heap.push(seq);
  161. last.store(seq);
  162. }
  163. }
  164. });
  165. for (size_t i = 1; i <= t_cnt; i++) {
  166. t[i] =
  167. ROCKSDB_NAMESPACE::port::Thread([&heap, &prepared_mutex, &last, i]() {
  168. auto seq = i;
  169. do {
  170. std::this_thread::yield();
  171. } while (last.load() < seq);
  172. WriteLock wl(&prepared_mutex);
  173. heap.erase(seq);
  174. });
  175. }
  176. for (size_t i = 0; i <= t_cnt; i++) {
  177. t[i].join();
  178. }
  179. ASSERT_TRUE(heap.empty());
  180. }
  181. }
  182. // Test that WriteBatchWithIndex correctly counts the number of sub-batches
  183. TEST(WriteBatchWithIndex, SubBatchCnt) {
  184. ColumnFamilyOptions cf_options;
  185. std::string cf_name = "two";
  186. DB* db;
  187. Options options;
  188. options.create_if_missing = true;
  189. const std::string dbname = test::PerThreadDBPath("transaction_testdb");
  190. DestroyDB(dbname, options);
  191. ASSERT_OK(DB::Open(options, dbname, &db));
  192. ColumnFamilyHandle* cf_handle = nullptr;
  193. ASSERT_OK(db->CreateColumnFamily(cf_options, cf_name, &cf_handle));
  194. WriteOptions write_options;
  195. size_t batch_cnt = 1;
  196. size_t save_points = 0;
  197. std::vector<size_t> batch_cnt_at;
  198. WriteBatchWithIndex batch(db->DefaultColumnFamily()->GetComparator(), 0, true,
  199. 0);
  200. ASSERT_EQ(batch_cnt, batch.SubBatchCnt());
  201. batch_cnt_at.push_back(batch_cnt);
  202. batch.SetSavePoint();
  203. save_points++;
  204. batch.Put(Slice("key"), Slice("value"));
  205. ASSERT_EQ(batch_cnt, batch.SubBatchCnt());
  206. batch_cnt_at.push_back(batch_cnt);
  207. batch.SetSavePoint();
  208. save_points++;
  209. batch.Put(Slice("key2"), Slice("value2"));
  210. ASSERT_EQ(batch_cnt, batch.SubBatchCnt());
  211. // duplicate the keys
  212. batch_cnt_at.push_back(batch_cnt);
  213. batch.SetSavePoint();
  214. save_points++;
  215. batch.Put(Slice("key"), Slice("value3"));
  216. batch_cnt++;
  217. ASSERT_EQ(batch_cnt, batch.SubBatchCnt());
  218. // duplicate the 2nd key. It should not be counted duplicate since a
  219. // sub-patch is cut after the last duplicate.
  220. batch_cnt_at.push_back(batch_cnt);
  221. batch.SetSavePoint();
  222. save_points++;
  223. batch.Put(Slice("key2"), Slice("value4"));
  224. ASSERT_EQ(batch_cnt, batch.SubBatchCnt());
  225. // duplicate the keys but in a different cf. It should not be counted as
  226. // duplicate keys
  227. batch_cnt_at.push_back(batch_cnt);
  228. batch.SetSavePoint();
  229. save_points++;
  230. batch.Put(cf_handle, Slice("key"), Slice("value5"));
  231. ASSERT_EQ(batch_cnt, batch.SubBatchCnt());
  232. // Test that the number of sub-batches matches what we count with
  233. // SubBatchCounter
  234. std::map<uint32_t, const Comparator*> comparators;
  235. comparators[0] = db->DefaultColumnFamily()->GetComparator();
  236. comparators[cf_handle->GetID()] = cf_handle->GetComparator();
  237. SubBatchCounter counter(comparators);
  238. ASSERT_OK(batch.GetWriteBatch()->Iterate(&counter));
  239. ASSERT_EQ(batch_cnt, counter.BatchCount());
  240. // Test that RollbackToSavePoint will properly resets the number of
  241. // sub-batches
  242. for (size_t i = save_points; i > 0; i--) {
  243. batch.RollbackToSavePoint();
  244. ASSERT_EQ(batch_cnt_at[i - 1], batch.SubBatchCnt());
  245. }
  246. // Test the count is right with random batches
  247. {
  248. const size_t TOTAL_KEYS = 20; // 20 ~= 10 to cause a few randoms
  249. Random rnd(1131);
  250. std::string keys[TOTAL_KEYS];
  251. for (size_t k = 0; k < TOTAL_KEYS; k++) {
  252. int len = static_cast<int>(rnd.Uniform(50));
  253. keys[k] = test::RandomKey(&rnd, len);
  254. }
  255. for (size_t i = 0; i < 1000; i++) { // 1000 random batches
  256. WriteBatchWithIndex rndbatch(db->DefaultColumnFamily()->GetComparator(),
  257. 0, true, 0);
  258. for (size_t k = 0; k < 10; k++) { // 10 key per batch
  259. size_t ki = static_cast<size_t>(rnd.Uniform(TOTAL_KEYS));
  260. Slice key = Slice(keys[ki]);
  261. std::string buffer;
  262. Slice value = Slice(test::RandomString(&rnd, 16, &buffer));
  263. rndbatch.Put(key, value);
  264. }
  265. SubBatchCounter batch_counter(comparators);
  266. ASSERT_OK(rndbatch.GetWriteBatch()->Iterate(&batch_counter));
  267. ASSERT_EQ(rndbatch.SubBatchCnt(), batch_counter.BatchCount());
  268. }
  269. }
  270. delete cf_handle;
  271. delete db;
  272. }
  273. TEST(CommitEntry64b, BasicTest) {
  274. const size_t INDEX_BITS = static_cast<size_t>(21);
  275. const size_t INDEX_SIZE = static_cast<size_t>(1ull << INDEX_BITS);
  276. const CommitEntry64bFormat FORMAT(static_cast<size_t>(INDEX_BITS));
  277. // zero-initialized CommitEntry64b should indicate an empty entry
  278. CommitEntry64b empty_entry64b;
  279. uint64_t empty_index = 11ul;
  280. CommitEntry empty_entry;
  281. bool ok = empty_entry64b.Parse(empty_index, &empty_entry, FORMAT);
  282. ASSERT_FALSE(ok);
  283. // the zero entry is reserved for un-initialized entries
  284. const size_t MAX_COMMIT = (1 << FORMAT.COMMIT_BITS) - 1 - 1;
  285. // Samples over the numbers that are covered by that many index bits
  286. std::array<uint64_t, 4> is = {{0, 1, INDEX_SIZE / 2 + 1, INDEX_SIZE - 1}};
  287. // Samples over the numbers that are covered by that many commit bits
  288. std::array<uint64_t, 4> ds = {{0, 1, MAX_COMMIT / 2 + 1, MAX_COMMIT}};
  289. // Iterate over prepare numbers that have i) cover all bits of a sequence
  290. // number, and ii) include some bits that fall into the range of index or
  291. // commit bits
  292. for (uint64_t base = 1; base < kMaxSequenceNumber; base *= 2) {
  293. for (uint64_t i : is) {
  294. for (uint64_t d : ds) {
  295. uint64_t p = base + i + d;
  296. for (uint64_t c : {p, p + d / 2, p + d}) {
  297. uint64_t index = p % INDEX_SIZE;
  298. CommitEntry before(p, c), after;
  299. CommitEntry64b entry64b(before, FORMAT);
  300. ok = entry64b.Parse(index, &after, FORMAT);
  301. ASSERT_TRUE(ok);
  302. if (!(before == after)) {
  303. printf("base %" PRIu64 " i %" PRIu64 " d %" PRIu64 " p %" PRIu64
  304. " c %" PRIu64 " index %" PRIu64 "\n",
  305. base, i, d, p, c, index);
  306. }
  307. ASSERT_EQ(before, after);
  308. }
  309. }
  310. }
  311. }
  312. }
  313. class WritePreparedTxnDBMock : public WritePreparedTxnDB {
  314. public:
  315. WritePreparedTxnDBMock(DBImpl* db_impl, TransactionDBOptions& opt)
  316. : WritePreparedTxnDB(db_impl, opt) {}
  317. void SetDBSnapshots(const std::vector<SequenceNumber>& snapshots) {
  318. snapshots_ = snapshots;
  319. }
  320. void TakeSnapshot(SequenceNumber seq) { snapshots_.push_back(seq); }
  321. protected:
  322. const std::vector<SequenceNumber> GetSnapshotListFromDB(
  323. SequenceNumber /* unused */) override {
  324. return snapshots_;
  325. }
  326. private:
  327. std::vector<SequenceNumber> snapshots_;
  328. };
  329. class WritePreparedTransactionTestBase : public TransactionTestBase {
  330. public:
  331. WritePreparedTransactionTestBase(bool use_stackable_db, bool two_write_queue,
  332. TxnDBWritePolicy write_policy,
  333. WriteOrdering write_ordering)
  334. : TransactionTestBase(use_stackable_db, two_write_queue, write_policy,
  335. write_ordering){};
  336. protected:
  337. void UpdateTransactionDBOptions(size_t snapshot_cache_bits,
  338. size_t commit_cache_bits) {
  339. txn_db_options.wp_snapshot_cache_bits = snapshot_cache_bits;
  340. txn_db_options.wp_commit_cache_bits = commit_cache_bits;
  341. }
  342. void UpdateTransactionDBOptions(size_t snapshot_cache_bits) {
  343. txn_db_options.wp_snapshot_cache_bits = snapshot_cache_bits;
  344. }
  345. // If expect_update is set, check if it actually updated old_commit_map_. If
  346. // it did not and yet suggested not to check the next snapshot, do the
  347. // opposite to check if it was not a bad suggestion.
  348. void MaybeUpdateOldCommitMapTestWithNext(uint64_t prepare, uint64_t commit,
  349. uint64_t snapshot,
  350. uint64_t next_snapshot,
  351. bool expect_update) {
  352. WritePreparedTxnDB* wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  353. // reset old_commit_map_empty_ so that its value indicate whether
  354. // old_commit_map_ was updated
  355. wp_db->old_commit_map_empty_ = true;
  356. bool check_next = wp_db->MaybeUpdateOldCommitMap(prepare, commit, snapshot,
  357. snapshot < next_snapshot);
  358. if (expect_update == wp_db->old_commit_map_empty_) {
  359. printf("prepare: %" PRIu64 " commit: %" PRIu64 " snapshot: %" PRIu64
  360. " next: %" PRIu64 "\n",
  361. prepare, commit, snapshot, next_snapshot);
  362. }
  363. EXPECT_EQ(!expect_update, wp_db->old_commit_map_empty_);
  364. if (!check_next && wp_db->old_commit_map_empty_) {
  365. // do the opposite to make sure it was not a bad suggestion
  366. const bool dont_care_bool = true;
  367. wp_db->MaybeUpdateOldCommitMap(prepare, commit, next_snapshot,
  368. dont_care_bool);
  369. if (!wp_db->old_commit_map_empty_) {
  370. printf("prepare: %" PRIu64 " commit: %" PRIu64 " snapshot: %" PRIu64
  371. " next: %" PRIu64 "\n",
  372. prepare, commit, snapshot, next_snapshot);
  373. }
  374. EXPECT_TRUE(wp_db->old_commit_map_empty_);
  375. }
  376. }
  377. // Test that a CheckAgainstSnapshots thread reading old_snapshots will not
  378. // miss a snapshot because of a concurrent update by UpdateSnapshots that is
  379. // writing new_snapshots. Both threads are broken at two points. The sync
  380. // points to enforce them are specified by a1, a2, b1, and b2. CommitEntry
  381. // entry is expected to be vital for one of the snapshots that is common
  382. // between the old and new list of snapshots.
  383. void SnapshotConcurrentAccessTestInternal(
  384. WritePreparedTxnDB* wp_db,
  385. const std::vector<SequenceNumber>& old_snapshots,
  386. const std::vector<SequenceNumber>& new_snapshots, CommitEntry& entry,
  387. SequenceNumber& version, size_t a1, size_t a2, size_t b1, size_t b2) {
  388. // First reset the snapshot list
  389. const std::vector<SequenceNumber> empty_snapshots;
  390. wp_db->old_commit_map_empty_ = true;
  391. wp_db->UpdateSnapshots(empty_snapshots, ++version);
  392. // Then initialize it with the old_snapshots
  393. wp_db->UpdateSnapshots(old_snapshots, ++version);
  394. // Starting from the first thread, cut each thread at two points
  395. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency({
  396. {"WritePreparedTxnDB::CheckAgainstSnapshots:p:" + std::to_string(a1),
  397. "WritePreparedTxnDB::UpdateSnapshots:s:start"},
  398. {"WritePreparedTxnDB::UpdateSnapshots:p:" + std::to_string(b1),
  399. "WritePreparedTxnDB::CheckAgainstSnapshots:s:" + std::to_string(a1)},
  400. {"WritePreparedTxnDB::CheckAgainstSnapshots:p:" + std::to_string(a2),
  401. "WritePreparedTxnDB::UpdateSnapshots:s:" + std::to_string(b1)},
  402. {"WritePreparedTxnDB::UpdateSnapshots:p:" + std::to_string(b2),
  403. "WritePreparedTxnDB::CheckAgainstSnapshots:s:" + std::to_string(a2)},
  404. {"WritePreparedTxnDB::CheckAgainstSnapshots:p:end",
  405. "WritePreparedTxnDB::UpdateSnapshots:s:" + std::to_string(b2)},
  406. });
  407. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  408. {
  409. ASSERT_TRUE(wp_db->old_commit_map_empty_);
  410. ROCKSDB_NAMESPACE::port::Thread t1(
  411. [&]() { wp_db->UpdateSnapshots(new_snapshots, version); });
  412. ROCKSDB_NAMESPACE::port::Thread t2(
  413. [&]() { wp_db->CheckAgainstSnapshots(entry); });
  414. t1.join();
  415. t2.join();
  416. ASSERT_FALSE(wp_db->old_commit_map_empty_);
  417. }
  418. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  419. wp_db->old_commit_map_empty_ = true;
  420. wp_db->UpdateSnapshots(empty_snapshots, ++version);
  421. wp_db->UpdateSnapshots(old_snapshots, ++version);
  422. // Starting from the second thread, cut each thread at two points
  423. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency({
  424. {"WritePreparedTxnDB::UpdateSnapshots:p:" + std::to_string(a1),
  425. "WritePreparedTxnDB::CheckAgainstSnapshots:s:start"},
  426. {"WritePreparedTxnDB::CheckAgainstSnapshots:p:" + std::to_string(b1),
  427. "WritePreparedTxnDB::UpdateSnapshots:s:" + std::to_string(a1)},
  428. {"WritePreparedTxnDB::UpdateSnapshots:p:" + std::to_string(a2),
  429. "WritePreparedTxnDB::CheckAgainstSnapshots:s:" + std::to_string(b1)},
  430. {"WritePreparedTxnDB::CheckAgainstSnapshots:p:" + std::to_string(b2),
  431. "WritePreparedTxnDB::UpdateSnapshots:s:" + std::to_string(a2)},
  432. {"WritePreparedTxnDB::UpdateSnapshots:p:end",
  433. "WritePreparedTxnDB::CheckAgainstSnapshots:s:" + std::to_string(b2)},
  434. });
  435. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  436. {
  437. ASSERT_TRUE(wp_db->old_commit_map_empty_);
  438. ROCKSDB_NAMESPACE::port::Thread t1(
  439. [&]() { wp_db->UpdateSnapshots(new_snapshots, version); });
  440. ROCKSDB_NAMESPACE::port::Thread t2(
  441. [&]() { wp_db->CheckAgainstSnapshots(entry); });
  442. t1.join();
  443. t2.join();
  444. ASSERT_FALSE(wp_db->old_commit_map_empty_);
  445. }
  446. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  447. }
  448. // Verify value of keys.
  449. void VerifyKeys(const std::unordered_map<std::string, std::string>& data,
  450. const Snapshot* snapshot = nullptr) {
  451. std::string value;
  452. ReadOptions read_options;
  453. read_options.snapshot = snapshot;
  454. for (auto& kv : data) {
  455. auto s = db->Get(read_options, kv.first, &value);
  456. ASSERT_TRUE(s.ok() || s.IsNotFound());
  457. if (s.ok()) {
  458. if (kv.second != value) {
  459. printf("key = %s\n", kv.first.c_str());
  460. }
  461. ASSERT_EQ(kv.second, value);
  462. } else {
  463. ASSERT_EQ(kv.second, "NOT_FOUND");
  464. }
  465. // Try with MultiGet API too
  466. std::vector<std::string> values;
  467. auto s_vec = db->MultiGet(read_options, {db->DefaultColumnFamily()},
  468. {kv.first}, &values);
  469. ASSERT_EQ(1, values.size());
  470. ASSERT_EQ(1, s_vec.size());
  471. s = s_vec[0];
  472. ASSERT_TRUE(s.ok() || s.IsNotFound());
  473. if (s.ok()) {
  474. ASSERT_TRUE(kv.second == values[0]);
  475. } else {
  476. ASSERT_EQ(kv.second, "NOT_FOUND");
  477. }
  478. }
  479. }
  480. // Verify all versions of keys.
  481. void VerifyInternalKeys(const std::vector<KeyVersion>& expected_versions) {
  482. std::vector<KeyVersion> versions;
  483. const size_t kMaxKeys = 100000;
  484. ASSERT_OK(GetAllKeyVersions(db, expected_versions.front().user_key,
  485. expected_versions.back().user_key, kMaxKeys,
  486. &versions));
  487. ASSERT_EQ(expected_versions.size(), versions.size());
  488. for (size_t i = 0; i < versions.size(); i++) {
  489. ASSERT_EQ(expected_versions[i].user_key, versions[i].user_key);
  490. ASSERT_EQ(expected_versions[i].sequence, versions[i].sequence);
  491. ASSERT_EQ(expected_versions[i].type, versions[i].type);
  492. if (versions[i].type != kTypeDeletion &&
  493. versions[i].type != kTypeSingleDeletion) {
  494. ASSERT_EQ(expected_versions[i].value, versions[i].value);
  495. }
  496. // Range delete not supported.
  497. assert(expected_versions[i].type != kTypeRangeDeletion);
  498. }
  499. }
  500. };
  501. class WritePreparedTransactionTest
  502. : public WritePreparedTransactionTestBase,
  503. virtual public ::testing::WithParamInterface<
  504. std::tuple<bool, bool, TxnDBWritePolicy, WriteOrdering>> {
  505. public:
  506. WritePreparedTransactionTest()
  507. : WritePreparedTransactionTestBase(
  508. std::get<0>(GetParam()), std::get<1>(GetParam()),
  509. std::get<2>(GetParam()), std::get<3>(GetParam())){};
  510. };
  511. #ifndef ROCKSDB_VALGRIND_RUN
  512. class SnapshotConcurrentAccessTest
  513. : public WritePreparedTransactionTestBase,
  514. virtual public ::testing::WithParamInterface<std::tuple<
  515. bool, bool, TxnDBWritePolicy, WriteOrdering, size_t, size_t>> {
  516. public:
  517. SnapshotConcurrentAccessTest()
  518. : WritePreparedTransactionTestBase(
  519. std::get<0>(GetParam()), std::get<1>(GetParam()),
  520. std::get<2>(GetParam()), std::get<3>(GetParam())),
  521. split_id_(std::get<4>(GetParam())),
  522. split_cnt_(std::get<5>(GetParam())){};
  523. protected:
  524. // A test is split into split_cnt_ tests, each identified with split_id_ where
  525. // 0 <= split_id_ < split_cnt_
  526. size_t split_id_;
  527. size_t split_cnt_;
  528. };
  529. #endif // ROCKSDB_VALGRIND_RUN
  530. class SeqAdvanceConcurrentTest
  531. : public WritePreparedTransactionTestBase,
  532. virtual public ::testing::WithParamInterface<std::tuple<
  533. bool, bool, TxnDBWritePolicy, WriteOrdering, size_t, size_t>> {
  534. public:
  535. SeqAdvanceConcurrentTest()
  536. : WritePreparedTransactionTestBase(
  537. std::get<0>(GetParam()), std::get<1>(GetParam()),
  538. std::get<2>(GetParam()), std::get<3>(GetParam())),
  539. split_id_(std::get<4>(GetParam())),
  540. split_cnt_(std::get<5>(GetParam())){};
  541. protected:
  542. // A test is split into split_cnt_ tests, each identified with split_id_ where
  543. // 0 <= split_id_ < split_cnt_
  544. size_t split_id_;
  545. size_t split_cnt_;
  546. };
  547. INSTANTIATE_TEST_CASE_P(
  548. WritePreparedTransaction, WritePreparedTransactionTest,
  549. ::testing::Values(
  550. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite),
  551. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite),
  552. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite)));
  553. #ifndef ROCKSDB_VALGRIND_RUN
  554. INSTANTIATE_TEST_CASE_P(
  555. TwoWriteQueues, SnapshotConcurrentAccessTest,
  556. ::testing::Values(
  557. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 0, 20),
  558. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 1, 20),
  559. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 2, 20),
  560. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 3, 20),
  561. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 4, 20),
  562. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 5, 20),
  563. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 6, 20),
  564. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 7, 20),
  565. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 8, 20),
  566. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 9, 20),
  567. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 10, 20),
  568. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 11, 20),
  569. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 12, 20),
  570. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 13, 20),
  571. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 14, 20),
  572. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 15, 20),
  573. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 16, 20),
  574. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 17, 20),
  575. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 18, 20),
  576. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 19, 20),
  577. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 0, 20),
  578. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 1, 20),
  579. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 2, 20),
  580. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 3, 20),
  581. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 4, 20),
  582. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 5, 20),
  583. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 6, 20),
  584. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 7, 20),
  585. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 8, 20),
  586. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 9, 20),
  587. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 10, 20),
  588. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 11, 20),
  589. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 12, 20),
  590. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 13, 20),
  591. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 14, 20),
  592. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 15, 20),
  593. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 16, 20),
  594. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 17, 20),
  595. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 18, 20),
  596. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 19, 20)));
  597. INSTANTIATE_TEST_CASE_P(
  598. OneWriteQueue, SnapshotConcurrentAccessTest,
  599. ::testing::Values(
  600. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 0, 20),
  601. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 1, 20),
  602. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 2, 20),
  603. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 3, 20),
  604. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 4, 20),
  605. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 5, 20),
  606. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 6, 20),
  607. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 7, 20),
  608. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 8, 20),
  609. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 9, 20),
  610. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 10, 20),
  611. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 11, 20),
  612. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 12, 20),
  613. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 13, 20),
  614. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 14, 20),
  615. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 15, 20),
  616. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 16, 20),
  617. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 17, 20),
  618. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 18, 20),
  619. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 19, 20)));
  620. INSTANTIATE_TEST_CASE_P(
  621. TwoWriteQueues, SeqAdvanceConcurrentTest,
  622. ::testing::Values(
  623. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 0, 10),
  624. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 1, 10),
  625. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 2, 10),
  626. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 3, 10),
  627. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 4, 10),
  628. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 5, 10),
  629. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 6, 10),
  630. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 7, 10),
  631. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 8, 10),
  632. std::make_tuple(false, true, WRITE_PREPARED, kOrderedWrite, 9, 10),
  633. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 0, 10),
  634. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 1, 10),
  635. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 2, 10),
  636. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 3, 10),
  637. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 4, 10),
  638. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 5, 10),
  639. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 6, 10),
  640. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 7, 10),
  641. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 8, 10),
  642. std::make_tuple(false, true, WRITE_PREPARED, kUnorderedWrite, 9, 10)));
  643. INSTANTIATE_TEST_CASE_P(
  644. OneWriteQueue, SeqAdvanceConcurrentTest,
  645. ::testing::Values(
  646. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 0, 10),
  647. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 1, 10),
  648. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 2, 10),
  649. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 3, 10),
  650. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 4, 10),
  651. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 5, 10),
  652. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 6, 10),
  653. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 7, 10),
  654. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 8, 10),
  655. std::make_tuple(false, false, WRITE_PREPARED, kOrderedWrite, 9, 10)));
  656. #endif // ROCKSDB_VALGRIND_RUN
  657. TEST_P(WritePreparedTransactionTest, CommitMap) {
  658. WritePreparedTxnDB* wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  659. assert(wp_db);
  660. assert(wp_db->db_impl_);
  661. size_t size = wp_db->COMMIT_CACHE_SIZE;
  662. CommitEntry c = {5, 12}, e;
  663. bool evicted = wp_db->AddCommitEntry(c.prep_seq % size, c, &e);
  664. ASSERT_FALSE(evicted);
  665. // Should be able to read the same value
  666. CommitEntry64b dont_care;
  667. bool found = wp_db->GetCommitEntry(c.prep_seq % size, &dont_care, &e);
  668. ASSERT_TRUE(found);
  669. ASSERT_EQ(c, e);
  670. // Should be able to distinguish between overlapping entries
  671. found = wp_db->GetCommitEntry((c.prep_seq + size) % size, &dont_care, &e);
  672. ASSERT_TRUE(found);
  673. ASSERT_NE(c.prep_seq + size, e.prep_seq);
  674. // Should be able to detect non-existent entry
  675. found = wp_db->GetCommitEntry((c.prep_seq + 1) % size, &dont_care, &e);
  676. ASSERT_FALSE(found);
  677. // Reject an invalid exchange
  678. CommitEntry e2 = {c.prep_seq + size, c.commit_seq + size};
  679. CommitEntry64b e2_64b(e2, wp_db->FORMAT);
  680. bool exchanged = wp_db->ExchangeCommitEntry(e2.prep_seq % size, e2_64b, e);
  681. ASSERT_FALSE(exchanged);
  682. // check whether it did actually reject that
  683. found = wp_db->GetCommitEntry(e2.prep_seq % size, &dont_care, &e);
  684. ASSERT_TRUE(found);
  685. ASSERT_EQ(c, e);
  686. // Accept a valid exchange
  687. CommitEntry64b c_64b(c, wp_db->FORMAT);
  688. CommitEntry e3 = {c.prep_seq + size, c.commit_seq + size + 1};
  689. exchanged = wp_db->ExchangeCommitEntry(c.prep_seq % size, c_64b, e3);
  690. ASSERT_TRUE(exchanged);
  691. // check whether it did actually accepted that
  692. found = wp_db->GetCommitEntry(c.prep_seq % size, &dont_care, &e);
  693. ASSERT_TRUE(found);
  694. ASSERT_EQ(e3, e);
  695. // Rewrite an entry
  696. CommitEntry e4 = {e3.prep_seq + size, e3.commit_seq + size + 1};
  697. evicted = wp_db->AddCommitEntry(e4.prep_seq % size, e4, &e);
  698. ASSERT_TRUE(evicted);
  699. ASSERT_EQ(e3, e);
  700. found = wp_db->GetCommitEntry(e4.prep_seq % size, &dont_care, &e);
  701. ASSERT_TRUE(found);
  702. ASSERT_EQ(e4, e);
  703. }
  704. TEST_P(WritePreparedTransactionTest, MaybeUpdateOldCommitMap) {
  705. // If prepare <= snapshot < commit we should keep the entry around since its
  706. // nonexistence could be interpreted as committed in the snapshot while it is
  707. // not true. We keep such entries around by adding them to the
  708. // old_commit_map_.
  709. uint64_t p /*prepare*/, c /*commit*/, s /*snapshot*/, ns /*next_snapshot*/;
  710. p = 10l, c = 15l, s = 20l, ns = 21l;
  711. MaybeUpdateOldCommitMapTestWithNext(p, c, s, ns, false);
  712. // If we do not expect the old commit map to be updated, try also with a next
  713. // snapshot that is expected to update the old commit map. This would test
  714. // that MaybeUpdateOldCommitMap would not prevent us from checking the next
  715. // snapshot that must be checked.
  716. p = 10l, c = 15l, s = 20l, ns = 11l;
  717. MaybeUpdateOldCommitMapTestWithNext(p, c, s, ns, false);
  718. p = 10l, c = 20l, s = 20l, ns = 19l;
  719. MaybeUpdateOldCommitMapTestWithNext(p, c, s, ns, false);
  720. p = 10l, c = 20l, s = 20l, ns = 21l;
  721. MaybeUpdateOldCommitMapTestWithNext(p, c, s, ns, false);
  722. p = 20l, c = 20l, s = 20l, ns = 21l;
  723. MaybeUpdateOldCommitMapTestWithNext(p, c, s, ns, false);
  724. p = 20l, c = 20l, s = 20l, ns = 19l;
  725. MaybeUpdateOldCommitMapTestWithNext(p, c, s, ns, false);
  726. p = 10l, c = 25l, s = 20l, ns = 21l;
  727. MaybeUpdateOldCommitMapTestWithNext(p, c, s, ns, true);
  728. p = 20l, c = 25l, s = 20l, ns = 21l;
  729. MaybeUpdateOldCommitMapTestWithNext(p, c, s, ns, true);
  730. p = 21l, c = 25l, s = 20l, ns = 22l;
  731. MaybeUpdateOldCommitMapTestWithNext(p, c, s, ns, false);
  732. p = 21l, c = 25l, s = 20l, ns = 19l;
  733. MaybeUpdateOldCommitMapTestWithNext(p, c, s, ns, false);
  734. }
  735. // Trigger the condition where some old memtables are skipped when doing
  736. // TransactionUtil::CheckKey(), and make sure the result is still correct.
  737. TEST_P(WritePreparedTransactionTest, CheckKeySkipOldMemtable) {
  738. const int kAttemptHistoryMemtable = 0;
  739. const int kAttemptImmMemTable = 1;
  740. for (int attempt = kAttemptHistoryMemtable; attempt <= kAttemptImmMemTable;
  741. attempt++) {
  742. options.max_write_buffer_number_to_maintain = 3;
  743. ReOpen();
  744. WriteOptions write_options;
  745. ReadOptions read_options;
  746. TransactionOptions txn_options;
  747. txn_options.set_snapshot = true;
  748. string value;
  749. Status s;
  750. ASSERT_OK(db->Put(write_options, Slice("foo"), Slice("bar")));
  751. ASSERT_OK(db->Put(write_options, Slice("foo2"), Slice("bar")));
  752. Transaction* txn = db->BeginTransaction(write_options, txn_options);
  753. ASSERT_TRUE(txn != nullptr);
  754. ASSERT_OK(txn->SetName("txn"));
  755. Transaction* txn2 = db->BeginTransaction(write_options, txn_options);
  756. ASSERT_TRUE(txn2 != nullptr);
  757. ASSERT_OK(txn2->SetName("txn2"));
  758. // This transaction is created to cause potential conflict.
  759. Transaction* txn_x = db->BeginTransaction(write_options);
  760. ASSERT_OK(txn_x->SetName("txn_x"));
  761. ASSERT_OK(txn_x->Put(Slice("foo"), Slice("bar3")));
  762. ASSERT_OK(txn_x->Prepare());
  763. // Create snapshots after the prepare, but there should still
  764. // be a conflict when trying to read "foo".
  765. if (attempt == kAttemptImmMemTable) {
  766. // For the second attempt, hold flush from beginning. The memtable
  767. // will be switched to immutable after calling TEST_SwitchMemtable()
  768. // while CheckKey() is called.
  769. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
  770. {{"WritePreparedTransactionTest.CheckKeySkipOldMemtable",
  771. "FlushJob::Start"}});
  772. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  773. }
  774. // force a memtable flush. The memtable should still be kept
  775. FlushOptions flush_ops;
  776. if (attempt == kAttemptHistoryMemtable) {
  777. ASSERT_OK(db->Flush(flush_ops));
  778. } else {
  779. assert(attempt == kAttemptImmMemTable);
  780. DBImpl* db_impl = static_cast<DBImpl*>(db->GetRootDB());
  781. db_impl->TEST_SwitchMemtable();
  782. }
  783. uint64_t num_imm_mems;
  784. ASSERT_TRUE(db->GetIntProperty(DB::Properties::kNumImmutableMemTable,
  785. &num_imm_mems));
  786. if (attempt == kAttemptHistoryMemtable) {
  787. ASSERT_EQ(0, num_imm_mems);
  788. } else {
  789. assert(attempt == kAttemptImmMemTable);
  790. ASSERT_EQ(1, num_imm_mems);
  791. }
  792. // Put something in active memtable
  793. ASSERT_OK(db->Put(write_options, Slice("foo3"), Slice("bar")));
  794. // Create txn3 after flushing, but this transaction also needs to
  795. // check all memtables because of they contains uncommitted data.
  796. Transaction* txn3 = db->BeginTransaction(write_options, txn_options);
  797. ASSERT_TRUE(txn3 != nullptr);
  798. ASSERT_OK(txn3->SetName("txn3"));
  799. // Commit the pending write
  800. ASSERT_OK(txn_x->Commit());
  801. // Commit txn, txn2 and tx3. txn and tx3 will conflict but txn2 will
  802. // pass. In all cases, both memtables are queried.
  803. SetPerfLevel(PerfLevel::kEnableCount);
  804. get_perf_context()->Reset();
  805. ASSERT_TRUE(txn3->GetForUpdate(read_options, "foo", &value).IsBusy());
  806. // We should have checked two memtables, active and either immutable
  807. // or history memtable, depending on the test case.
  808. ASSERT_EQ(2, get_perf_context()->get_from_memtable_count);
  809. get_perf_context()->Reset();
  810. ASSERT_TRUE(txn->GetForUpdate(read_options, "foo", &value).IsBusy());
  811. // We should have checked two memtables, active and either immutable
  812. // or history memtable, depending on the test case.
  813. ASSERT_EQ(2, get_perf_context()->get_from_memtable_count);
  814. get_perf_context()->Reset();
  815. ASSERT_OK(txn2->GetForUpdate(read_options, "foo2", &value));
  816. ASSERT_EQ(value, "bar");
  817. // We should have checked two memtables, and since there is no
  818. // conflict, another Get() will be made and fetch the data from
  819. // DB. If it is in immutable memtable, two extra memtable reads
  820. // will be issued. If it is not (in history), only one will
  821. // be made, which is to the active memtable.
  822. if (attempt == kAttemptHistoryMemtable) {
  823. ASSERT_EQ(3, get_perf_context()->get_from_memtable_count);
  824. } else {
  825. assert(attempt == kAttemptImmMemTable);
  826. ASSERT_EQ(4, get_perf_context()->get_from_memtable_count);
  827. }
  828. Transaction* txn4 = db->BeginTransaction(write_options, txn_options);
  829. ASSERT_TRUE(txn4 != nullptr);
  830. ASSERT_OK(txn4->SetName("txn4"));
  831. get_perf_context()->Reset();
  832. ASSERT_OK(txn4->GetForUpdate(read_options, "foo", &value));
  833. if (attempt == kAttemptHistoryMemtable) {
  834. // Active memtable will be checked in snapshot validation and when
  835. // getting the value.
  836. ASSERT_EQ(2, get_perf_context()->get_from_memtable_count);
  837. } else {
  838. // Only active memtable will be checked in snapshot validation but
  839. // both of active and immutable snapshot will be queried when
  840. // getting the value.
  841. assert(attempt == kAttemptImmMemTable);
  842. ASSERT_EQ(3, get_perf_context()->get_from_memtable_count);
  843. }
  844. ASSERT_OK(txn2->Commit());
  845. ASSERT_OK(txn4->Commit());
  846. TEST_SYNC_POINT("WritePreparedTransactionTest.CheckKeySkipOldMemtable");
  847. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  848. SetPerfLevel(PerfLevel::kDisable);
  849. delete txn;
  850. delete txn2;
  851. delete txn3;
  852. delete txn4;
  853. delete txn_x;
  854. }
  855. }
  856. // Reproduce the bug with two snapshots with the same seuqence number and test
  857. // that the release of the first snapshot will not affect the reads by the other
  858. // snapshot
  859. TEST_P(WritePreparedTransactionTest, DoubleSnapshot) {
  860. TransactionOptions txn_options;
  861. Status s;
  862. // Insert initial value
  863. ASSERT_OK(db->Put(WriteOptions(), "key", "value1"));
  864. WritePreparedTxnDB* wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  865. Transaction* txn =
  866. wp_db->BeginTransaction(WriteOptions(), txn_options, nullptr);
  867. ASSERT_OK(txn->SetName("txn"));
  868. ASSERT_OK(txn->Put("key", "value2"));
  869. ASSERT_OK(txn->Prepare());
  870. // Three snapshots with the same seq number
  871. const Snapshot* snapshot0 = wp_db->GetSnapshot();
  872. const Snapshot* snapshot1 = wp_db->GetSnapshot();
  873. const Snapshot* snapshot2 = wp_db->GetSnapshot();
  874. ASSERT_OK(txn->Commit());
  875. SequenceNumber cache_size = wp_db->COMMIT_CACHE_SIZE;
  876. SequenceNumber overlap_seq = txn->GetId() + cache_size;
  877. delete txn;
  878. // 4th snapshot with a larger seq
  879. const Snapshot* snapshot3 = wp_db->GetSnapshot();
  880. // Cause an eviction to advance max evicted seq number
  881. // This also fetches the 4 snapshots from db since their seq is lower than the
  882. // new max
  883. wp_db->AddCommitted(overlap_seq, overlap_seq);
  884. ReadOptions ropt;
  885. // It should see the value before commit
  886. ropt.snapshot = snapshot2;
  887. PinnableSlice pinnable_val;
  888. s = wp_db->Get(ropt, wp_db->DefaultColumnFamily(), "key", &pinnable_val);
  889. ASSERT_OK(s);
  890. ASSERT_TRUE(pinnable_val == "value1");
  891. pinnable_val.Reset();
  892. wp_db->ReleaseSnapshot(snapshot1);
  893. // It should still see the value before commit
  894. s = wp_db->Get(ropt, wp_db->DefaultColumnFamily(), "key", &pinnable_val);
  895. ASSERT_OK(s);
  896. ASSERT_TRUE(pinnable_val == "value1");
  897. pinnable_val.Reset();
  898. // Cause an eviction to advance max evicted seq number and trigger updating
  899. // the snapshot list
  900. overlap_seq += cache_size;
  901. wp_db->AddCommitted(overlap_seq, overlap_seq);
  902. // It should still see the value before commit
  903. s = wp_db->Get(ropt, wp_db->DefaultColumnFamily(), "key", &pinnable_val);
  904. ASSERT_OK(s);
  905. ASSERT_TRUE(pinnable_val == "value1");
  906. pinnable_val.Reset();
  907. wp_db->ReleaseSnapshot(snapshot0);
  908. wp_db->ReleaseSnapshot(snapshot2);
  909. wp_db->ReleaseSnapshot(snapshot3);
  910. }
  911. size_t UniqueCnt(std::vector<SequenceNumber> vec) {
  912. std::set<SequenceNumber> aset;
  913. for (auto i : vec) {
  914. aset.insert(i);
  915. }
  916. return aset.size();
  917. }
  918. // Test that the entries in old_commit_map_ get garbage collected properly
  919. TEST_P(WritePreparedTransactionTest, OldCommitMapGC) {
  920. const size_t snapshot_cache_bits = 0;
  921. const size_t commit_cache_bits = 0;
  922. DBImpl* mock_db = new DBImpl(options, dbname);
  923. UpdateTransactionDBOptions(snapshot_cache_bits, commit_cache_bits);
  924. std::unique_ptr<WritePreparedTxnDBMock> wp_db(
  925. new WritePreparedTxnDBMock(mock_db, txn_db_options));
  926. SequenceNumber seq = 0;
  927. // Take the first snapshot that overlaps with two txn
  928. auto prep_seq = ++seq;
  929. wp_db->AddPrepared(prep_seq);
  930. auto prep_seq2 = ++seq;
  931. wp_db->AddPrepared(prep_seq2);
  932. auto snap_seq1 = seq;
  933. wp_db->TakeSnapshot(snap_seq1);
  934. auto commit_seq = ++seq;
  935. wp_db->AddCommitted(prep_seq, commit_seq);
  936. wp_db->RemovePrepared(prep_seq);
  937. auto commit_seq2 = ++seq;
  938. wp_db->AddCommitted(prep_seq2, commit_seq2);
  939. wp_db->RemovePrepared(prep_seq2);
  940. // Take the 2nd and 3rd snapshot that overlap with the same txn
  941. prep_seq = ++seq;
  942. wp_db->AddPrepared(prep_seq);
  943. auto snap_seq2 = seq;
  944. wp_db->TakeSnapshot(snap_seq2);
  945. seq++;
  946. auto snap_seq3 = seq;
  947. wp_db->TakeSnapshot(snap_seq3);
  948. seq++;
  949. commit_seq = ++seq;
  950. wp_db->AddCommitted(prep_seq, commit_seq);
  951. wp_db->RemovePrepared(prep_seq);
  952. // Make sure max_evicted_seq_ will be larger than 2nd snapshot by evicting the
  953. // only item in the commit_cache_ via another commit.
  954. prep_seq = ++seq;
  955. wp_db->AddPrepared(prep_seq);
  956. commit_seq = ++seq;
  957. wp_db->AddCommitted(prep_seq, commit_seq);
  958. wp_db->RemovePrepared(prep_seq);
  959. // Verify that the evicted commit entries for all snapshots are in the
  960. // old_commit_map_
  961. {
  962. ASSERT_FALSE(wp_db->old_commit_map_empty_.load());
  963. ReadLock rl(&wp_db->old_commit_map_mutex_);
  964. ASSERT_EQ(3, wp_db->old_commit_map_.size());
  965. ASSERT_EQ(2, UniqueCnt(wp_db->old_commit_map_[snap_seq1]));
  966. ASSERT_EQ(1, UniqueCnt(wp_db->old_commit_map_[snap_seq2]));
  967. ASSERT_EQ(1, UniqueCnt(wp_db->old_commit_map_[snap_seq3]));
  968. }
  969. // Verify that the 2nd snapshot is cleaned up after the release
  970. wp_db->ReleaseSnapshotInternal(snap_seq2);
  971. {
  972. ASSERT_FALSE(wp_db->old_commit_map_empty_.load());
  973. ReadLock rl(&wp_db->old_commit_map_mutex_);
  974. ASSERT_EQ(2, wp_db->old_commit_map_.size());
  975. ASSERT_EQ(2, UniqueCnt(wp_db->old_commit_map_[snap_seq1]));
  976. ASSERT_EQ(1, UniqueCnt(wp_db->old_commit_map_[snap_seq3]));
  977. }
  978. // Verify that the 1st snapshot is cleaned up after the release
  979. wp_db->ReleaseSnapshotInternal(snap_seq1);
  980. {
  981. ASSERT_FALSE(wp_db->old_commit_map_empty_.load());
  982. ReadLock rl(&wp_db->old_commit_map_mutex_);
  983. ASSERT_EQ(1, wp_db->old_commit_map_.size());
  984. ASSERT_EQ(1, UniqueCnt(wp_db->old_commit_map_[snap_seq3]));
  985. }
  986. // Verify that the 3rd snapshot is cleaned up after the release
  987. wp_db->ReleaseSnapshotInternal(snap_seq3);
  988. {
  989. ASSERT_TRUE(wp_db->old_commit_map_empty_.load());
  990. ReadLock rl(&wp_db->old_commit_map_mutex_);
  991. ASSERT_EQ(0, wp_db->old_commit_map_.size());
  992. }
  993. }
  994. TEST_P(WritePreparedTransactionTest, CheckAgainstSnapshots) {
  995. std::vector<SequenceNumber> snapshots = {100l, 200l, 300l, 400l, 500l,
  996. 600l, 700l, 800l, 900l};
  997. const size_t snapshot_cache_bits = 2;
  998. const uint64_t cache_size = 1ul << snapshot_cache_bits;
  999. // Safety check to express the intended size in the test. Can be adjusted if
  1000. // the snapshots lists changed.
  1001. assert((1ul << snapshot_cache_bits) * 2 + 1 == snapshots.size());
  1002. DBImpl* mock_db = new DBImpl(options, dbname);
  1003. UpdateTransactionDBOptions(snapshot_cache_bits);
  1004. std::unique_ptr<WritePreparedTxnDBMock> wp_db(
  1005. new WritePreparedTxnDBMock(mock_db, txn_db_options));
  1006. SequenceNumber version = 1000l;
  1007. ASSERT_EQ(0, wp_db->snapshots_total_);
  1008. wp_db->UpdateSnapshots(snapshots, version);
  1009. ASSERT_EQ(snapshots.size(), wp_db->snapshots_total_);
  1010. // seq numbers are chosen so that we have two of them between each two
  1011. // snapshots. If the diff of two consecutive seq is more than 5, there is a
  1012. // snapshot between them.
  1013. std::vector<SequenceNumber> seqs = {50l, 55l, 150l, 155l, 250l, 255l, 350l,
  1014. 355l, 450l, 455l, 550l, 555l, 650l, 655l,
  1015. 750l, 755l, 850l, 855l, 950l, 955l};
  1016. assert(seqs.size() > 1);
  1017. for (size_t i = 0; i < seqs.size() - 1; i++) {
  1018. wp_db->old_commit_map_empty_ = true; // reset
  1019. CommitEntry commit_entry = {seqs[i], seqs[i + 1]};
  1020. wp_db->CheckAgainstSnapshots(commit_entry);
  1021. // Expect update if there is snapshot in between the prepare and commit
  1022. bool expect_update = commit_entry.commit_seq - commit_entry.prep_seq > 5 &&
  1023. commit_entry.commit_seq >= snapshots.front() &&
  1024. commit_entry.prep_seq <= snapshots.back();
  1025. ASSERT_EQ(expect_update, !wp_db->old_commit_map_empty_);
  1026. }
  1027. // Test that search will include multiple snapshot from snapshot cache
  1028. {
  1029. // exclude first and last item in the cache
  1030. CommitEntry commit_entry = {snapshots.front() + 1,
  1031. snapshots[cache_size - 1] - 1};
  1032. wp_db->old_commit_map_empty_ = true; // reset
  1033. wp_db->old_commit_map_.clear();
  1034. wp_db->CheckAgainstSnapshots(commit_entry);
  1035. ASSERT_EQ(wp_db->old_commit_map_.size(), cache_size - 2);
  1036. }
  1037. // Test that search will include multiple snapshot from old snapshots
  1038. {
  1039. // include two in the middle
  1040. CommitEntry commit_entry = {snapshots[cache_size] + 1,
  1041. snapshots[cache_size + 2] + 1};
  1042. wp_db->old_commit_map_empty_ = true; // reset
  1043. wp_db->old_commit_map_.clear();
  1044. wp_db->CheckAgainstSnapshots(commit_entry);
  1045. ASSERT_EQ(wp_db->old_commit_map_.size(), 2);
  1046. }
  1047. // Test that search will include both snapshot cache and old snapshots
  1048. // Case 1: includes all in snapshot cache
  1049. {
  1050. CommitEntry commit_entry = {snapshots.front() - 1, snapshots.back() + 1};
  1051. wp_db->old_commit_map_empty_ = true; // reset
  1052. wp_db->old_commit_map_.clear();
  1053. wp_db->CheckAgainstSnapshots(commit_entry);
  1054. ASSERT_EQ(wp_db->old_commit_map_.size(), snapshots.size());
  1055. }
  1056. // Case 2: includes all snapshot caches except the smallest
  1057. {
  1058. CommitEntry commit_entry = {snapshots.front() + 1, snapshots.back() + 1};
  1059. wp_db->old_commit_map_empty_ = true; // reset
  1060. wp_db->old_commit_map_.clear();
  1061. wp_db->CheckAgainstSnapshots(commit_entry);
  1062. ASSERT_EQ(wp_db->old_commit_map_.size(), snapshots.size() - 1);
  1063. }
  1064. // Case 3: includes only the largest of snapshot cache
  1065. {
  1066. CommitEntry commit_entry = {snapshots[cache_size - 1] - 1,
  1067. snapshots.back() + 1};
  1068. wp_db->old_commit_map_empty_ = true; // reset
  1069. wp_db->old_commit_map_.clear();
  1070. wp_db->CheckAgainstSnapshots(commit_entry);
  1071. ASSERT_EQ(wp_db->old_commit_map_.size(), snapshots.size() - cache_size + 1);
  1072. }
  1073. }
  1074. // This test is too slow for travis
  1075. #ifndef TRAVIS
  1076. #ifndef ROCKSDB_VALGRIND_RUN
  1077. // Test that CheckAgainstSnapshots will not miss a live snapshot if it is run in
  1078. // parallel with UpdateSnapshots.
  1079. TEST_P(SnapshotConcurrentAccessTest, SnapshotConcurrentAccess) {
  1080. // We have a sync point in the method under test after checking each snapshot.
  1081. // If you increase the max number of snapshots in this test, more sync points
  1082. // in the methods must also be added.
  1083. const std::vector<SequenceNumber> snapshots = {10l, 20l, 30l, 40l, 50l,
  1084. 60l, 70l, 80l, 90l, 100l};
  1085. const size_t snapshot_cache_bits = 2;
  1086. // Safety check to express the intended size in the test. Can be adjusted if
  1087. // the snapshots lists changed.
  1088. assert((1ul << snapshot_cache_bits) * 2 + 2 == snapshots.size());
  1089. SequenceNumber version = 1000l;
  1090. // Choose the cache size so that the new snapshot list could replace all the
  1091. // existing items in the cache and also have some overflow.
  1092. DBImpl* mock_db = new DBImpl(options, dbname);
  1093. UpdateTransactionDBOptions(snapshot_cache_bits);
  1094. std::unique_ptr<WritePreparedTxnDBMock> wp_db(
  1095. new WritePreparedTxnDBMock(mock_db, txn_db_options));
  1096. const size_t extra = 2;
  1097. size_t loop_id = 0;
  1098. // Add up to extra items that do not fit into the cache
  1099. for (size_t old_size = 1; old_size <= wp_db->SNAPSHOT_CACHE_SIZE + extra;
  1100. old_size++) {
  1101. const std::vector<SequenceNumber> old_snapshots(
  1102. snapshots.begin(), snapshots.begin() + old_size);
  1103. // Each member of old snapshot might or might not appear in the new list. We
  1104. // create a common_snapshots for each combination.
  1105. size_t new_comb_cnt = size_t(1) << old_size;
  1106. for (size_t new_comb = 0; new_comb < new_comb_cnt; new_comb++, loop_id++) {
  1107. if (loop_id % split_cnt_ != split_id_) continue;
  1108. printf("."); // To signal progress
  1109. fflush(stdout);
  1110. std::vector<SequenceNumber> common_snapshots;
  1111. for (size_t i = 0; i < old_snapshots.size(); i++) {
  1112. if (IsInCombination(i, new_comb)) {
  1113. common_snapshots.push_back(old_snapshots[i]);
  1114. }
  1115. }
  1116. // And add some new snapshots to the common list
  1117. for (size_t added_snapshots = 0;
  1118. added_snapshots <= snapshots.size() - old_snapshots.size();
  1119. added_snapshots++) {
  1120. std::vector<SequenceNumber> new_snapshots = common_snapshots;
  1121. for (size_t i = 0; i < added_snapshots; i++) {
  1122. new_snapshots.push_back(snapshots[old_snapshots.size() + i]);
  1123. }
  1124. for (auto it = common_snapshots.begin(); it != common_snapshots.end();
  1125. ++it) {
  1126. auto snapshot = *it;
  1127. // Create a commit entry that is around the snapshot and thus should
  1128. // be not be discarded
  1129. CommitEntry entry = {static_cast<uint64_t>(snapshot - 1),
  1130. snapshot + 1};
  1131. // The critical part is when iterating the snapshot cache. Afterwards,
  1132. // we are operating under the lock
  1133. size_t a_range =
  1134. std::min(old_snapshots.size(), wp_db->SNAPSHOT_CACHE_SIZE) + 1;
  1135. size_t b_range =
  1136. std::min(new_snapshots.size(), wp_db->SNAPSHOT_CACHE_SIZE) + 1;
  1137. // Break each thread at two points
  1138. for (size_t a1 = 1; a1 <= a_range; a1++) {
  1139. for (size_t a2 = a1 + 1; a2 <= a_range; a2++) {
  1140. for (size_t b1 = 1; b1 <= b_range; b1++) {
  1141. for (size_t b2 = b1 + 1; b2 <= b_range; b2++) {
  1142. SnapshotConcurrentAccessTestInternal(
  1143. wp_db.get(), old_snapshots, new_snapshots, entry, version,
  1144. a1, a2, b1, b2);
  1145. }
  1146. }
  1147. }
  1148. }
  1149. }
  1150. }
  1151. }
  1152. }
  1153. printf("\n");
  1154. }
  1155. #endif // ROCKSDB_VALGRIND_RUN
  1156. #endif // TRAVIS
  1157. // This test clarifies the contract of AdvanceMaxEvictedSeq method
  1158. TEST_P(WritePreparedTransactionTest, AdvanceMaxEvictedSeqBasic) {
  1159. DBImpl* mock_db = new DBImpl(options, dbname);
  1160. std::unique_ptr<WritePreparedTxnDBMock> wp_db(
  1161. new WritePreparedTxnDBMock(mock_db, txn_db_options));
  1162. // 1. Set the initial values for max, prepared, and snapshots
  1163. SequenceNumber zero_max = 0l;
  1164. // Set the initial list of prepared txns
  1165. const std::vector<SequenceNumber> initial_prepared = {10, 30, 50, 100,
  1166. 150, 200, 250};
  1167. for (auto p : initial_prepared) {
  1168. wp_db->AddPrepared(p);
  1169. }
  1170. // This updates the max value and also set old prepared
  1171. SequenceNumber init_max = 100;
  1172. wp_db->AdvanceMaxEvictedSeq(zero_max, init_max);
  1173. const std::vector<SequenceNumber> initial_snapshots = {20, 40};
  1174. wp_db->SetDBSnapshots(initial_snapshots);
  1175. // This will update the internal cache of snapshots from the DB
  1176. wp_db->UpdateSnapshots(initial_snapshots, init_max);
  1177. // 2. Invoke AdvanceMaxEvictedSeq
  1178. const std::vector<SequenceNumber> latest_snapshots = {20, 110, 220, 300};
  1179. wp_db->SetDBSnapshots(latest_snapshots);
  1180. SequenceNumber new_max = 200;
  1181. wp_db->AdvanceMaxEvictedSeq(init_max, new_max);
  1182. // 3. Verify that the state matches with AdvanceMaxEvictedSeq contract
  1183. // a. max should be updated to new_max
  1184. ASSERT_EQ(wp_db->max_evicted_seq_, new_max);
  1185. // b. delayed prepared should contain every txn <= max and prepared should
  1186. // only contain txns > max
  1187. auto it = initial_prepared.begin();
  1188. for (; it != initial_prepared.end() && *it <= new_max; ++it) {
  1189. ASSERT_EQ(1, wp_db->delayed_prepared_.erase(*it));
  1190. }
  1191. ASSERT_TRUE(wp_db->delayed_prepared_.empty());
  1192. for (; it != initial_prepared.end() && !wp_db->prepared_txns_.empty();
  1193. ++it, wp_db->prepared_txns_.pop()) {
  1194. ASSERT_EQ(*it, wp_db->prepared_txns_.top());
  1195. }
  1196. ASSERT_TRUE(it == initial_prepared.end());
  1197. ASSERT_TRUE(wp_db->prepared_txns_.empty());
  1198. // c. snapshots should contain everything below new_max
  1199. auto sit = latest_snapshots.begin();
  1200. for (size_t i = 0; sit != latest_snapshots.end() && *sit <= new_max &&
  1201. i < wp_db->snapshots_total_;
  1202. sit++, i++) {
  1203. ASSERT_TRUE(i < wp_db->snapshots_total_);
  1204. // This test is in small scale and the list of snapshots are assumed to be
  1205. // within the cache size limit. This is just a safety check to double check
  1206. // that assumption.
  1207. ASSERT_TRUE(i < wp_db->SNAPSHOT_CACHE_SIZE);
  1208. ASSERT_EQ(*sit, wp_db->snapshot_cache_[i]);
  1209. }
  1210. }
  1211. // A new snapshot should always be always larger than max_evicted_seq_
  1212. // Otherwise the snapshot does not go through AdvanceMaxEvictedSeq
  1213. TEST_P(WritePreparedTransactionTest, NewSnapshotLargerThanMax) {
  1214. WriteOptions woptions;
  1215. TransactionOptions txn_options;
  1216. WritePreparedTxnDB* wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  1217. Transaction* txn0 = db->BeginTransaction(woptions, txn_options);
  1218. ASSERT_OK(txn0->Put(Slice("key"), Slice("value")));
  1219. ASSERT_OK(txn0->Commit());
  1220. const SequenceNumber seq = txn0->GetId(); // is also prepare seq
  1221. delete txn0;
  1222. std::vector<Transaction*> txns;
  1223. // Inc seq without committing anything
  1224. for (int i = 0; i < 10; i++) {
  1225. Transaction* txn = db->BeginTransaction(woptions, txn_options);
  1226. ASSERT_OK(txn->SetName("xid" + std::to_string(i)));
  1227. ASSERT_OK(txn->Put(Slice("key" + std::to_string(i)), Slice("value")));
  1228. ASSERT_OK(txn->Prepare());
  1229. txns.push_back(txn);
  1230. }
  1231. // The new commit is seq + 10
  1232. ASSERT_OK(db->Put(woptions, "key", "value"));
  1233. auto snap = wp_db->GetSnapshot();
  1234. const SequenceNumber last_seq = snap->GetSequenceNumber();
  1235. wp_db->ReleaseSnapshot(snap);
  1236. ASSERT_LT(seq, last_seq);
  1237. // Otherwise our test is not effective
  1238. ASSERT_LT(last_seq - seq, wp_db->INC_STEP_FOR_MAX_EVICTED);
  1239. // Evict seq out of commit cache
  1240. const SequenceNumber overwrite_seq = seq + wp_db->COMMIT_CACHE_SIZE;
  1241. // Check that the next write could make max go beyond last
  1242. auto last_max = wp_db->max_evicted_seq_.load();
  1243. wp_db->AddCommitted(overwrite_seq, overwrite_seq);
  1244. // Check that eviction has advanced the max
  1245. ASSERT_LT(last_max, wp_db->max_evicted_seq_.load());
  1246. // Check that the new max has not advanced the last seq
  1247. ASSERT_LT(wp_db->max_evicted_seq_.load(), last_seq);
  1248. for (auto txn : txns) {
  1249. txn->Rollback();
  1250. delete txn;
  1251. }
  1252. }
  1253. // A new snapshot should always be always larger than max_evicted_seq_
  1254. // In very rare cases max could be below last published seq. Test that
  1255. // taking snapshot will wait for max to catch up.
  1256. TEST_P(WritePreparedTransactionTest, MaxCatchupWithNewSnapshot) {
  1257. const size_t snapshot_cache_bits = 7; // same as default
  1258. const size_t commit_cache_bits = 0; // only 1 entry => frequent eviction
  1259. UpdateTransactionDBOptions(snapshot_cache_bits, commit_cache_bits);
  1260. ReOpen();
  1261. WriteOptions woptions;
  1262. WritePreparedTxnDB* wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  1263. const int writes = 50;
  1264. const int batch_cnt = 4;
  1265. ROCKSDB_NAMESPACE::port::Thread t1([&]() {
  1266. for (int i = 0; i < writes; i++) {
  1267. WriteBatch batch;
  1268. // For duplicate keys cause 4 commit entries, each evicting an entry that
  1269. // is not published yet, thus causing max evicted seq go higher than last
  1270. // published.
  1271. for (int b = 0; b < batch_cnt; b++) {
  1272. batch.Put("foo", "foo");
  1273. }
  1274. db->Write(woptions, &batch);
  1275. }
  1276. });
  1277. ROCKSDB_NAMESPACE::port::Thread t2([&]() {
  1278. while (wp_db->max_evicted_seq_ == 0) { // wait for insert thread
  1279. std::this_thread::yield();
  1280. }
  1281. for (int i = 0; i < 10; i++) {
  1282. SequenceNumber max_lower_bound = wp_db->max_evicted_seq_;
  1283. auto snap = db->GetSnapshot();
  1284. if (snap->GetSequenceNumber() != 0) {
  1285. // Value of max_evicted_seq_ when snapshot was taken in unknown. We thus
  1286. // compare with the lower bound instead as an approximation.
  1287. ASSERT_LT(max_lower_bound, snap->GetSequenceNumber());
  1288. } // seq 0 is ok to be less than max since nothing is visible to it
  1289. db->ReleaseSnapshot(snap);
  1290. }
  1291. });
  1292. t1.join();
  1293. t2.join();
  1294. // Make sure that the test has worked and seq number has advanced as we
  1295. // thought
  1296. auto snap = db->GetSnapshot();
  1297. ASSERT_GT(snap->GetSequenceNumber(), batch_cnt * writes - 1);
  1298. db->ReleaseSnapshot(snap);
  1299. }
  1300. // Test that reads without snapshots would not hit an undefined state
  1301. TEST_P(WritePreparedTransactionTest, MaxCatchupWithUnbackedSnapshot) {
  1302. const size_t snapshot_cache_bits = 7; // same as default
  1303. const size_t commit_cache_bits = 0; // only 1 entry => frequent eviction
  1304. UpdateTransactionDBOptions(snapshot_cache_bits, commit_cache_bits);
  1305. ReOpen();
  1306. WriteOptions woptions;
  1307. WritePreparedTxnDB* wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  1308. const int writes = 50;
  1309. ROCKSDB_NAMESPACE::port::Thread t1([&]() {
  1310. for (int i = 0; i < writes; i++) {
  1311. WriteBatch batch;
  1312. batch.Put("key", "foo");
  1313. db->Write(woptions, &batch);
  1314. }
  1315. });
  1316. ROCKSDB_NAMESPACE::port::Thread t2([&]() {
  1317. while (wp_db->max_evicted_seq_ == 0) { // wait for insert thread
  1318. std::this_thread::yield();
  1319. }
  1320. ReadOptions ropt;
  1321. PinnableSlice pinnable_val;
  1322. TransactionOptions txn_options;
  1323. for (int i = 0; i < 10; i++) {
  1324. auto s = db->Get(ropt, db->DefaultColumnFamily(), "key", &pinnable_val);
  1325. ASSERT_TRUE(s.ok() || s.IsTryAgain());
  1326. pinnable_val.Reset();
  1327. Transaction* txn = db->BeginTransaction(woptions, txn_options);
  1328. s = txn->Get(ropt, db->DefaultColumnFamily(), "key", &pinnable_val);
  1329. ASSERT_TRUE(s.ok() || s.IsTryAgain());
  1330. pinnable_val.Reset();
  1331. std::vector<std::string> values;
  1332. auto s_vec =
  1333. txn->MultiGet(ropt, {db->DefaultColumnFamily()}, {"key"}, &values);
  1334. ASSERT_EQ(1, values.size());
  1335. ASSERT_EQ(1, s_vec.size());
  1336. s = s_vec[0];
  1337. ASSERT_TRUE(s.ok() || s.IsTryAgain());
  1338. Slice key("key");
  1339. txn->MultiGet(ropt, db->DefaultColumnFamily(), 1, &key, &pinnable_val, &s,
  1340. true);
  1341. ASSERT_TRUE(s.ok() || s.IsTryAgain());
  1342. delete txn;
  1343. }
  1344. });
  1345. t1.join();
  1346. t2.join();
  1347. // Make sure that the test has worked and seq number has advanced as we
  1348. // thought
  1349. auto snap = db->GetSnapshot();
  1350. ASSERT_GT(snap->GetSequenceNumber(), writes - 1);
  1351. db->ReleaseSnapshot(snap);
  1352. }
  1353. // Check that old_commit_map_ cleanup works correctly if the snapshot equals
  1354. // max_evicted_seq_.
  1355. TEST_P(WritePreparedTransactionTest, CleanupSnapshotEqualToMax) {
  1356. const size_t snapshot_cache_bits = 7; // same as default
  1357. const size_t commit_cache_bits = 0; // only 1 entry => frequent eviction
  1358. UpdateTransactionDBOptions(snapshot_cache_bits, commit_cache_bits);
  1359. ReOpen();
  1360. WriteOptions woptions;
  1361. WritePreparedTxnDB* wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  1362. // Insert something to increase seq
  1363. ASSERT_OK(db->Put(woptions, "key", "value"));
  1364. auto snap = db->GetSnapshot();
  1365. auto snap_seq = snap->GetSequenceNumber();
  1366. // Another insert should trigger eviction + load snapshot from db
  1367. ASSERT_OK(db->Put(woptions, "key", "value"));
  1368. // This is the scenario that we check agaisnt
  1369. ASSERT_EQ(snap_seq, wp_db->max_evicted_seq_);
  1370. // old_commit_map_ now has some data that needs gc
  1371. ASSERT_EQ(1, wp_db->snapshots_total_);
  1372. ASSERT_EQ(1, wp_db->old_commit_map_.size());
  1373. db->ReleaseSnapshot(snap);
  1374. // Another insert should trigger eviction + load snapshot from db
  1375. ASSERT_OK(db->Put(woptions, "key", "value"));
  1376. // the snapshot and related metadata must be properly garbage collected
  1377. ASSERT_EQ(0, wp_db->snapshots_total_);
  1378. ASSERT_TRUE(wp_db->snapshots_all_.empty());
  1379. ASSERT_EQ(0, wp_db->old_commit_map_.size());
  1380. }
  1381. TEST_P(WritePreparedTransactionTest, AdvanceSeqByOne) {
  1382. auto snap = db->GetSnapshot();
  1383. auto seq1 = snap->GetSequenceNumber();
  1384. db->ReleaseSnapshot(snap);
  1385. WritePreparedTxnDB* wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  1386. wp_db->AdvanceSeqByOne();
  1387. snap = db->GetSnapshot();
  1388. auto seq2 = snap->GetSequenceNumber();
  1389. db->ReleaseSnapshot(snap);
  1390. ASSERT_LT(seq1, seq2);
  1391. }
  1392. // Test that the txn Initilize calls the overridden functions
  1393. TEST_P(WritePreparedTransactionTest, TxnInitialize) {
  1394. TransactionOptions txn_options;
  1395. WriteOptions write_options;
  1396. ASSERT_OK(db->Put(write_options, "key", "value"));
  1397. Transaction* txn0 = db->BeginTransaction(write_options, txn_options);
  1398. ASSERT_OK(txn0->SetName("xid"));
  1399. ASSERT_OK(txn0->Put(Slice("key"), Slice("value1")));
  1400. ASSERT_OK(txn0->Prepare());
  1401. // SetSnapshot is overridden to update min_uncommitted_
  1402. txn_options.set_snapshot = true;
  1403. Transaction* txn1 = db->BeginTransaction(write_options, txn_options);
  1404. auto snap = txn1->GetSnapshot();
  1405. auto snap_impl = reinterpret_cast<const SnapshotImpl*>(snap);
  1406. // If ::Initialize calls the overriden SetSnapshot, min_uncommitted_ must be
  1407. // udpated
  1408. ASSERT_GT(snap_impl->min_uncommitted_, kMinUnCommittedSeq);
  1409. txn0->Rollback();
  1410. txn1->Rollback();
  1411. delete txn0;
  1412. delete txn1;
  1413. }
  1414. // This tests that transactions with duplicate keys perform correctly after max
  1415. // is advancing their prepared sequence numbers. This will not be the case if
  1416. // for example the txn does not add the prepared seq for the second sub-batch to
  1417. // the PreparedHeap structure.
  1418. TEST_P(WritePreparedTransactionTest, AdvanceMaxEvictedSeqWithDuplicates) {
  1419. const size_t snapshot_cache_bits = 7; // same as default
  1420. const size_t commit_cache_bits = 1; // disable commit cache
  1421. UpdateTransactionDBOptions(snapshot_cache_bits, commit_cache_bits);
  1422. ReOpen();
  1423. ReadOptions ropt;
  1424. PinnableSlice pinnable_val;
  1425. WriteOptions write_options;
  1426. TransactionOptions txn_options;
  1427. Transaction* txn0 = db->BeginTransaction(write_options, txn_options);
  1428. ASSERT_OK(txn0->SetName("xid"));
  1429. ASSERT_OK(txn0->Put(Slice("key"), Slice("value1")));
  1430. ASSERT_OK(txn0->Put(Slice("key"), Slice("value2")));
  1431. ASSERT_OK(txn0->Prepare());
  1432. ASSERT_OK(db->Put(write_options, "key2", "value"));
  1433. // Will cause max advance due to disabled commit cache
  1434. ASSERT_OK(db->Put(write_options, "key3", "value"));
  1435. auto s = db->Get(ropt, db->DefaultColumnFamily(), "key", &pinnable_val);
  1436. ASSERT_TRUE(s.IsNotFound());
  1437. delete txn0;
  1438. WritePreparedTxnDB* wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  1439. wp_db->db_impl_->FlushWAL(true);
  1440. wp_db->TEST_Crash();
  1441. ReOpenNoDelete();
  1442. assert(db != nullptr);
  1443. s = db->Get(ropt, db->DefaultColumnFamily(), "key", &pinnable_val);
  1444. ASSERT_TRUE(s.IsNotFound());
  1445. txn0 = db->GetTransactionByName("xid");
  1446. ASSERT_OK(txn0->Rollback());
  1447. delete txn0;
  1448. }
  1449. #ifndef ROCKSDB_VALGRIND_RUN
  1450. // Stress SmallestUnCommittedSeq, which reads from both prepared_txns_ and
  1451. // delayed_prepared_, when is run concurrently with advancing max_evicted_seq,
  1452. // which moves prepared txns from prepared_txns_ to delayed_prepared_.
  1453. TEST_P(WritePreparedTransactionTest, SmallestUnCommittedSeq) {
  1454. const size_t snapshot_cache_bits = 7; // same as default
  1455. const size_t commit_cache_bits = 1; // disable commit cache
  1456. UpdateTransactionDBOptions(snapshot_cache_bits, commit_cache_bits);
  1457. ReOpen();
  1458. WritePreparedTxnDB* wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  1459. ReadOptions ropt;
  1460. PinnableSlice pinnable_val;
  1461. WriteOptions write_options;
  1462. TransactionOptions txn_options;
  1463. std::vector<Transaction*> txns, committed_txns;
  1464. const int cnt = 100;
  1465. for (int i = 0; i < cnt; i++) {
  1466. Transaction* txn = db->BeginTransaction(write_options, txn_options);
  1467. ASSERT_OK(txn->SetName("xid" + ToString(i)));
  1468. auto key = "key1" + ToString(i);
  1469. auto value = "value1" + ToString(i);
  1470. ASSERT_OK(txn->Put(Slice(key), Slice(value)));
  1471. ASSERT_OK(txn->Prepare());
  1472. txns.push_back(txn);
  1473. }
  1474. port::Mutex mutex;
  1475. Random rnd(1103);
  1476. ROCKSDB_NAMESPACE::port::Thread commit_thread([&]() {
  1477. for (int i = 0; i < cnt; i++) {
  1478. uint32_t index = rnd.Uniform(cnt - i);
  1479. Transaction* txn;
  1480. {
  1481. MutexLock l(&mutex);
  1482. txn = txns[index];
  1483. txns.erase(txns.begin() + index);
  1484. }
  1485. // Since commit cache is practically disabled, commit results in immediate
  1486. // advance in max_evicted_seq_ and subsequently moving some prepared txns
  1487. // to delayed_prepared_.
  1488. txn->Commit();
  1489. committed_txns.push_back(txn);
  1490. }
  1491. });
  1492. ROCKSDB_NAMESPACE::port::Thread read_thread([&]() {
  1493. while (1) {
  1494. MutexLock l(&mutex);
  1495. if (txns.empty()) {
  1496. break;
  1497. }
  1498. auto min_uncommitted = wp_db->SmallestUnCommittedSeq();
  1499. ASSERT_LE(min_uncommitted, (*txns.begin())->GetId());
  1500. }
  1501. });
  1502. commit_thread.join();
  1503. read_thread.join();
  1504. for (auto txn : committed_txns) {
  1505. delete txn;
  1506. }
  1507. }
  1508. #endif // ROCKSDB_VALGRIND_RUN
  1509. TEST_P(SeqAdvanceConcurrentTest, SeqAdvanceConcurrent) {
  1510. // Given the sequential run of txns, with this timeout we should never see a
  1511. // deadlock nor a timeout unless we have a key conflict, which should be
  1512. // almost infeasible.
  1513. txn_db_options.transaction_lock_timeout = 1000;
  1514. txn_db_options.default_lock_timeout = 1000;
  1515. ReOpen();
  1516. FlushOptions fopt;
  1517. // Number of different txn types we use in this test
  1518. const size_t type_cnt = 5;
  1519. // The size of the first write group
  1520. // TODO(myabandeh): This should be increase for pre-release tests
  1521. const size_t first_group_size = 2;
  1522. // Total number of txns we run in each test
  1523. // TODO(myabandeh): This should be increase for pre-release tests
  1524. const size_t txn_cnt = first_group_size + 1;
  1525. size_t base[txn_cnt + 1] = {
  1526. 1,
  1527. };
  1528. for (size_t bi = 1; bi <= txn_cnt; bi++) {
  1529. base[bi] = base[bi - 1] * type_cnt;
  1530. }
  1531. const size_t max_n = static_cast<size_t>(std::pow(type_cnt, txn_cnt));
  1532. printf("Number of cases being tested is %" ROCKSDB_PRIszt "\n", max_n);
  1533. for (size_t n = 0; n < max_n; n++, ReOpen()) {
  1534. if (n % split_cnt_ != split_id_) continue;
  1535. if (n % 1000 == 0) {
  1536. printf("Tested %" ROCKSDB_PRIszt " cases so far\n", n);
  1537. }
  1538. DBImpl* db_impl = reinterpret_cast<DBImpl*>(db->GetRootDB());
  1539. auto seq = db_impl->TEST_GetLastVisibleSequence();
  1540. with_empty_commits = 0;
  1541. exp_seq = seq;
  1542. // This is increased before writing the batch for commit
  1543. commit_writes = 0;
  1544. // This is increased before txn starts linking if it expects to do a commit
  1545. // eventually
  1546. expected_commits = 0;
  1547. std::vector<port::Thread> threads;
  1548. linked = 0;
  1549. std::atomic<bool> batch_formed(false);
  1550. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1551. "WriteThread::EnterAsBatchGroupLeader:End",
  1552. [&](void* /*arg*/) { batch_formed = true; });
  1553. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1554. "WriteThread::JoinBatchGroup:Wait", [&](void* /*arg*/) {
  1555. linked++;
  1556. if (linked == 1) {
  1557. // Wait until the others are linked too.
  1558. while (linked < first_group_size) {
  1559. }
  1560. } else if (linked == 1 + first_group_size) {
  1561. // Make the 2nd batch of the rest of writes plus any followup
  1562. // commits from the first batch
  1563. while (linked < txn_cnt + commit_writes) {
  1564. }
  1565. }
  1566. // Then we will have one or more batches consisting of follow-up
  1567. // commits from the 2nd batch. There is a bit of non-determinism here
  1568. // but it should be tolerable.
  1569. });
  1570. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  1571. for (size_t bi = 0; bi < txn_cnt; bi++) {
  1572. // get the bi-th digit in number system based on type_cnt
  1573. size_t d = (n % base[bi + 1]) / base[bi];
  1574. switch (d) {
  1575. case 0:
  1576. threads.emplace_back(txn_t0, bi);
  1577. break;
  1578. case 1:
  1579. threads.emplace_back(txn_t1, bi);
  1580. break;
  1581. case 2:
  1582. threads.emplace_back(txn_t2, bi);
  1583. break;
  1584. case 3:
  1585. threads.emplace_back(txn_t3, bi);
  1586. break;
  1587. case 4:
  1588. threads.emplace_back(txn_t3, bi);
  1589. break;
  1590. default:
  1591. assert(false);
  1592. }
  1593. // wait to be linked
  1594. while (linked.load() <= bi) {
  1595. }
  1596. // after a queue of size first_group_size
  1597. if (bi + 1 == first_group_size) {
  1598. while (!batch_formed) {
  1599. }
  1600. // to make it more deterministic, wait until the commits are linked
  1601. while (linked.load() <= bi + expected_commits) {
  1602. }
  1603. }
  1604. }
  1605. for (auto& t : threads) {
  1606. t.join();
  1607. }
  1608. if (options.two_write_queues) {
  1609. // In this case none of the above scheduling tricks to deterministically
  1610. // form merged batches works because the writes go to separate queues.
  1611. // This would result in different write groups in each run of the test. We
  1612. // still keep the test since although non-deterministic and hard to debug,
  1613. // it is still useful to have.
  1614. // TODO(myabandeh): Add a deterministic unit test for two_write_queues
  1615. }
  1616. // Check if memtable inserts advanced seq number as expected
  1617. seq = db_impl->TEST_GetLastVisibleSequence();
  1618. ASSERT_EQ(exp_seq, seq);
  1619. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  1620. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();
  1621. // Check if recovery preserves the last sequence number
  1622. db_impl->FlushWAL(true);
  1623. ReOpenNoDelete();
  1624. assert(db != nullptr);
  1625. db_impl = reinterpret_cast<DBImpl*>(db->GetRootDB());
  1626. seq = db_impl->TEST_GetLastVisibleSequence();
  1627. ASSERT_LE(exp_seq, seq + with_empty_commits);
  1628. // Check if flush preserves the last sequence number
  1629. db_impl->Flush(fopt);
  1630. seq = db_impl->GetLatestSequenceNumber();
  1631. ASSERT_LE(exp_seq, seq + with_empty_commits);
  1632. // Check if recovery after flush preserves the last sequence number
  1633. db_impl->FlushWAL(true);
  1634. ReOpenNoDelete();
  1635. assert(db != nullptr);
  1636. db_impl = reinterpret_cast<DBImpl*>(db->GetRootDB());
  1637. seq = db_impl->GetLatestSequenceNumber();
  1638. ASSERT_LE(exp_seq, seq + with_empty_commits);
  1639. }
  1640. }
  1641. // Run a couple of different txns among them some uncommitted. Restart the db at
  1642. // a couple points to check whether the list of uncommitted txns are recovered
  1643. // properly.
  1644. TEST_P(WritePreparedTransactionTest, BasicRecovery) {
  1645. options.disable_auto_compactions = true;
  1646. ReOpen();
  1647. WritePreparedTxnDB* wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  1648. txn_t0(0);
  1649. TransactionOptions txn_options;
  1650. WriteOptions write_options;
  1651. size_t index = 1000;
  1652. Transaction* txn0 = db->BeginTransaction(write_options, txn_options);
  1653. auto istr0 = std::to_string(index);
  1654. auto s = txn0->SetName("xid" + istr0);
  1655. ASSERT_OK(s);
  1656. s = txn0->Put(Slice("foo0" + istr0), Slice("bar0" + istr0));
  1657. ASSERT_OK(s);
  1658. s = txn0->Prepare();
  1659. auto prep_seq_0 = txn0->GetId();
  1660. txn_t1(0);
  1661. index++;
  1662. Transaction* txn1 = db->BeginTransaction(write_options, txn_options);
  1663. auto istr1 = std::to_string(index);
  1664. s = txn1->SetName("xid" + istr1);
  1665. ASSERT_OK(s);
  1666. s = txn1->Put(Slice("foo1" + istr1), Slice("bar"));
  1667. ASSERT_OK(s);
  1668. s = txn1->Prepare();
  1669. auto prep_seq_1 = txn1->GetId();
  1670. txn_t2(0);
  1671. ReadOptions ropt;
  1672. PinnableSlice pinnable_val;
  1673. // Check the value is not committed before restart
  1674. s = db->Get(ropt, db->DefaultColumnFamily(), "foo0" + istr0, &pinnable_val);
  1675. ASSERT_TRUE(s.IsNotFound());
  1676. pinnable_val.Reset();
  1677. delete txn0;
  1678. delete txn1;
  1679. wp_db->db_impl_->FlushWAL(true);
  1680. wp_db->TEST_Crash();
  1681. ReOpenNoDelete();
  1682. assert(db != nullptr);
  1683. wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  1684. // After recovery, all the uncommitted txns (0 and 1) should be inserted into
  1685. // delayed_prepared_
  1686. ASSERT_TRUE(wp_db->prepared_txns_.empty());
  1687. ASSERT_FALSE(wp_db->delayed_prepared_empty_);
  1688. ASSERT_LE(prep_seq_0, wp_db->max_evicted_seq_);
  1689. ASSERT_LE(prep_seq_1, wp_db->max_evicted_seq_);
  1690. {
  1691. ReadLock rl(&wp_db->prepared_mutex_);
  1692. ASSERT_EQ(2, wp_db->delayed_prepared_.size());
  1693. ASSERT_TRUE(wp_db->delayed_prepared_.find(prep_seq_0) !=
  1694. wp_db->delayed_prepared_.end());
  1695. ASSERT_TRUE(wp_db->delayed_prepared_.find(prep_seq_1) !=
  1696. wp_db->delayed_prepared_.end());
  1697. }
  1698. // Check the value is still not committed after restart
  1699. s = db->Get(ropt, db->DefaultColumnFamily(), "foo0" + istr0, &pinnable_val);
  1700. ASSERT_TRUE(s.IsNotFound());
  1701. pinnable_val.Reset();
  1702. txn_t3(0);
  1703. // Test that a recovered txns will be properly marked committed for the next
  1704. // recovery
  1705. txn1 = db->GetTransactionByName("xid" + istr1);
  1706. ASSERT_NE(txn1, nullptr);
  1707. txn1->Commit();
  1708. delete txn1;
  1709. index++;
  1710. Transaction* txn2 = db->BeginTransaction(write_options, txn_options);
  1711. auto istr2 = std::to_string(index);
  1712. s = txn2->SetName("xid" + istr2);
  1713. ASSERT_OK(s);
  1714. s = txn2->Put(Slice("foo2" + istr2), Slice("bar"));
  1715. ASSERT_OK(s);
  1716. s = txn2->Prepare();
  1717. auto prep_seq_2 = txn2->GetId();
  1718. delete txn2;
  1719. wp_db->db_impl_->FlushWAL(true);
  1720. wp_db->TEST_Crash();
  1721. ReOpenNoDelete();
  1722. assert(db != nullptr);
  1723. wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  1724. ASSERT_TRUE(wp_db->prepared_txns_.empty());
  1725. ASSERT_FALSE(wp_db->delayed_prepared_empty_);
  1726. // 0 and 2 are prepared and 1 is committed
  1727. {
  1728. ReadLock rl(&wp_db->prepared_mutex_);
  1729. ASSERT_EQ(2, wp_db->delayed_prepared_.size());
  1730. const auto& end = wp_db->delayed_prepared_.end();
  1731. ASSERT_NE(wp_db->delayed_prepared_.find(prep_seq_0), end);
  1732. ASSERT_EQ(wp_db->delayed_prepared_.find(prep_seq_1), end);
  1733. ASSERT_NE(wp_db->delayed_prepared_.find(prep_seq_2), end);
  1734. }
  1735. ASSERT_LE(prep_seq_0, wp_db->max_evicted_seq_);
  1736. ASSERT_LE(prep_seq_2, wp_db->max_evicted_seq_);
  1737. // Commit all the remaining txns
  1738. txn0 = db->GetTransactionByName("xid" + istr0);
  1739. ASSERT_NE(txn0, nullptr);
  1740. txn0->Commit();
  1741. txn2 = db->GetTransactionByName("xid" + istr2);
  1742. ASSERT_NE(txn2, nullptr);
  1743. txn2->Commit();
  1744. // Check the value is committed after commit
  1745. s = db->Get(ropt, db->DefaultColumnFamily(), "foo0" + istr0, &pinnable_val);
  1746. ASSERT_TRUE(s.ok());
  1747. ASSERT_TRUE(pinnable_val == ("bar0" + istr0));
  1748. pinnable_val.Reset();
  1749. delete txn0;
  1750. delete txn2;
  1751. wp_db->db_impl_->FlushWAL(true);
  1752. ReOpenNoDelete();
  1753. assert(db != nullptr);
  1754. wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  1755. ASSERT_TRUE(wp_db->prepared_txns_.empty());
  1756. ASSERT_TRUE(wp_db->delayed_prepared_empty_);
  1757. // Check the value is still committed after recovery
  1758. s = db->Get(ropt, db->DefaultColumnFamily(), "foo0" + istr0, &pinnable_val);
  1759. ASSERT_TRUE(s.ok());
  1760. ASSERT_TRUE(pinnable_val == ("bar0" + istr0));
  1761. pinnable_val.Reset();
  1762. }
  1763. // After recovery the commit map is empty while the max is set. The code would
  1764. // go through a different path which requires a separate test. Test that the
  1765. // committed data before the restart is visible to all snapshots.
  1766. TEST_P(WritePreparedTransactionTest, IsInSnapshotEmptyMap) {
  1767. for (bool end_with_prepare : {false, true}) {
  1768. ReOpen();
  1769. WriteOptions woptions;
  1770. ASSERT_OK(db->Put(woptions, "key", "value"));
  1771. ASSERT_OK(db->Put(woptions, "key", "value"));
  1772. ASSERT_OK(db->Put(woptions, "key", "value"));
  1773. SequenceNumber prepare_seq = kMaxSequenceNumber;
  1774. if (end_with_prepare) {
  1775. TransactionOptions txn_options;
  1776. Transaction* txn = db->BeginTransaction(woptions, txn_options);
  1777. ASSERT_OK(txn->SetName("xid0"));
  1778. ASSERT_OK(txn->Prepare());
  1779. prepare_seq = txn->GetId();
  1780. delete txn;
  1781. }
  1782. dynamic_cast<WritePreparedTxnDB*>(db)->TEST_Crash();
  1783. auto db_impl = reinterpret_cast<DBImpl*>(db->GetRootDB());
  1784. db_impl->FlushWAL(true);
  1785. ReOpenNoDelete();
  1786. WritePreparedTxnDB* wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  1787. assert(wp_db != nullptr);
  1788. ASSERT_GT(wp_db->max_evicted_seq_, 0); // max after recovery
  1789. // Take a snapshot right after recovery
  1790. const Snapshot* snap = db->GetSnapshot();
  1791. auto snap_seq = snap->GetSequenceNumber();
  1792. ASSERT_GT(snap_seq, 0);
  1793. for (SequenceNumber seq = 0;
  1794. seq <= wp_db->max_evicted_seq_ && seq != prepare_seq; seq++) {
  1795. ASSERT_TRUE(wp_db->IsInSnapshot(seq, snap_seq));
  1796. }
  1797. if (end_with_prepare) {
  1798. ASSERT_FALSE(wp_db->IsInSnapshot(prepare_seq, snap_seq));
  1799. }
  1800. // trivial check
  1801. ASSERT_FALSE(wp_db->IsInSnapshot(snap_seq + 1, snap_seq));
  1802. db->ReleaseSnapshot(snap);
  1803. ASSERT_OK(db->Put(woptions, "key", "value"));
  1804. // Take a snapshot after some writes
  1805. snap = db->GetSnapshot();
  1806. snap_seq = snap->GetSequenceNumber();
  1807. for (SequenceNumber seq = 0;
  1808. seq <= wp_db->max_evicted_seq_ && seq != prepare_seq; seq++) {
  1809. ASSERT_TRUE(wp_db->IsInSnapshot(seq, snap_seq));
  1810. }
  1811. if (end_with_prepare) {
  1812. ASSERT_FALSE(wp_db->IsInSnapshot(prepare_seq, snap_seq));
  1813. }
  1814. // trivial check
  1815. ASSERT_FALSE(wp_db->IsInSnapshot(snap_seq + 1, snap_seq));
  1816. db->ReleaseSnapshot(snap);
  1817. }
  1818. }
  1819. // Shows the contract of IsInSnapshot when called on invalid/released snapshots
  1820. TEST_P(WritePreparedTransactionTest, IsInSnapshotReleased) {
  1821. WritePreparedTxnDB* wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  1822. WriteOptions woptions;
  1823. ASSERT_OK(db->Put(woptions, "key", "value"));
  1824. // snap seq = 1
  1825. const Snapshot* snap1 = db->GetSnapshot();
  1826. ASSERT_OK(db->Put(woptions, "key", "value"));
  1827. ASSERT_OK(db->Put(woptions, "key", "value"));
  1828. // snap seq = 3
  1829. const Snapshot* snap2 = db->GetSnapshot();
  1830. const SequenceNumber seq = 1;
  1831. // Evict seq out of commit cache
  1832. size_t overwrite_seq = wp_db->COMMIT_CACHE_SIZE + seq;
  1833. wp_db->AddCommitted(overwrite_seq, overwrite_seq);
  1834. SequenceNumber snap_seq;
  1835. uint64_t min_uncommitted = kMinUnCommittedSeq;
  1836. bool released;
  1837. released = false;
  1838. snap_seq = snap1->GetSequenceNumber();
  1839. ASSERT_LE(seq, snap_seq);
  1840. // Valid snapshot lower than max
  1841. ASSERT_LE(snap_seq, wp_db->max_evicted_seq_);
  1842. ASSERT_TRUE(wp_db->IsInSnapshot(seq, snap_seq, min_uncommitted, &released));
  1843. ASSERT_FALSE(released);
  1844. released = false;
  1845. snap_seq = snap1->GetSequenceNumber();
  1846. // Invaid snapshot lower than max
  1847. ASSERT_LE(snap_seq + 1, wp_db->max_evicted_seq_);
  1848. ASSERT_TRUE(
  1849. wp_db->IsInSnapshot(seq, snap_seq + 1, min_uncommitted, &released));
  1850. ASSERT_TRUE(released);
  1851. db->ReleaseSnapshot(snap1);
  1852. released = false;
  1853. // Released snapshot lower than max
  1854. ASSERT_TRUE(wp_db->IsInSnapshot(seq, snap_seq, min_uncommitted, &released));
  1855. // The release does not take affect until the next max advance
  1856. ASSERT_FALSE(released);
  1857. released = false;
  1858. // Invaid snapshot lower than max
  1859. ASSERT_TRUE(
  1860. wp_db->IsInSnapshot(seq, snap_seq + 1, min_uncommitted, &released));
  1861. ASSERT_TRUE(released);
  1862. // This make the snapshot release to reflect in txn db structures
  1863. wp_db->AdvanceMaxEvictedSeq(wp_db->max_evicted_seq_,
  1864. wp_db->max_evicted_seq_ + 1);
  1865. released = false;
  1866. // Released snapshot lower than max
  1867. ASSERT_TRUE(wp_db->IsInSnapshot(seq, snap_seq, min_uncommitted, &released));
  1868. ASSERT_TRUE(released);
  1869. released = false;
  1870. // Invaid snapshot lower than max
  1871. ASSERT_TRUE(
  1872. wp_db->IsInSnapshot(seq, snap_seq + 1, min_uncommitted, &released));
  1873. ASSERT_TRUE(released);
  1874. snap_seq = snap2->GetSequenceNumber();
  1875. released = false;
  1876. // Unreleased snapshot lower than max
  1877. ASSERT_TRUE(wp_db->IsInSnapshot(seq, snap_seq, min_uncommitted, &released));
  1878. ASSERT_FALSE(released);
  1879. db->ReleaseSnapshot(snap2);
  1880. }
  1881. // Test WritePreparedTxnDB's IsInSnapshot against different ordering of
  1882. // snapshot, max_committed_seq_, prepared, and commit entries.
  1883. TEST_P(WritePreparedTransactionTest, IsInSnapshot) {
  1884. WriteOptions wo;
  1885. // Use small commit cache to trigger lots of eviction and fast advance of
  1886. // max_evicted_seq_
  1887. const size_t commit_cache_bits = 3;
  1888. // Same for snapshot cache size
  1889. const size_t snapshot_cache_bits = 2;
  1890. // Take some preliminary snapshots first. This is to stress the data structure
  1891. // that holds the old snapshots as it will be designed to be efficient when
  1892. // only a few snapshots are below the max_evicted_seq_.
  1893. for (int max_snapshots = 1; max_snapshots < 20; max_snapshots++) {
  1894. // Leave some gap between the preliminary snapshots and the final snapshot
  1895. // that we check. This should test for also different overlapping scenarios
  1896. // between the last snapshot and the commits.
  1897. for (int max_gap = 1; max_gap < 10; max_gap++) {
  1898. // Since we do not actually write to db, we mock the seq as it would be
  1899. // increased by the db. The only exception is that we need db seq to
  1900. // advance for our snapshots. for which we apply a dummy put each time we
  1901. // increase our mock of seq.
  1902. uint64_t seq = 0;
  1903. // At each step we prepare a txn and then we commit it in the next txn.
  1904. // This emulates the consecutive transactions that write to the same key
  1905. uint64_t cur_txn = 0;
  1906. // Number of snapshots taken so far
  1907. int num_snapshots = 0;
  1908. // Number of gaps applied so far
  1909. int gap_cnt = 0;
  1910. // The final snapshot that we will inspect
  1911. uint64_t snapshot = 0;
  1912. bool found_committed = false;
  1913. // To stress the data structure that maintain prepared txns, at each cycle
  1914. // we add a new prepare txn. These do not mean to be committed for
  1915. // snapshot inspection.
  1916. std::set<uint64_t> prepared;
  1917. // We keep the list of txns committed before we take the last snapshot.
  1918. // These should be the only seq numbers that will be found in the snapshot
  1919. std::set<uint64_t> committed_before;
  1920. // The set of commit seq numbers to be excluded from IsInSnapshot queries
  1921. std::set<uint64_t> commit_seqs;
  1922. DBImpl* mock_db = new DBImpl(options, dbname);
  1923. UpdateTransactionDBOptions(snapshot_cache_bits, commit_cache_bits);
  1924. std::unique_ptr<WritePreparedTxnDBMock> wp_db(
  1925. new WritePreparedTxnDBMock(mock_db, txn_db_options));
  1926. // We continue until max advances a bit beyond the snapshot.
  1927. while (!snapshot || wp_db->max_evicted_seq_ < snapshot + 100) {
  1928. // do prepare for a transaction
  1929. seq++;
  1930. wp_db->AddPrepared(seq);
  1931. prepared.insert(seq);
  1932. // If cur_txn is not started, do prepare for it.
  1933. if (!cur_txn) {
  1934. seq++;
  1935. cur_txn = seq;
  1936. wp_db->AddPrepared(cur_txn);
  1937. } else { // else commit it
  1938. seq++;
  1939. wp_db->AddCommitted(cur_txn, seq);
  1940. wp_db->RemovePrepared(cur_txn);
  1941. commit_seqs.insert(seq);
  1942. if (!snapshot) {
  1943. committed_before.insert(cur_txn);
  1944. }
  1945. cur_txn = 0;
  1946. }
  1947. if (num_snapshots < max_snapshots - 1) {
  1948. // Take preliminary snapshots
  1949. wp_db->TakeSnapshot(seq);
  1950. num_snapshots++;
  1951. } else if (gap_cnt < max_gap) {
  1952. // Wait for some gap before taking the final snapshot
  1953. gap_cnt++;
  1954. } else if (!snapshot) {
  1955. // Take the final snapshot if it is not already taken
  1956. snapshot = seq;
  1957. wp_db->TakeSnapshot(snapshot);
  1958. num_snapshots++;
  1959. }
  1960. // If the snapshot is taken, verify seq numbers visible to it. We redo
  1961. // it at each cycle to test that the system is still sound when
  1962. // max_evicted_seq_ advances.
  1963. if (snapshot) {
  1964. for (uint64_t s = 1;
  1965. s <= seq && commit_seqs.find(s) == commit_seqs.end(); s++) {
  1966. bool was_committed =
  1967. (committed_before.find(s) != committed_before.end());
  1968. bool is_in_snapshot = wp_db->IsInSnapshot(s, snapshot);
  1969. if (was_committed != is_in_snapshot) {
  1970. printf("max_snapshots %d max_gap %d seq %" PRIu64 " max %" PRIu64
  1971. " snapshot %" PRIu64
  1972. " gap_cnt %d num_snapshots %d s %" PRIu64 "\n",
  1973. max_snapshots, max_gap, seq,
  1974. wp_db->max_evicted_seq_.load(), snapshot, gap_cnt,
  1975. num_snapshots, s);
  1976. }
  1977. ASSERT_EQ(was_committed, is_in_snapshot);
  1978. found_committed = found_committed || is_in_snapshot;
  1979. }
  1980. }
  1981. }
  1982. // Safety check to make sure the test actually ran
  1983. ASSERT_TRUE(found_committed);
  1984. // As an extra check, check if prepared set will be properly empty after
  1985. // they are committed.
  1986. if (cur_txn) {
  1987. wp_db->AddCommitted(cur_txn, seq);
  1988. wp_db->RemovePrepared(cur_txn);
  1989. }
  1990. for (auto p : prepared) {
  1991. wp_db->AddCommitted(p, seq);
  1992. wp_db->RemovePrepared(p);
  1993. }
  1994. ASSERT_TRUE(wp_db->delayed_prepared_.empty());
  1995. ASSERT_TRUE(wp_db->prepared_txns_.empty());
  1996. }
  1997. }
  1998. }
  1999. void ASSERT_SAME(ReadOptions roptions, TransactionDB* db, Status exp_s,
  2000. PinnableSlice& exp_v, Slice key) {
  2001. Status s;
  2002. PinnableSlice v;
  2003. s = db->Get(roptions, db->DefaultColumnFamily(), key, &v);
  2004. ASSERT_TRUE(exp_s == s);
  2005. ASSERT_TRUE(s.ok() || s.IsNotFound());
  2006. if (s.ok()) {
  2007. ASSERT_TRUE(exp_v == v);
  2008. }
  2009. // Try with MultiGet API too
  2010. std::vector<std::string> values;
  2011. auto s_vec =
  2012. db->MultiGet(roptions, {db->DefaultColumnFamily()}, {key}, &values);
  2013. ASSERT_EQ(1, values.size());
  2014. ASSERT_EQ(1, s_vec.size());
  2015. s = s_vec[0];
  2016. ASSERT_TRUE(exp_s == s);
  2017. ASSERT_TRUE(s.ok() || s.IsNotFound());
  2018. if (s.ok()) {
  2019. ASSERT_TRUE(exp_v == values[0]);
  2020. }
  2021. }
  2022. void ASSERT_SAME(TransactionDB* db, Status exp_s, PinnableSlice& exp_v,
  2023. Slice key) {
  2024. ASSERT_SAME(ReadOptions(), db, exp_s, exp_v, key);
  2025. }
  2026. TEST_P(WritePreparedTransactionTest, Rollback) {
  2027. ReadOptions roptions;
  2028. WriteOptions woptions;
  2029. TransactionOptions txn_options;
  2030. const size_t num_keys = 4;
  2031. const size_t num_values = 5;
  2032. for (size_t ikey = 1; ikey <= num_keys; ikey++) {
  2033. for (size_t ivalue = 0; ivalue < num_values; ivalue++) {
  2034. for (bool crash : {false, true}) {
  2035. ReOpen();
  2036. WritePreparedTxnDB* wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  2037. std::string key_str = "key" + ToString(ikey);
  2038. switch (ivalue) {
  2039. case 0:
  2040. break;
  2041. case 1:
  2042. ASSERT_OK(db->Put(woptions, key_str, "initvalue1"));
  2043. break;
  2044. case 2:
  2045. ASSERT_OK(db->Merge(woptions, key_str, "initvalue2"));
  2046. break;
  2047. case 3:
  2048. ASSERT_OK(db->Delete(woptions, key_str));
  2049. break;
  2050. case 4:
  2051. ASSERT_OK(db->SingleDelete(woptions, key_str));
  2052. break;
  2053. default:
  2054. assert(0);
  2055. }
  2056. PinnableSlice v1;
  2057. auto s1 =
  2058. db->Get(roptions, db->DefaultColumnFamily(), Slice("key1"), &v1);
  2059. PinnableSlice v2;
  2060. auto s2 =
  2061. db->Get(roptions, db->DefaultColumnFamily(), Slice("key2"), &v2);
  2062. PinnableSlice v3;
  2063. auto s3 =
  2064. db->Get(roptions, db->DefaultColumnFamily(), Slice("key3"), &v3);
  2065. PinnableSlice v4;
  2066. auto s4 =
  2067. db->Get(roptions, db->DefaultColumnFamily(), Slice("key4"), &v4);
  2068. Transaction* txn = db->BeginTransaction(woptions, txn_options);
  2069. auto s = txn->SetName("xid0");
  2070. ASSERT_OK(s);
  2071. s = txn->Put(Slice("key1"), Slice("value1"));
  2072. ASSERT_OK(s);
  2073. s = txn->Merge(Slice("key2"), Slice("value2"));
  2074. ASSERT_OK(s);
  2075. s = txn->Delete(Slice("key3"));
  2076. ASSERT_OK(s);
  2077. s = txn->SingleDelete(Slice("key4"));
  2078. ASSERT_OK(s);
  2079. s = txn->Prepare();
  2080. ASSERT_OK(s);
  2081. {
  2082. ReadLock rl(&wp_db->prepared_mutex_);
  2083. ASSERT_FALSE(wp_db->prepared_txns_.empty());
  2084. ASSERT_EQ(txn->GetId(), wp_db->prepared_txns_.top());
  2085. }
  2086. ASSERT_SAME(db, s1, v1, "key1");
  2087. ASSERT_SAME(db, s2, v2, "key2");
  2088. ASSERT_SAME(db, s3, v3, "key3");
  2089. ASSERT_SAME(db, s4, v4, "key4");
  2090. if (crash) {
  2091. delete txn;
  2092. auto db_impl = reinterpret_cast<DBImpl*>(db->GetRootDB());
  2093. db_impl->FlushWAL(true);
  2094. dynamic_cast<WritePreparedTxnDB*>(db)->TEST_Crash();
  2095. ReOpenNoDelete();
  2096. assert(db != nullptr);
  2097. wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  2098. txn = db->GetTransactionByName("xid0");
  2099. ASSERT_FALSE(wp_db->delayed_prepared_empty_);
  2100. ReadLock rl(&wp_db->prepared_mutex_);
  2101. ASSERT_TRUE(wp_db->prepared_txns_.empty());
  2102. ASSERT_FALSE(wp_db->delayed_prepared_.empty());
  2103. ASSERT_TRUE(wp_db->delayed_prepared_.find(txn->GetId()) !=
  2104. wp_db->delayed_prepared_.end());
  2105. }
  2106. ASSERT_SAME(db, s1, v1, "key1");
  2107. ASSERT_SAME(db, s2, v2, "key2");
  2108. ASSERT_SAME(db, s3, v3, "key3");
  2109. ASSERT_SAME(db, s4, v4, "key4");
  2110. s = txn->Rollback();
  2111. ASSERT_OK(s);
  2112. {
  2113. ASSERT_TRUE(wp_db->delayed_prepared_empty_);
  2114. ReadLock rl(&wp_db->prepared_mutex_);
  2115. ASSERT_TRUE(wp_db->prepared_txns_.empty());
  2116. ASSERT_TRUE(wp_db->delayed_prepared_.empty());
  2117. }
  2118. ASSERT_SAME(db, s1, v1, "key1");
  2119. ASSERT_SAME(db, s2, v2, "key2");
  2120. ASSERT_SAME(db, s3, v3, "key3");
  2121. ASSERT_SAME(db, s4, v4, "key4");
  2122. delete txn;
  2123. }
  2124. }
  2125. }
  2126. }
  2127. TEST_P(WritePreparedTransactionTest, DisableGCDuringRecovery) {
  2128. // Use large buffer to avoid memtable flush after 1024 insertions
  2129. options.write_buffer_size = 1024 * 1024;
  2130. ReOpen();
  2131. std::vector<KeyVersion> versions;
  2132. uint64_t seq = 0;
  2133. for (uint64_t i = 1; i <= 1024; i++) {
  2134. std::string v = "bar" + ToString(i);
  2135. ASSERT_OK(db->Put(WriteOptions(), "foo", v));
  2136. VerifyKeys({{"foo", v}});
  2137. seq++; // one for the key/value
  2138. KeyVersion kv = {"foo", v, seq, kTypeValue};
  2139. if (options.two_write_queues) {
  2140. seq++; // one for the commit
  2141. }
  2142. versions.emplace_back(kv);
  2143. }
  2144. std::reverse(std::begin(versions), std::end(versions));
  2145. VerifyInternalKeys(versions);
  2146. DBImpl* db_impl = reinterpret_cast<DBImpl*>(db->GetRootDB());
  2147. db_impl->FlushWAL(true);
  2148. // Use small buffer to ensure memtable flush during recovery
  2149. options.write_buffer_size = 1024;
  2150. ReOpenNoDelete();
  2151. VerifyInternalKeys(versions);
  2152. }
  2153. TEST_P(WritePreparedTransactionTest, SequenceNumberZero) {
  2154. ASSERT_OK(db->Put(WriteOptions(), "foo", "bar"));
  2155. VerifyKeys({{"foo", "bar"}});
  2156. const Snapshot* snapshot = db->GetSnapshot();
  2157. ASSERT_OK(db->Flush(FlushOptions()));
  2158. // Dummy keys to avoid compaction trivially move files and get around actual
  2159. // compaction logic.
  2160. ASSERT_OK(db->Put(WriteOptions(), "a", "dummy"));
  2161. ASSERT_OK(db->Put(WriteOptions(), "z", "dummy"));
  2162. ASSERT_OK(db->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  2163. // Compaction will output keys with sequence number 0, if it is visible to
  2164. // earliest snapshot. Make sure IsInSnapshot() report sequence number 0 is
  2165. // visible to any snapshot.
  2166. VerifyKeys({{"foo", "bar"}});
  2167. VerifyKeys({{"foo", "bar"}}, snapshot);
  2168. VerifyInternalKeys({{"foo", "bar", 0, kTypeValue}});
  2169. db->ReleaseSnapshot(snapshot);
  2170. }
  2171. // Compaction should not remove a key if it is not committed, and should
  2172. // proceed with older versions of the key as-if the new version doesn't exist.
  2173. TEST_P(WritePreparedTransactionTest, CompactionShouldKeepUncommittedKeys) {
  2174. options.disable_auto_compactions = true;
  2175. ReOpen();
  2176. DBImpl* db_impl = reinterpret_cast<DBImpl*>(db->GetRootDB());
  2177. // Snapshots to avoid keys get evicted.
  2178. std::vector<const Snapshot*> snapshots;
  2179. // Keep track of expected sequence number.
  2180. SequenceNumber expected_seq = 0;
  2181. auto add_key = [&](std::function<Status()> func) {
  2182. ASSERT_OK(func());
  2183. expected_seq++;
  2184. if (options.two_write_queues) {
  2185. expected_seq++; // 1 for commit
  2186. }
  2187. ASSERT_EQ(expected_seq, db_impl->TEST_GetLastVisibleSequence());
  2188. snapshots.push_back(db->GetSnapshot());
  2189. };
  2190. // Each key here represent a standalone test case.
  2191. add_key([&]() { return db->Put(WriteOptions(), "key1", "value1_1"); });
  2192. add_key([&]() { return db->Put(WriteOptions(), "key2", "value2_1"); });
  2193. add_key([&]() { return db->Put(WriteOptions(), "key3", "value3_1"); });
  2194. add_key([&]() { return db->Put(WriteOptions(), "key4", "value4_1"); });
  2195. add_key([&]() { return db->Merge(WriteOptions(), "key5", "value5_1"); });
  2196. add_key([&]() { return db->Merge(WriteOptions(), "key5", "value5_2"); });
  2197. add_key([&]() { return db->Put(WriteOptions(), "key6", "value6_1"); });
  2198. add_key([&]() { return db->Put(WriteOptions(), "key7", "value7_1"); });
  2199. ASSERT_OK(db->Flush(FlushOptions()));
  2200. add_key([&]() { return db->Delete(WriteOptions(), "key6"); });
  2201. add_key([&]() { return db->SingleDelete(WriteOptions(), "key7"); });
  2202. auto* transaction = db->BeginTransaction(WriteOptions());
  2203. ASSERT_OK(transaction->SetName("txn"));
  2204. ASSERT_OK(transaction->Put("key1", "value1_2"));
  2205. ASSERT_OK(transaction->Delete("key2"));
  2206. ASSERT_OK(transaction->SingleDelete("key3"));
  2207. ASSERT_OK(transaction->Merge("key4", "value4_2"));
  2208. ASSERT_OK(transaction->Merge("key5", "value5_3"));
  2209. ASSERT_OK(transaction->Put("key6", "value6_2"));
  2210. ASSERT_OK(transaction->Put("key7", "value7_2"));
  2211. // Prepare but not commit.
  2212. ASSERT_OK(transaction->Prepare());
  2213. ASSERT_EQ(++expected_seq, db->GetLatestSequenceNumber());
  2214. ASSERT_OK(db->Flush(FlushOptions()));
  2215. for (auto* s : snapshots) {
  2216. db->ReleaseSnapshot(s);
  2217. }
  2218. // Dummy keys to avoid compaction trivially move files and get around actual
  2219. // compaction logic.
  2220. ASSERT_OK(db->Put(WriteOptions(), "a", "dummy"));
  2221. ASSERT_OK(db->Put(WriteOptions(), "z", "dummy"));
  2222. ASSERT_OK(db->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  2223. VerifyKeys({
  2224. {"key1", "value1_1"},
  2225. {"key2", "value2_1"},
  2226. {"key3", "value3_1"},
  2227. {"key4", "value4_1"},
  2228. {"key5", "value5_1,value5_2"},
  2229. {"key6", "NOT_FOUND"},
  2230. {"key7", "NOT_FOUND"},
  2231. });
  2232. VerifyInternalKeys({
  2233. {"key1", "value1_2", expected_seq, kTypeValue},
  2234. {"key1", "value1_1", 0, kTypeValue},
  2235. {"key2", "", expected_seq, kTypeDeletion},
  2236. {"key2", "value2_1", 0, kTypeValue},
  2237. {"key3", "", expected_seq, kTypeSingleDeletion},
  2238. {"key3", "value3_1", 0, kTypeValue},
  2239. {"key4", "value4_2", expected_seq, kTypeMerge},
  2240. {"key4", "value4_1", 0, kTypeValue},
  2241. {"key5", "value5_3", expected_seq, kTypeMerge},
  2242. {"key5", "value5_1,value5_2", 0, kTypeValue},
  2243. {"key6", "value6_2", expected_seq, kTypeValue},
  2244. {"key7", "value7_2", expected_seq, kTypeValue},
  2245. });
  2246. ASSERT_OK(transaction->Commit());
  2247. VerifyKeys({
  2248. {"key1", "value1_2"},
  2249. {"key2", "NOT_FOUND"},
  2250. {"key3", "NOT_FOUND"},
  2251. {"key4", "value4_1,value4_2"},
  2252. {"key5", "value5_1,value5_2,value5_3"},
  2253. {"key6", "value6_2"},
  2254. {"key7", "value7_2"},
  2255. });
  2256. delete transaction;
  2257. }
  2258. // Compaction should keep keys visible to a snapshot based on commit sequence,
  2259. // not just prepare sequence.
  2260. TEST_P(WritePreparedTransactionTest, CompactionShouldKeepSnapshotVisibleKeys) {
  2261. options.disable_auto_compactions = true;
  2262. ReOpen();
  2263. // Keep track of expected sequence number.
  2264. SequenceNumber expected_seq = 0;
  2265. auto* txn1 = db->BeginTransaction(WriteOptions());
  2266. ASSERT_OK(txn1->SetName("txn1"));
  2267. ASSERT_OK(txn1->Put("key1", "value1_1"));
  2268. ASSERT_OK(txn1->Prepare());
  2269. ASSERT_EQ(++expected_seq, db->GetLatestSequenceNumber());
  2270. ASSERT_OK(txn1->Commit());
  2271. DBImpl* db_impl = reinterpret_cast<DBImpl*>(db->GetRootDB());
  2272. ASSERT_EQ(++expected_seq, db_impl->TEST_GetLastVisibleSequence());
  2273. delete txn1;
  2274. // Take a snapshots to avoid keys get evicted before compaction.
  2275. const Snapshot* snapshot1 = db->GetSnapshot();
  2276. auto* txn2 = db->BeginTransaction(WriteOptions());
  2277. ASSERT_OK(txn2->SetName("txn2"));
  2278. ASSERT_OK(txn2->Put("key2", "value2_1"));
  2279. ASSERT_OK(txn2->Prepare());
  2280. ASSERT_EQ(++expected_seq, db->GetLatestSequenceNumber());
  2281. // txn1 commit before snapshot2 and it is visible to snapshot2.
  2282. // txn2 commit after snapshot2 and it is not visible.
  2283. const Snapshot* snapshot2 = db->GetSnapshot();
  2284. ASSERT_OK(txn2->Commit());
  2285. ASSERT_EQ(++expected_seq, db_impl->TEST_GetLastVisibleSequence());
  2286. delete txn2;
  2287. // Take a snapshots to avoid keys get evicted before compaction.
  2288. const Snapshot* snapshot3 = db->GetSnapshot();
  2289. ASSERT_OK(db->Put(WriteOptions(), "key1", "value1_2"));
  2290. expected_seq++; // 1 for write
  2291. SequenceNumber seq1 = expected_seq;
  2292. if (options.two_write_queues) {
  2293. expected_seq++; // 1 for commit
  2294. }
  2295. ASSERT_EQ(expected_seq, db_impl->TEST_GetLastVisibleSequence());
  2296. ASSERT_OK(db->Put(WriteOptions(), "key2", "value2_2"));
  2297. expected_seq++; // 1 for write
  2298. SequenceNumber seq2 = expected_seq;
  2299. if (options.two_write_queues) {
  2300. expected_seq++; // 1 for commit
  2301. }
  2302. ASSERT_EQ(expected_seq, db_impl->TEST_GetLastVisibleSequence());
  2303. ASSERT_OK(db->Flush(FlushOptions()));
  2304. db->ReleaseSnapshot(snapshot1);
  2305. db->ReleaseSnapshot(snapshot3);
  2306. // Dummy keys to avoid compaction trivially move files and get around actual
  2307. // compaction logic.
  2308. ASSERT_OK(db->Put(WriteOptions(), "a", "dummy"));
  2309. ASSERT_OK(db->Put(WriteOptions(), "z", "dummy"));
  2310. ASSERT_OK(db->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  2311. VerifyKeys({{"key1", "value1_2"}, {"key2", "value2_2"}});
  2312. VerifyKeys({{"key1", "value1_1"}, {"key2", "NOT_FOUND"}}, snapshot2);
  2313. VerifyInternalKeys({
  2314. {"key1", "value1_2", seq1, kTypeValue},
  2315. // "value1_1" is visible to snapshot2. Also keys at bottom level visible
  2316. // to earliest snapshot will output with seq = 0.
  2317. {"key1", "value1_1", 0, kTypeValue},
  2318. {"key2", "value2_2", seq2, kTypeValue},
  2319. });
  2320. db->ReleaseSnapshot(snapshot2);
  2321. }
  2322. TEST_P(WritePreparedTransactionTest, SmallestUncommittedOptimization) {
  2323. const size_t snapshot_cache_bits = 7; // same as default
  2324. const size_t commit_cache_bits = 0; // disable commit cache
  2325. for (bool has_recent_prepare : {true, false}) {
  2326. UpdateTransactionDBOptions(snapshot_cache_bits, commit_cache_bits);
  2327. ReOpen();
  2328. ASSERT_OK(db->Put(WriteOptions(), "key1", "value1"));
  2329. auto* transaction =
  2330. db->BeginTransaction(WriteOptions(), TransactionOptions(), nullptr);
  2331. ASSERT_OK(transaction->SetName("txn"));
  2332. ASSERT_OK(transaction->Delete("key1"));
  2333. ASSERT_OK(transaction->Prepare());
  2334. // snapshot1 should get min_uncommitted from prepared_txns_ heap.
  2335. auto snapshot1 = db->GetSnapshot();
  2336. ASSERT_EQ(transaction->GetId(),
  2337. ((SnapshotImpl*)snapshot1)->min_uncommitted_);
  2338. // Add a commit to advance max_evicted_seq and move the prepared transaction
  2339. // into delayed_prepared_ set.
  2340. ASSERT_OK(db->Put(WriteOptions(), "key2", "value2"));
  2341. Transaction* txn2 = nullptr;
  2342. if (has_recent_prepare) {
  2343. txn2 =
  2344. db->BeginTransaction(WriteOptions(), TransactionOptions(), nullptr);
  2345. ASSERT_OK(txn2->SetName("txn2"));
  2346. ASSERT_OK(txn2->Put("key3", "value3"));
  2347. ASSERT_OK(txn2->Prepare());
  2348. }
  2349. // snapshot2 should get min_uncommitted from delayed_prepared_ set.
  2350. auto snapshot2 = db->GetSnapshot();
  2351. ASSERT_EQ(transaction->GetId(),
  2352. ((SnapshotImpl*)snapshot1)->min_uncommitted_);
  2353. ASSERT_OK(transaction->Commit());
  2354. delete transaction;
  2355. if (has_recent_prepare) {
  2356. ASSERT_OK(txn2->Commit());
  2357. delete txn2;
  2358. }
  2359. VerifyKeys({{"key1", "NOT_FOUND"}});
  2360. VerifyKeys({{"key1", "value1"}}, snapshot1);
  2361. VerifyKeys({{"key1", "value1"}}, snapshot2);
  2362. db->ReleaseSnapshot(snapshot1);
  2363. db->ReleaseSnapshot(snapshot2);
  2364. }
  2365. }
  2366. // Insert two values, v1 and v2, for a key. Between prepare and commit of v2
  2367. // take two snapshots, s1 and s2. Release s1 during compaction.
  2368. // Test to make sure compaction doesn't get confused and think s1 can see both
  2369. // values, and thus compact out the older value by mistake.
  2370. TEST_P(WritePreparedTransactionTest, ReleaseSnapshotDuringCompaction) {
  2371. const size_t snapshot_cache_bits = 7; // same as default
  2372. const size_t commit_cache_bits = 0; // minimum commit cache
  2373. UpdateTransactionDBOptions(snapshot_cache_bits, commit_cache_bits);
  2374. ReOpen();
  2375. ASSERT_OK(db->Put(WriteOptions(), "key1", "value1_1"));
  2376. auto* transaction =
  2377. db->BeginTransaction(WriteOptions(), TransactionOptions(), nullptr);
  2378. ASSERT_OK(transaction->SetName("txn"));
  2379. ASSERT_OK(transaction->Put("key1", "value1_2"));
  2380. ASSERT_OK(transaction->Prepare());
  2381. auto snapshot1 = db->GetSnapshot();
  2382. // Increment sequence number.
  2383. ASSERT_OK(db->Put(WriteOptions(), "key2", "value2"));
  2384. auto snapshot2 = db->GetSnapshot();
  2385. ASSERT_OK(transaction->Commit());
  2386. delete transaction;
  2387. VerifyKeys({{"key1", "value1_2"}});
  2388. VerifyKeys({{"key1", "value1_1"}}, snapshot1);
  2389. VerifyKeys({{"key1", "value1_1"}}, snapshot2);
  2390. // Add a flush to avoid compaction to fallback to trivial move.
  2391. auto callback = [&](void*) {
  2392. // Release snapshot1 after CompactionIterator init.
  2393. // CompactionIterator need to figure out the earliest snapshot
  2394. // that can see key1:value1_2 is kMaxSequenceNumber, not
  2395. // snapshot1 or snapshot2.
  2396. db->ReleaseSnapshot(snapshot1);
  2397. // Add some keys to advance max_evicted_seq.
  2398. ASSERT_OK(db->Put(WriteOptions(), "key3", "value3"));
  2399. ASSERT_OK(db->Put(WriteOptions(), "key4", "value4"));
  2400. };
  2401. SyncPoint::GetInstance()->SetCallBack("CompactionIterator:AfterInit",
  2402. callback);
  2403. SyncPoint::GetInstance()->EnableProcessing();
  2404. ASSERT_OK(db->Flush(FlushOptions()));
  2405. VerifyKeys({{"key1", "value1_2"}});
  2406. VerifyKeys({{"key1", "value1_1"}}, snapshot2);
  2407. db->ReleaseSnapshot(snapshot2);
  2408. SyncPoint::GetInstance()->ClearAllCallBacks();
  2409. }
  2410. // Insert two values, v1 and v2, for a key. Take two snapshots, s1 and s2,
  2411. // after committing v2. Release s1 during compaction, right after compaction
  2412. // processes v2 and before processes v1. Test to make sure compaction doesn't
  2413. // get confused and believe v1 and v2 are visible to different snapshot
  2414. // (v1 by s2, v2 by s1) and refuse to compact out v1.
  2415. TEST_P(WritePreparedTransactionTest, ReleaseSnapshotDuringCompaction2) {
  2416. const size_t snapshot_cache_bits = 7; // same as default
  2417. const size_t commit_cache_bits = 0; // minimum commit cache
  2418. UpdateTransactionDBOptions(snapshot_cache_bits, commit_cache_bits);
  2419. ReOpen();
  2420. ASSERT_OK(db->Put(WriteOptions(), "key1", "value1"));
  2421. ASSERT_OK(db->Put(WriteOptions(), "key1", "value2"));
  2422. SequenceNumber v2_seq = db->GetLatestSequenceNumber();
  2423. auto* s1 = db->GetSnapshot();
  2424. // Advance sequence number.
  2425. ASSERT_OK(db->Put(WriteOptions(), "key2", "dummy"));
  2426. auto* s2 = db->GetSnapshot();
  2427. int count_value = 0;
  2428. auto callback = [&](void* arg) {
  2429. auto* ikey = reinterpret_cast<ParsedInternalKey*>(arg);
  2430. if (ikey->user_key == "key1") {
  2431. count_value++;
  2432. if (count_value == 2) {
  2433. // Processing v1.
  2434. db->ReleaseSnapshot(s1);
  2435. // Add some keys to advance max_evicted_seq and update
  2436. // old_commit_map.
  2437. ASSERT_OK(db->Put(WriteOptions(), "key3", "dummy"));
  2438. ASSERT_OK(db->Put(WriteOptions(), "key4", "dummy"));
  2439. }
  2440. }
  2441. };
  2442. SyncPoint::GetInstance()->SetCallBack("CompactionIterator:ProcessKV",
  2443. callback);
  2444. SyncPoint::GetInstance()->EnableProcessing();
  2445. ASSERT_OK(db->Flush(FlushOptions()));
  2446. // value1 should be compact out.
  2447. VerifyInternalKeys({{"key1", "value2", v2_seq, kTypeValue}});
  2448. // cleanup
  2449. db->ReleaseSnapshot(s2);
  2450. SyncPoint::GetInstance()->ClearAllCallBacks();
  2451. }
  2452. // Insert two values, v1 and v2, for a key. Insert another dummy key
  2453. // so to evict the commit cache for v2, while v1 is still in commit cache.
  2454. // Take two snapshots, s1 and s2. Release s1 during compaction.
  2455. // Since commit cache for v2 is evicted, and old_commit_map don't have
  2456. // s1 (it is released),
  2457. // TODO(myabandeh): how can we be sure that the v2's commit info is evicted
  2458. // (and not v1's)? Instead of putting a dummy, we can directly call
  2459. // AddCommitted(v2_seq + cache_size, ...) to evict v2's entry from commit cache.
  2460. TEST_P(WritePreparedTransactionTest, ReleaseSnapshotDuringCompaction3) {
  2461. const size_t snapshot_cache_bits = 7; // same as default
  2462. const size_t commit_cache_bits = 1; // commit cache size = 2
  2463. UpdateTransactionDBOptions(snapshot_cache_bits, commit_cache_bits);
  2464. ReOpen();
  2465. // Add a dummy key to evict v2 commit cache, but keep v1 commit cache.
  2466. // It also advance max_evicted_seq and can trigger old_commit_map cleanup.
  2467. auto add_dummy = [&]() {
  2468. auto* txn_dummy =
  2469. db->BeginTransaction(WriteOptions(), TransactionOptions(), nullptr);
  2470. ASSERT_OK(txn_dummy->SetName("txn_dummy"));
  2471. ASSERT_OK(txn_dummy->Put("dummy", "dummy"));
  2472. ASSERT_OK(txn_dummy->Prepare());
  2473. ASSERT_OK(txn_dummy->Commit());
  2474. delete txn_dummy;
  2475. };
  2476. ASSERT_OK(db->Put(WriteOptions(), "key1", "value1"));
  2477. auto* txn =
  2478. db->BeginTransaction(WriteOptions(), TransactionOptions(), nullptr);
  2479. ASSERT_OK(txn->SetName("txn"));
  2480. ASSERT_OK(txn->Put("key1", "value2"));
  2481. ASSERT_OK(txn->Prepare());
  2482. // TODO(myabandeh): replace it with GetId()?
  2483. auto v2_seq = db->GetLatestSequenceNumber();
  2484. ASSERT_OK(txn->Commit());
  2485. delete txn;
  2486. auto* s1 = db->GetSnapshot();
  2487. // Dummy key to advance sequence number.
  2488. add_dummy();
  2489. auto* s2 = db->GetSnapshot();
  2490. auto callback = [&](void*) {
  2491. db->ReleaseSnapshot(s1);
  2492. // Add some dummy entries to trigger s1 being cleanup from old_commit_map.
  2493. add_dummy();
  2494. add_dummy();
  2495. };
  2496. SyncPoint::GetInstance()->SetCallBack("CompactionIterator:AfterInit",
  2497. callback);
  2498. SyncPoint::GetInstance()->EnableProcessing();
  2499. ASSERT_OK(db->Flush(FlushOptions()));
  2500. // value1 should be compact out.
  2501. VerifyInternalKeys({{"key1", "value2", v2_seq, kTypeValue}});
  2502. db->ReleaseSnapshot(s2);
  2503. SyncPoint::GetInstance()->ClearAllCallBacks();
  2504. }
  2505. TEST_P(WritePreparedTransactionTest, ReleaseEarliestSnapshotDuringCompaction) {
  2506. const size_t snapshot_cache_bits = 7; // same as default
  2507. const size_t commit_cache_bits = 0; // minimum commit cache
  2508. UpdateTransactionDBOptions(snapshot_cache_bits, commit_cache_bits);
  2509. ReOpen();
  2510. ASSERT_OK(db->Put(WriteOptions(), "key1", "value1"));
  2511. auto* transaction =
  2512. db->BeginTransaction(WriteOptions(), TransactionOptions(), nullptr);
  2513. ASSERT_OK(transaction->SetName("txn"));
  2514. ASSERT_OK(transaction->Delete("key1"));
  2515. ASSERT_OK(transaction->Prepare());
  2516. SequenceNumber del_seq = db->GetLatestSequenceNumber();
  2517. auto snapshot1 = db->GetSnapshot();
  2518. // Increment sequence number.
  2519. ASSERT_OK(db->Put(WriteOptions(), "key2", "value2"));
  2520. auto snapshot2 = db->GetSnapshot();
  2521. ASSERT_OK(transaction->Commit());
  2522. delete transaction;
  2523. VerifyKeys({{"key1", "NOT_FOUND"}});
  2524. VerifyKeys({{"key1", "value1"}}, snapshot1);
  2525. VerifyKeys({{"key1", "value1"}}, snapshot2);
  2526. ASSERT_OK(db->Flush(FlushOptions()));
  2527. auto callback = [&](void* compaction) {
  2528. // Release snapshot1 after CompactionIterator init.
  2529. // CompactionIterator need to double check and find out snapshot2 is now
  2530. // the earliest existing snapshot.
  2531. if (compaction != nullptr) {
  2532. db->ReleaseSnapshot(snapshot1);
  2533. // Add some keys to advance max_evicted_seq.
  2534. ASSERT_OK(db->Put(WriteOptions(), "key3", "value3"));
  2535. ASSERT_OK(db->Put(WriteOptions(), "key4", "value4"));
  2536. }
  2537. };
  2538. SyncPoint::GetInstance()->SetCallBack("CompactionIterator:AfterInit",
  2539. callback);
  2540. SyncPoint::GetInstance()->EnableProcessing();
  2541. // Dummy keys to avoid compaction trivially move files and get around actual
  2542. // compaction logic.
  2543. ASSERT_OK(db->Put(WriteOptions(), "a", "dummy"));
  2544. ASSERT_OK(db->Put(WriteOptions(), "z", "dummy"));
  2545. ASSERT_OK(db->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  2546. // Only verify for key1. Both the put and delete for the key should be kept.
  2547. // Since the delete tombstone is not visible to snapshot2, we need to keep
  2548. // at least one version of the key, for write-conflict check.
  2549. VerifyInternalKeys({{"key1", "", del_seq, kTypeDeletion},
  2550. {"key1", "value1", 0, kTypeValue}});
  2551. db->ReleaseSnapshot(snapshot2);
  2552. SyncPoint::GetInstance()->ClearAllCallBacks();
  2553. }
  2554. // A more complex test to verify compaction/flush should keep keys visible
  2555. // to snapshots.
  2556. TEST_P(WritePreparedTransactionTest,
  2557. CompactionKeepSnapshotVisibleKeysRandomized) {
  2558. constexpr size_t kNumTransactions = 10;
  2559. constexpr size_t kNumIterations = 1000;
  2560. std::vector<Transaction*> transactions(kNumTransactions, nullptr);
  2561. std::vector<size_t> versions(kNumTransactions, 0);
  2562. std::unordered_map<std::string, std::string> current_data;
  2563. std::vector<const Snapshot*> snapshots;
  2564. std::vector<std::unordered_map<std::string, std::string>> snapshot_data;
  2565. Random rnd(1103);
  2566. options.disable_auto_compactions = true;
  2567. ReOpen();
  2568. for (size_t i = 0; i < kNumTransactions; i++) {
  2569. std::string key = "key" + ToString(i);
  2570. std::string value = "value0";
  2571. ASSERT_OK(db->Put(WriteOptions(), key, value));
  2572. current_data[key] = value;
  2573. }
  2574. VerifyKeys(current_data);
  2575. for (size_t iter = 0; iter < kNumIterations; iter++) {
  2576. auto r = rnd.Next() % (kNumTransactions + 1);
  2577. if (r < kNumTransactions) {
  2578. std::string key = "key" + ToString(r);
  2579. if (transactions[r] == nullptr) {
  2580. std::string value = "value" + ToString(versions[r] + 1);
  2581. auto* txn = db->BeginTransaction(WriteOptions());
  2582. ASSERT_OK(txn->SetName("txn" + ToString(r)));
  2583. ASSERT_OK(txn->Put(key, value));
  2584. ASSERT_OK(txn->Prepare());
  2585. transactions[r] = txn;
  2586. } else {
  2587. std::string value = "value" + ToString(++versions[r]);
  2588. ASSERT_OK(transactions[r]->Commit());
  2589. delete transactions[r];
  2590. transactions[r] = nullptr;
  2591. current_data[key] = value;
  2592. }
  2593. } else {
  2594. auto* snapshot = db->GetSnapshot();
  2595. VerifyKeys(current_data, snapshot);
  2596. snapshots.push_back(snapshot);
  2597. snapshot_data.push_back(current_data);
  2598. }
  2599. VerifyKeys(current_data);
  2600. }
  2601. // Take a last snapshot to test compaction with uncommitted prepared
  2602. // transaction.
  2603. snapshots.push_back(db->GetSnapshot());
  2604. snapshot_data.push_back(current_data);
  2605. assert(snapshots.size() == snapshot_data.size());
  2606. for (size_t i = 0; i < snapshots.size(); i++) {
  2607. VerifyKeys(snapshot_data[i], snapshots[i]);
  2608. }
  2609. ASSERT_OK(db->Flush(FlushOptions()));
  2610. for (size_t i = 0; i < snapshots.size(); i++) {
  2611. VerifyKeys(snapshot_data[i], snapshots[i]);
  2612. }
  2613. // Dummy keys to avoid compaction trivially move files and get around actual
  2614. // compaction logic.
  2615. ASSERT_OK(db->Put(WriteOptions(), "a", "dummy"));
  2616. ASSERT_OK(db->Put(WriteOptions(), "z", "dummy"));
  2617. ASSERT_OK(db->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  2618. for (size_t i = 0; i < snapshots.size(); i++) {
  2619. VerifyKeys(snapshot_data[i], snapshots[i]);
  2620. }
  2621. // cleanup
  2622. for (size_t i = 0; i < kNumTransactions; i++) {
  2623. if (transactions[i] == nullptr) {
  2624. continue;
  2625. }
  2626. ASSERT_OK(transactions[i]->Commit());
  2627. delete transactions[i];
  2628. }
  2629. for (size_t i = 0; i < snapshots.size(); i++) {
  2630. db->ReleaseSnapshot(snapshots[i]);
  2631. }
  2632. }
  2633. // Compaction should not apply the optimization to output key with sequence
  2634. // number equal to 0 if the key is not visible to earliest snapshot, based on
  2635. // commit sequence number.
  2636. TEST_P(WritePreparedTransactionTest,
  2637. CompactionShouldKeepSequenceForUncommittedKeys) {
  2638. options.disable_auto_compactions = true;
  2639. ReOpen();
  2640. // Keep track of expected sequence number.
  2641. SequenceNumber expected_seq = 0;
  2642. auto* transaction = db->BeginTransaction(WriteOptions());
  2643. ASSERT_OK(transaction->SetName("txn"));
  2644. ASSERT_OK(transaction->Put("key1", "value1"));
  2645. ASSERT_OK(transaction->Prepare());
  2646. ASSERT_EQ(++expected_seq, db->GetLatestSequenceNumber());
  2647. SequenceNumber seq1 = expected_seq;
  2648. ASSERT_OK(db->Put(WriteOptions(), "key2", "value2"));
  2649. DBImpl* db_impl = reinterpret_cast<DBImpl*>(db->GetRootDB());
  2650. expected_seq++; // one for data
  2651. if (options.two_write_queues) {
  2652. expected_seq++; // one for commit
  2653. }
  2654. ASSERT_EQ(expected_seq, db_impl->TEST_GetLastVisibleSequence());
  2655. ASSERT_OK(db->Flush(FlushOptions()));
  2656. // Dummy keys to avoid compaction trivially move files and get around actual
  2657. // compaction logic.
  2658. ASSERT_OK(db->Put(WriteOptions(), "a", "dummy"));
  2659. ASSERT_OK(db->Put(WriteOptions(), "z", "dummy"));
  2660. ASSERT_OK(db->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  2661. VerifyKeys({
  2662. {"key1", "NOT_FOUND"},
  2663. {"key2", "value2"},
  2664. });
  2665. VerifyInternalKeys({
  2666. // "key1" has not been committed. It keeps its sequence number.
  2667. {"key1", "value1", seq1, kTypeValue},
  2668. // "key2" is committed and output with seq = 0.
  2669. {"key2", "value2", 0, kTypeValue},
  2670. });
  2671. ASSERT_OK(transaction->Commit());
  2672. VerifyKeys({
  2673. {"key1", "value1"},
  2674. {"key2", "value2"},
  2675. });
  2676. delete transaction;
  2677. }
  2678. TEST_P(WritePreparedTransactionTest, CommitAndSnapshotDuringCompaction) {
  2679. options.disable_auto_compactions = true;
  2680. ReOpen();
  2681. const Snapshot* snapshot = nullptr;
  2682. ASSERT_OK(db->Put(WriteOptions(), "key1", "value1"));
  2683. auto* txn = db->BeginTransaction(WriteOptions());
  2684. ASSERT_OK(txn->SetName("txn"));
  2685. ASSERT_OK(txn->Put("key1", "value2"));
  2686. ASSERT_OK(txn->Prepare());
  2687. auto callback = [&](void*) {
  2688. // Snapshot is taken after compaction start. It should be taken into
  2689. // consideration for whether to compact out value1.
  2690. snapshot = db->GetSnapshot();
  2691. ASSERT_OK(txn->Commit());
  2692. delete txn;
  2693. };
  2694. SyncPoint::GetInstance()->SetCallBack("CompactionIterator:AfterInit",
  2695. callback);
  2696. SyncPoint::GetInstance()->EnableProcessing();
  2697. ASSERT_OK(db->Flush(FlushOptions()));
  2698. ASSERT_NE(nullptr, snapshot);
  2699. VerifyKeys({{"key1", "value2"}});
  2700. VerifyKeys({{"key1", "value1"}}, snapshot);
  2701. db->ReleaseSnapshot(snapshot);
  2702. }
  2703. TEST_P(WritePreparedTransactionTest, Iterate) {
  2704. auto verify_state = [](Iterator* iter, const std::string& key,
  2705. const std::string& value) {
  2706. ASSERT_TRUE(iter->Valid());
  2707. ASSERT_OK(iter->status());
  2708. ASSERT_EQ(key, iter->key().ToString());
  2709. ASSERT_EQ(value, iter->value().ToString());
  2710. };
  2711. auto verify_iter = [&](const std::string& expected_val) {
  2712. // Get iterator from a concurrent transaction and make sure it has the
  2713. // same view as an iterator from the DB.
  2714. auto* txn = db->BeginTransaction(WriteOptions());
  2715. for (int i = 0; i < 2; i++) {
  2716. Iterator* iter = (i == 0)
  2717. ? db->NewIterator(ReadOptions())
  2718. : txn->GetIterator(ReadOptions());
  2719. // Seek
  2720. iter->Seek("foo");
  2721. verify_state(iter, "foo", expected_val);
  2722. // Next
  2723. iter->Seek("a");
  2724. verify_state(iter, "a", "va");
  2725. iter->Next();
  2726. verify_state(iter, "foo", expected_val);
  2727. // SeekForPrev
  2728. iter->SeekForPrev("y");
  2729. verify_state(iter, "foo", expected_val);
  2730. // Prev
  2731. iter->SeekForPrev("z");
  2732. verify_state(iter, "z", "vz");
  2733. iter->Prev();
  2734. verify_state(iter, "foo", expected_val);
  2735. delete iter;
  2736. }
  2737. delete txn;
  2738. };
  2739. ASSERT_OK(db->Put(WriteOptions(), "foo", "v1"));
  2740. auto* transaction = db->BeginTransaction(WriteOptions());
  2741. ASSERT_OK(transaction->SetName("txn"));
  2742. ASSERT_OK(transaction->Put("foo", "v2"));
  2743. ASSERT_OK(transaction->Prepare());
  2744. VerifyKeys({{"foo", "v1"}});
  2745. // dummy keys
  2746. ASSERT_OK(db->Put(WriteOptions(), "a", "va"));
  2747. ASSERT_OK(db->Put(WriteOptions(), "z", "vz"));
  2748. verify_iter("v1");
  2749. ASSERT_OK(transaction->Commit());
  2750. VerifyKeys({{"foo", "v2"}});
  2751. verify_iter("v2");
  2752. delete transaction;
  2753. }
  2754. TEST_P(WritePreparedTransactionTest, IteratorRefreshNotSupported) {
  2755. Iterator* iter = db->NewIterator(ReadOptions());
  2756. ASSERT_TRUE(iter->Refresh().IsNotSupported());
  2757. delete iter;
  2758. }
  2759. // Committing an delayed prepared has two non-atomic steps: update commit cache,
  2760. // remove seq from delayed_prepared_. The read in IsInSnapshot also involves two
  2761. // non-atomic steps of checking these two data structures. This test breaks each
  2762. // in the middle to ensure correctness in spite of non-atomic execution.
  2763. // Note: This test is limitted to the case where snapshot is larger than the
  2764. // max_evicted_seq_.
  2765. TEST_P(WritePreparedTransactionTest, NonAtomicCommitOfDelayedPrepared) {
  2766. const size_t snapshot_cache_bits = 7; // same as default
  2767. const size_t commit_cache_bits = 3; // 8 entries
  2768. for (auto split_read : {true, false}) {
  2769. std::vector<bool> split_options = {false};
  2770. if (split_read) {
  2771. // Also test for break before mutex
  2772. split_options.push_back(true);
  2773. }
  2774. for (auto split_before_mutex : split_options) {
  2775. UpdateTransactionDBOptions(snapshot_cache_bits, commit_cache_bits);
  2776. ReOpen();
  2777. WritePreparedTxnDB* wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  2778. DBImpl* db_impl = reinterpret_cast<DBImpl*>(db->GetRootDB());
  2779. // Fill up the commit cache
  2780. std::string init_value("value1");
  2781. for (int i = 0; i < 10; i++) {
  2782. db->Put(WriteOptions(), Slice("key1"), Slice(init_value));
  2783. }
  2784. // Prepare a transaction but do not commit it
  2785. Transaction* txn =
  2786. db->BeginTransaction(WriteOptions(), TransactionOptions());
  2787. ASSERT_OK(txn->SetName("xid"));
  2788. ASSERT_OK(txn->Put(Slice("key1"), Slice("value2")));
  2789. ASSERT_OK(txn->Prepare());
  2790. // Commit a bunch of entries to advance max evicted seq and make the
  2791. // prepared a delayed prepared
  2792. for (int i = 0; i < 10; i++) {
  2793. db->Put(WriteOptions(), Slice("key3"), Slice("value3"));
  2794. }
  2795. // The snapshot should not see the delayed prepared entry
  2796. auto snap = db->GetSnapshot();
  2797. if (split_read) {
  2798. if (split_before_mutex) {
  2799. // split before acquiring prepare_mutex_
  2800. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
  2801. {{"WritePreparedTxnDB::IsInSnapshot:prepared_mutex_:pause",
  2802. "AtomicCommitOfDelayedPrepared:Commit:before"},
  2803. {"AtomicCommitOfDelayedPrepared:Commit:after",
  2804. "WritePreparedTxnDB::IsInSnapshot:prepared_mutex_:resume"}});
  2805. } else {
  2806. // split right after reading from the commit cache
  2807. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
  2808. {{"WritePreparedTxnDB::IsInSnapshot:GetCommitEntry:pause",
  2809. "AtomicCommitOfDelayedPrepared:Commit:before"},
  2810. {"AtomicCommitOfDelayedPrepared:Commit:after",
  2811. "WritePreparedTxnDB::IsInSnapshot:GetCommitEntry:resume"}});
  2812. }
  2813. } else { // split commit
  2814. // split right before removing from delayed_prepared_
  2815. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
  2816. {{"WritePreparedTxnDB::RemovePrepared:pause",
  2817. "AtomicCommitOfDelayedPrepared:Read:before"},
  2818. {"AtomicCommitOfDelayedPrepared:Read:after",
  2819. "WritePreparedTxnDB::RemovePrepared:resume"}});
  2820. }
  2821. SyncPoint::GetInstance()->EnableProcessing();
  2822. ROCKSDB_NAMESPACE::port::Thread commit_thread([&]() {
  2823. TEST_SYNC_POINT("AtomicCommitOfDelayedPrepared:Commit:before");
  2824. ASSERT_OK(txn->Commit());
  2825. if (split_before_mutex) {
  2826. // Do bunch of inserts to evict the commit entry from the cache. This
  2827. // would prevent the 2nd look into commit cache under prepare_mutex_
  2828. // to see the commit entry.
  2829. auto seq = db_impl->TEST_GetLastVisibleSequence();
  2830. size_t tries = 0;
  2831. while (wp_db->max_evicted_seq_ < seq && tries < 50) {
  2832. db->Put(WriteOptions(), Slice("key3"), Slice("value3"));
  2833. tries++;
  2834. };
  2835. ASSERT_LT(tries, 50);
  2836. }
  2837. TEST_SYNC_POINT("AtomicCommitOfDelayedPrepared:Commit:after");
  2838. delete txn;
  2839. });
  2840. ROCKSDB_NAMESPACE::port::Thread read_thread([&]() {
  2841. TEST_SYNC_POINT("AtomicCommitOfDelayedPrepared:Read:before");
  2842. ReadOptions roptions;
  2843. roptions.snapshot = snap;
  2844. PinnableSlice value;
  2845. auto s = db->Get(roptions, db->DefaultColumnFamily(), "key1", &value);
  2846. ASSERT_OK(s);
  2847. // It should not see the commit of delayed prepared
  2848. ASSERT_TRUE(value == init_value);
  2849. TEST_SYNC_POINT("AtomicCommitOfDelayedPrepared:Read:after");
  2850. db->ReleaseSnapshot(snap);
  2851. });
  2852. read_thread.join();
  2853. commit_thread.join();
  2854. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  2855. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();
  2856. } // for split_before_mutex
  2857. } // for split_read
  2858. }
  2859. // When max evicted seq advances a prepared seq, it involves two updates: i)
  2860. // adding prepared seq to delayed_prepared_, ii) updating max_evicted_seq_.
  2861. // ::IsInSnapshot also reads these two values in a non-atomic way. This test
  2862. // ensures correctness if the update occurs after ::IsInSnapshot reads
  2863. // delayed_prepared_empty_ and before it reads max_evicted_seq_.
  2864. // Note: this test focuses on read snapshot larger than max_evicted_seq_.
  2865. TEST_P(WritePreparedTransactionTest, NonAtomicUpdateOfDelayedPrepared) {
  2866. const size_t snapshot_cache_bits = 7; // same as default
  2867. const size_t commit_cache_bits = 3; // 8 entries
  2868. UpdateTransactionDBOptions(snapshot_cache_bits, commit_cache_bits);
  2869. ReOpen();
  2870. WritePreparedTxnDB* wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  2871. // Fill up the commit cache
  2872. std::string init_value("value1");
  2873. for (int i = 0; i < 10; i++) {
  2874. db->Put(WriteOptions(), Slice("key1"), Slice(init_value));
  2875. }
  2876. // Prepare a transaction but do not commit it
  2877. Transaction* txn = db->BeginTransaction(WriteOptions(), TransactionOptions());
  2878. ASSERT_OK(txn->SetName("xid"));
  2879. ASSERT_OK(txn->Put(Slice("key1"), Slice("value2")));
  2880. ASSERT_OK(txn->Prepare());
  2881. // Create a gap between prepare seq and snapshot seq
  2882. db->Put(WriteOptions(), Slice("key3"), Slice("value3"));
  2883. db->Put(WriteOptions(), Slice("key3"), Slice("value3"));
  2884. // The snapshot should not see the delayed prepared entry
  2885. auto snap = db->GetSnapshot();
  2886. ASSERT_LT(txn->GetId(), snap->GetSequenceNumber());
  2887. // split right after reading delayed_prepared_empty_
  2888. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
  2889. {{"WritePreparedTxnDB::IsInSnapshot:delayed_prepared_empty_:pause",
  2890. "AtomicUpdateOfDelayedPrepared:before"},
  2891. {"AtomicUpdateOfDelayedPrepared:after",
  2892. "WritePreparedTxnDB::IsInSnapshot:delayed_prepared_empty_:resume"}});
  2893. SyncPoint::GetInstance()->EnableProcessing();
  2894. ROCKSDB_NAMESPACE::port::Thread commit_thread([&]() {
  2895. TEST_SYNC_POINT("AtomicUpdateOfDelayedPrepared:before");
  2896. // Commit a bunch of entries to advance max evicted seq and make the
  2897. // prepared a delayed prepared
  2898. size_t tries = 0;
  2899. while (wp_db->max_evicted_seq_ < txn->GetId() && tries < 50) {
  2900. db->Put(WriteOptions(), Slice("key3"), Slice("value3"));
  2901. tries++;
  2902. };
  2903. ASSERT_LT(tries, 50);
  2904. // This is the case on which the test focuses
  2905. ASSERT_LT(wp_db->max_evicted_seq_, snap->GetSequenceNumber());
  2906. TEST_SYNC_POINT("AtomicUpdateOfDelayedPrepared:after");
  2907. });
  2908. ROCKSDB_NAMESPACE::port::Thread read_thread([&]() {
  2909. ReadOptions roptions;
  2910. roptions.snapshot = snap;
  2911. PinnableSlice value;
  2912. auto s = db->Get(roptions, db->DefaultColumnFamily(), "key1", &value);
  2913. ASSERT_OK(s);
  2914. // It should not see the uncommitted value of delayed prepared
  2915. ASSERT_TRUE(value == init_value);
  2916. db->ReleaseSnapshot(snap);
  2917. });
  2918. read_thread.join();
  2919. commit_thread.join();
  2920. ASSERT_OK(txn->Commit());
  2921. delete txn;
  2922. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  2923. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();
  2924. }
  2925. // Eviction from commit cache and update of max evicted seq are two non-atomic
  2926. // steps. Similarly the read of max_evicted_seq_ in ::IsInSnapshot and reading
  2927. // from commit cache are two non-atomic steps. This tests if the update occurs
  2928. // after reading max_evicted_seq_ and before reading the commit cache.
  2929. // Note: the test focuses on snapshot larger than max_evicted_seq_
  2930. TEST_P(WritePreparedTransactionTest, NonAtomicUpdateOfMaxEvictedSeq) {
  2931. const size_t snapshot_cache_bits = 7; // same as default
  2932. const size_t commit_cache_bits = 3; // 8 entries
  2933. UpdateTransactionDBOptions(snapshot_cache_bits, commit_cache_bits);
  2934. ReOpen();
  2935. WritePreparedTxnDB* wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  2936. // Fill up the commit cache
  2937. std::string init_value("value1");
  2938. std::string last_value("value_final");
  2939. for (int i = 0; i < 10; i++) {
  2940. db->Put(WriteOptions(), Slice("key1"), Slice(init_value));
  2941. }
  2942. // Do an uncommitted write to prevent min_uncommitted optimization
  2943. Transaction* txn1 =
  2944. db->BeginTransaction(WriteOptions(), TransactionOptions());
  2945. ASSERT_OK(txn1->SetName("xid1"));
  2946. ASSERT_OK(txn1->Put(Slice("key0"), last_value));
  2947. ASSERT_OK(txn1->Prepare());
  2948. // Do a write with prepare to get the prepare seq
  2949. Transaction* txn = db->BeginTransaction(WriteOptions(), TransactionOptions());
  2950. ASSERT_OK(txn->SetName("xid"));
  2951. ASSERT_OK(txn->Put(Slice("key1"), last_value));
  2952. ASSERT_OK(txn->Prepare());
  2953. ASSERT_OK(txn->Commit());
  2954. // Create a gap between commit entry and snapshot seq
  2955. db->Put(WriteOptions(), Slice("key3"), Slice("value3"));
  2956. db->Put(WriteOptions(), Slice("key3"), Slice("value3"));
  2957. // The snapshot should see the last commit
  2958. auto snap = db->GetSnapshot();
  2959. ASSERT_LE(txn->GetId(), snap->GetSequenceNumber());
  2960. // split right after reading max_evicted_seq_
  2961. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
  2962. {{"WritePreparedTxnDB::IsInSnapshot:max_evicted_seq_:pause",
  2963. "NonAtomicUpdateOfMaxEvictedSeq:before"},
  2964. {"NonAtomicUpdateOfMaxEvictedSeq:after",
  2965. "WritePreparedTxnDB::IsInSnapshot:max_evicted_seq_:resume"}});
  2966. SyncPoint::GetInstance()->EnableProcessing();
  2967. ROCKSDB_NAMESPACE::port::Thread commit_thread([&]() {
  2968. TEST_SYNC_POINT("NonAtomicUpdateOfMaxEvictedSeq:before");
  2969. // Commit a bunch of entries to advance max evicted seq beyond txn->GetId()
  2970. size_t tries = 0;
  2971. while (wp_db->max_evicted_seq_ < txn->GetId() && tries < 50) {
  2972. db->Put(WriteOptions(), Slice("key3"), Slice("value3"));
  2973. tries++;
  2974. };
  2975. ASSERT_LT(tries, 50);
  2976. // This is the case on which the test focuses
  2977. ASSERT_LT(wp_db->max_evicted_seq_, snap->GetSequenceNumber());
  2978. TEST_SYNC_POINT("NonAtomicUpdateOfMaxEvictedSeq:after");
  2979. });
  2980. ROCKSDB_NAMESPACE::port::Thread read_thread([&]() {
  2981. ReadOptions roptions;
  2982. roptions.snapshot = snap;
  2983. PinnableSlice value;
  2984. auto s = db->Get(roptions, db->DefaultColumnFamily(), "key1", &value);
  2985. ASSERT_OK(s);
  2986. // It should see the committed value of the evicted entry
  2987. ASSERT_TRUE(value == last_value);
  2988. db->ReleaseSnapshot(snap);
  2989. });
  2990. read_thread.join();
  2991. commit_thread.join();
  2992. delete txn;
  2993. txn1->Commit();
  2994. delete txn1;
  2995. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  2996. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();
  2997. }
  2998. // Test when we add a prepared seq when the max_evicted_seq_ already goes beyond
  2999. // that. The test focuses on a race condition between AddPrepared and
  3000. // AdvanceMaxEvictedSeq functions.
  3001. TEST_P(WritePreparedTransactionTest, AddPreparedBeforeMax) {
  3002. if (!options.two_write_queues) {
  3003. // This test is only for two write queues
  3004. return;
  3005. }
  3006. const size_t snapshot_cache_bits = 7; // same as default
  3007. // 1 entry to advance max after the 2nd commit
  3008. const size_t commit_cache_bits = 0;
  3009. UpdateTransactionDBOptions(snapshot_cache_bits, commit_cache_bits);
  3010. ReOpen();
  3011. WritePreparedTxnDB* wp_db = dynamic_cast<WritePreparedTxnDB*>(db);
  3012. std::string some_value("value_some");
  3013. std::string uncommitted_value("value_uncommitted");
  3014. // Prepare two uncommitted transactions
  3015. Transaction* txn1 =
  3016. db->BeginTransaction(WriteOptions(), TransactionOptions());
  3017. ASSERT_OK(txn1->SetName("xid1"));
  3018. ASSERT_OK(txn1->Put(Slice("key1"), some_value));
  3019. ASSERT_OK(txn1->Prepare());
  3020. Transaction* txn2 =
  3021. db->BeginTransaction(WriteOptions(), TransactionOptions());
  3022. ASSERT_OK(txn2->SetName("xid2"));
  3023. ASSERT_OK(txn2->Put(Slice("key2"), some_value));
  3024. ASSERT_OK(txn2->Prepare());
  3025. // Start the txn here so the other thread could get its id
  3026. Transaction* txn = db->BeginTransaction(WriteOptions(), TransactionOptions());
  3027. ASSERT_OK(txn->SetName("xid"));
  3028. ASSERT_OK(txn->Put(Slice("key0"), uncommitted_value));
  3029. port::Mutex txn_mutex_;
  3030. // t1) Insert prepared entry, t2) commit other entries to advance max
  3031. // evicted sec and finish checking the existing prepared entries, t1)
  3032. // AddPrepared, t2) update max_evicted_seq_
  3033. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency({
  3034. {"AddPreparedCallback::AddPrepared::begin:pause",
  3035. "AddPreparedBeforeMax::read_thread:start"},
  3036. {"AdvanceMaxEvictedSeq::update_max:pause",
  3037. "AddPreparedCallback::AddPrepared::begin:resume"},
  3038. {"AddPreparedCallback::AddPrepared::end",
  3039. "AdvanceMaxEvictedSeq::update_max:resume"},
  3040. });
  3041. SyncPoint::GetInstance()->EnableProcessing();
  3042. ROCKSDB_NAMESPACE::port::Thread write_thread([&]() {
  3043. txn_mutex_.Lock();
  3044. ASSERT_OK(txn->Prepare());
  3045. txn_mutex_.Unlock();
  3046. });
  3047. ROCKSDB_NAMESPACE::port::Thread read_thread([&]() {
  3048. TEST_SYNC_POINT("AddPreparedBeforeMax::read_thread:start");
  3049. // Publish seq number with a commit
  3050. ASSERT_OK(txn1->Commit());
  3051. // Since the commit cache size is one the 2nd commit evict the 1st one and
  3052. // invokes AdcanceMaxEvictedSeq
  3053. ASSERT_OK(txn2->Commit());
  3054. ReadOptions roptions;
  3055. PinnableSlice value;
  3056. // The snapshot should not see the uncommitted value from write_thread
  3057. auto snap = db->GetSnapshot();
  3058. ASSERT_LT(wp_db->max_evicted_seq_, snap->GetSequenceNumber());
  3059. // This is the scenario that we test for
  3060. txn_mutex_.Lock();
  3061. ASSERT_GT(wp_db->max_evicted_seq_, txn->GetId());
  3062. txn_mutex_.Unlock();
  3063. roptions.snapshot = snap;
  3064. auto s = db->Get(roptions, db->DefaultColumnFamily(), "key0", &value);
  3065. ASSERT_TRUE(s.IsNotFound());
  3066. db->ReleaseSnapshot(snap);
  3067. });
  3068. read_thread.join();
  3069. write_thread.join();
  3070. delete txn1;
  3071. delete txn2;
  3072. ASSERT_OK(txn->Commit());
  3073. delete txn;
  3074. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  3075. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();
  3076. }
  3077. // When an old prepared entry gets committed, there is a gap between the time
  3078. // that it is published and when it is cleaned up from old_prepared_. This test
  3079. // stresses such cases.
  3080. TEST_P(WritePreparedTransactionTest, CommitOfDelayedPrepared) {
  3081. const size_t snapshot_cache_bits = 7; // same as default
  3082. for (const size_t commit_cache_bits : {0, 2, 3}) {
  3083. for (const size_t sub_batch_cnt : {1, 2, 3}) {
  3084. UpdateTransactionDBOptions(snapshot_cache_bits, commit_cache_bits);
  3085. ReOpen();
  3086. std::atomic<const Snapshot*> snap = {nullptr};
  3087. std::atomic<SequenceNumber> exp_prepare = {0};
  3088. ROCKSDB_NAMESPACE::port::Thread callback_thread;
  3089. // Value is synchronized via snap
  3090. PinnableSlice value;
  3091. // Take a snapshot after publish and before RemovePrepared:Start
  3092. auto snap_callback = [&]() {
  3093. ASSERT_EQ(nullptr, snap.load());
  3094. snap.store(db->GetSnapshot());
  3095. ReadOptions roptions;
  3096. roptions.snapshot = snap.load();
  3097. auto s = db->Get(roptions, db->DefaultColumnFamily(), "key2", &value);
  3098. ASSERT_OK(s);
  3099. };
  3100. auto callback = [&](void* param) {
  3101. SequenceNumber prep_seq = *((SequenceNumber*)param);
  3102. if (prep_seq == exp_prepare.load()) { // only for write_thread
  3103. // We need to spawn a thread to avoid deadlock since getting a
  3104. // snpashot might end up calling AdvanceSeqByOne which needs joining
  3105. // the write queue.
  3106. callback_thread = ROCKSDB_NAMESPACE::port::Thread(snap_callback);
  3107. TEST_SYNC_POINT("callback:end");
  3108. }
  3109. };
  3110. // Wait for the first snapshot be taken in GetSnapshotInternal. Although
  3111. // it might be updated before GetSnapshotInternal finishes but this should
  3112. // cover most of the cases.
  3113. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency({
  3114. {"WritePreparedTxnDB::GetSnapshotInternal:first", "callback:end"},
  3115. });
  3116. SyncPoint::GetInstance()->SetCallBack("RemovePrepared:Start", callback);
  3117. SyncPoint::GetInstance()->EnableProcessing();
  3118. // Thread to cause frequent evictions
  3119. ROCKSDB_NAMESPACE::port::Thread eviction_thread([&]() {
  3120. // Too many txns might cause commit_seq - prepare_seq in another thread
  3121. // to go beyond DELTA_UPPERBOUND
  3122. for (int i = 0; i < 25 * (1 << commit_cache_bits); i++) {
  3123. db->Put(WriteOptions(), Slice("key1"), Slice("value1"));
  3124. }
  3125. });
  3126. ROCKSDB_NAMESPACE::port::Thread write_thread([&]() {
  3127. for (int i = 0; i < 25 * (1 << commit_cache_bits); i++) {
  3128. Transaction* txn =
  3129. db->BeginTransaction(WriteOptions(), TransactionOptions());
  3130. ASSERT_OK(txn->SetName("xid"));
  3131. std::string val_str = "value" + ToString(i);
  3132. for (size_t b = 0; b < sub_batch_cnt; b++) {
  3133. ASSERT_OK(txn->Put(Slice("key2"), val_str));
  3134. }
  3135. ASSERT_OK(txn->Prepare());
  3136. // Let an eviction to kick in
  3137. std::this_thread::yield();
  3138. exp_prepare.store(txn->GetId());
  3139. ASSERT_OK(txn->Commit());
  3140. delete txn;
  3141. // Wait for the snapshot taking that is triggered by
  3142. // RemovePrepared:Start callback
  3143. callback_thread.join();
  3144. // Read with the snapshot taken before delayed_prepared_ cleanup
  3145. ReadOptions roptions;
  3146. roptions.snapshot = snap.load();
  3147. ASSERT_NE(nullptr, roptions.snapshot);
  3148. PinnableSlice value2;
  3149. auto s =
  3150. db->Get(roptions, db->DefaultColumnFamily(), "key2", &value2);
  3151. ASSERT_OK(s);
  3152. // It should see its own write
  3153. ASSERT_TRUE(val_str == value2);
  3154. // The value read by snapshot should not change
  3155. ASSERT_STREQ(value2.ToString().c_str(), value.ToString().c_str());
  3156. db->ReleaseSnapshot(roptions.snapshot);
  3157. snap.store(nullptr);
  3158. }
  3159. });
  3160. write_thread.join();
  3161. eviction_thread.join();
  3162. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  3163. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();
  3164. }
  3165. }
  3166. }
  3167. // Test that updating the commit map will not affect the existing snapshots
  3168. TEST_P(WritePreparedTransactionTest, AtomicCommit) {
  3169. for (bool skip_prepare : {true, false}) {
  3170. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency({
  3171. {"WritePreparedTxnDB::AddCommitted:start",
  3172. "AtomicCommit::GetSnapshot:start"},
  3173. {"AtomicCommit::Get:end",
  3174. "WritePreparedTxnDB::AddCommitted:start:pause"},
  3175. {"WritePreparedTxnDB::AddCommitted:end", "AtomicCommit::Get2:start"},
  3176. {"AtomicCommit::Get2:end",
  3177. "WritePreparedTxnDB::AddCommitted:end:pause:"},
  3178. });
  3179. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  3180. ROCKSDB_NAMESPACE::port::Thread write_thread([&]() {
  3181. if (skip_prepare) {
  3182. db->Put(WriteOptions(), Slice("key"), Slice("value"));
  3183. } else {
  3184. Transaction* txn =
  3185. db->BeginTransaction(WriteOptions(), TransactionOptions());
  3186. ASSERT_OK(txn->SetName("xid"));
  3187. ASSERT_OK(txn->Put(Slice("key"), Slice("value")));
  3188. ASSERT_OK(txn->Prepare());
  3189. ASSERT_OK(txn->Commit());
  3190. delete txn;
  3191. }
  3192. });
  3193. ROCKSDB_NAMESPACE::port::Thread read_thread([&]() {
  3194. ReadOptions roptions;
  3195. TEST_SYNC_POINT("AtomicCommit::GetSnapshot:start");
  3196. roptions.snapshot = db->GetSnapshot();
  3197. PinnableSlice val;
  3198. auto s = db->Get(roptions, db->DefaultColumnFamily(), "key", &val);
  3199. TEST_SYNC_POINT("AtomicCommit::Get:end");
  3200. TEST_SYNC_POINT("AtomicCommit::Get2:start");
  3201. ASSERT_SAME(roptions, db, s, val, "key");
  3202. TEST_SYNC_POINT("AtomicCommit::Get2:end");
  3203. db->ReleaseSnapshot(roptions.snapshot);
  3204. });
  3205. read_thread.join();
  3206. write_thread.join();
  3207. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
  3208. }
  3209. }
  3210. // Test that we can change write policy from WriteCommitted to WritePrepared
  3211. // after a clean shutdown (which would empty the WAL)
  3212. TEST_P(WritePreparedTransactionTest, WP_WC_DBBackwardCompatibility) {
  3213. bool empty_wal = true;
  3214. CrossCompatibilityTest(WRITE_COMMITTED, WRITE_PREPARED, empty_wal);
  3215. }
  3216. // Test that we fail fast if WAL is not emptied between changing the write
  3217. // policy from WriteCommitted to WritePrepared
  3218. TEST_P(WritePreparedTransactionTest, WP_WC_WALBackwardIncompatibility) {
  3219. bool empty_wal = true;
  3220. CrossCompatibilityTest(WRITE_COMMITTED, WRITE_PREPARED, !empty_wal);
  3221. }
  3222. // Test that we can change write policy from WritePrepare back to WriteCommitted
  3223. // after a clean shutdown (which would empty the WAL)
  3224. TEST_P(WritePreparedTransactionTest, WC_WP_ForwardCompatibility) {
  3225. bool empty_wal = true;
  3226. CrossCompatibilityTest(WRITE_PREPARED, WRITE_COMMITTED, empty_wal);
  3227. }
  3228. // Test that we fail fast if WAL is not emptied between changing the write
  3229. // policy from WriteCommitted to WritePrepared
  3230. TEST_P(WritePreparedTransactionTest, WC_WP_WALForwardIncompatibility) {
  3231. bool empty_wal = true;
  3232. CrossCompatibilityTest(WRITE_PREPARED, WRITE_COMMITTED, !empty_wal);
  3233. }
  3234. } // namespace ROCKSDB_NAMESPACE
  3235. int main(int argc, char** argv) {
  3236. ::testing::InitGoogleTest(&argc, argv);
  3237. return RUN_ALL_TESTS();
  3238. }
  3239. #else
  3240. #include <stdio.h>
  3241. int main(int /*argc*/, char** /*argv*/) {
  3242. fprintf(stderr,
  3243. "SKIPPED as Transactions are not supported in ROCKSDB_LITE\n");
  3244. return 0;
  3245. }
  3246. #endif // ROCKSDB_LITE