compaction_service_test.cc 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. #include "db/db_test_util.h"
  6. #include "file/file_util.h"
  7. #include "port/stack_trace.h"
  8. #include "rocksdb/utilities/options_util.h"
  9. #include "table/unique_id_impl.h"
  10. #include "utilities/merge_operators/string_append/stringappend.h"
  11. namespace ROCKSDB_NAMESPACE {
  12. class MyTestCompactionService : public CompactionService {
  13. public:
  14. MyTestCompactionService(
  15. std::string db_path, Options& options,
  16. std::shared_ptr<Statistics>& statistics,
  17. std::vector<std::shared_ptr<EventListener>> listeners,
  18. std::vector<std::shared_ptr<TablePropertiesCollectorFactory>>
  19. table_properties_collector_factories)
  20. : db_path_(std::move(db_path)),
  21. statistics_(statistics),
  22. options_(options),
  23. start_info_("na", "na", "na", 0, "na", 0, Env::TOTAL,
  24. CompactionReason::kUnknown, false, false, false, -1, -1),
  25. wait_info_("na", "na", "na", 0, "na", 0, Env::TOTAL,
  26. CompactionReason::kUnknown, false, false, false, -1, -1),
  27. listeners_(std::move(listeners)),
  28. table_properties_collector_factories_(
  29. std::move(table_properties_collector_factories)) {}
  30. static const char* kClassName() { return "MyTestCompactionService"; }
  31. const char* Name() const override { return kClassName(); }
  32. CompactionServiceScheduleResponse Schedule(
  33. const CompactionServiceJobInfo& info,
  34. const std::string& compaction_service_input) override {
  35. InstrumentedMutexLock l(&mutex_);
  36. start_info_ = info;
  37. assert(info.db_name == db_path_);
  38. std::string unique_id = Env::Default()->GenerateUniqueId();
  39. jobs_.emplace(unique_id, compaction_service_input);
  40. infos_.emplace(unique_id, info);
  41. CompactionServiceScheduleResponse response(
  42. unique_id, is_override_start_status_
  43. ? override_start_status_
  44. : CompactionServiceJobStatus::kSuccess);
  45. return response;
  46. }
  47. CompactionServiceJobStatus Wait(const std::string& scheduled_job_id,
  48. std::string* result) override {
  49. std::string compaction_input;
  50. {
  51. InstrumentedMutexLock l(&mutex_);
  52. auto job_index = jobs_.find(scheduled_job_id);
  53. if (job_index == jobs_.end()) {
  54. return CompactionServiceJobStatus::kFailure;
  55. }
  56. compaction_input = std::move(job_index->second);
  57. jobs_.erase(job_index);
  58. auto info_index = infos_.find(scheduled_job_id);
  59. if (info_index == infos_.end()) {
  60. return CompactionServiceJobStatus::kFailure;
  61. }
  62. wait_info_ = std::move(info_index->second);
  63. infos_.erase(info_index);
  64. }
  65. if (is_override_wait_status_) {
  66. return override_wait_status_;
  67. }
  68. CompactionServiceOptionsOverride options_override = GetOptionsOverride();
  69. OpenAndCompactOptions options;
  70. options.canceled = &canceled_;
  71. Status s =
  72. DB::OpenAndCompact(options, db_path_, GetOutputPath(scheduled_job_id),
  73. compaction_input, result, options_override);
  74. {
  75. InstrumentedMutexLock l(&mutex_);
  76. if (is_override_wait_result_) {
  77. *result = override_wait_result_;
  78. }
  79. result_ = *result;
  80. }
  81. compaction_num_.fetch_add(1);
  82. if (s.ok()) {
  83. return CompactionServiceJobStatus::kSuccess;
  84. } else {
  85. return CompactionServiceJobStatus::kFailure;
  86. }
  87. }
  88. CompactionServiceOptionsOverride GetOptionsOverride() {
  89. CompactionServiceOptionsOverride options_override;
  90. options_override.env = options_.env;
  91. options_override.file_checksum_gen_factory =
  92. options_.file_checksum_gen_factory;
  93. options_override.comparator = options_.comparator;
  94. options_override.merge_operator = options_.merge_operator;
  95. options_override.compaction_filter = options_.compaction_filter;
  96. options_override.compaction_filter_factory =
  97. options_.compaction_filter_factory;
  98. options_override.prefix_extractor = options_.prefix_extractor;
  99. options_override.table_factory = options_.table_factory;
  100. options_override.sst_partitioner_factory = options_.sst_partitioner_factory;
  101. options_override.statistics = statistics_;
  102. options_override.info_log = options_.info_log;
  103. if (!listeners_.empty()) {
  104. options_override.listeners = listeners_;
  105. }
  106. if (!table_properties_collector_factories_.empty()) {
  107. options_override.table_properties_collector_factories =
  108. table_properties_collector_factories_;
  109. }
  110. return options_override;
  111. }
  112. void CancelAwaitingJobs() override { canceled_ = true; }
  113. void OnInstallation(const std::string& /*scheduled_job_id*/,
  114. CompactionServiceJobStatus status) override {
  115. final_updated_status_ = status;
  116. }
  117. int GetCompactionNum() { return compaction_num_.load(); }
  118. CompactionServiceJobInfo GetCompactionInfoForStart() { return start_info_; }
  119. CompactionServiceJobInfo GetCompactionInfoForWait() { return wait_info_; }
  120. void OverrideStartStatus(CompactionServiceJobStatus s) {
  121. is_override_start_status_ = true;
  122. override_start_status_ = s;
  123. }
  124. void OverrideWaitStatus(CompactionServiceJobStatus s) {
  125. is_override_wait_status_ = true;
  126. override_wait_status_ = s;
  127. }
  128. void OverrideWaitResult(std::string str) {
  129. is_override_wait_result_ = true;
  130. override_wait_result_ = std::move(str);
  131. }
  132. void ResetOverride() {
  133. is_override_wait_result_ = false;
  134. is_override_start_status_ = false;
  135. is_override_wait_status_ = false;
  136. }
  137. void SetCanceled(bool canceled) { canceled_ = canceled; }
  138. bool GetCanceled() { return canceled_; }
  139. void GetResult(CompactionServiceResult* deserialized) {
  140. CompactionServiceResult::Read(result_, deserialized).PermitUncheckedError();
  141. }
  142. CompactionServiceJobStatus GetFinalCompactionServiceJobStatus() {
  143. return final_updated_status_.load();
  144. }
  145. protected:
  146. InstrumentedMutex mutex_;
  147. const std::string db_path_;
  148. std::shared_ptr<Statistics> statistics_;
  149. std::map<std::string, std::string> jobs_;
  150. std::map<std::string, CompactionServiceJobInfo> infos_;
  151. std::string result_;
  152. std::string GetOutputPath(const std::string& scheduled_job_id) {
  153. return db_path_ + "/" + scheduled_job_id;
  154. }
  155. private:
  156. std::atomic_int compaction_num_{0};
  157. Options options_;
  158. CompactionServiceJobInfo start_info_;
  159. CompactionServiceJobInfo wait_info_;
  160. bool is_override_start_status_ = false;
  161. CompactionServiceJobStatus override_start_status_ =
  162. CompactionServiceJobStatus::kFailure;
  163. bool is_override_wait_status_ = false;
  164. CompactionServiceJobStatus override_wait_status_ =
  165. CompactionServiceJobStatus::kFailure;
  166. bool is_override_wait_result_ = false;
  167. std::string override_wait_result_;
  168. std::vector<std::shared_ptr<EventListener>> listeners_;
  169. std::vector<std::shared_ptr<TablePropertiesCollectorFactory>>
  170. table_properties_collector_factories_;
  171. std::atomic_bool canceled_{false};
  172. std::atomic<CompactionServiceJobStatus> final_updated_status_{
  173. CompactionServiceJobStatus::kUseLocal};
  174. };
  175. class CompactionServiceTest : public DBTestBase {
  176. public:
  177. explicit CompactionServiceTest()
  178. : DBTestBase("compaction_service_test", true) {}
  179. protected:
  180. void ReopenWithCompactionService(Options* options) {
  181. options->env = env_;
  182. primary_statistics_ = CreateDBStatistics();
  183. options->statistics = primary_statistics_;
  184. compactor_statistics_ = CreateDBStatistics();
  185. auto my_cs = std::make_shared<MyTestCompactionService>(
  186. dbname_, *options, compactor_statistics_, remote_listeners,
  187. remote_table_properties_collector_factories);
  188. compaction_service_ = my_cs;
  189. options->compaction_service = compaction_service_;
  190. DestroyAndReopen(*options);
  191. CreateAndReopenWithCF({"cf_1", "cf_2", "cf_3"}, *options);
  192. my_cs->SetCanceled(false);
  193. }
  194. Statistics* GetCompactorStatistics() { return compactor_statistics_.get(); }
  195. Statistics* GetPrimaryStatistics() { return primary_statistics_.get(); }
  196. MyTestCompactionService* GetCompactionService() {
  197. CompactionService* cs = compaction_service_.get();
  198. return static_cast_with_check<MyTestCompactionService>(cs);
  199. }
  200. void GenerateTestData(bool move_files_manually = false) {
  201. // Generate 20 files @ L2 Per CF
  202. for (int cf_id = 0; cf_id < static_cast<int>(handles_.size()); cf_id++) {
  203. for (int i = 0; i < 20; i++) {
  204. for (int j = 0; j < 10; j++) {
  205. int key_id = i * 10 + j;
  206. ASSERT_OK(Put(cf_id, Key(key_id), "value" + std::to_string(key_id)));
  207. }
  208. ASSERT_OK(Flush(cf_id));
  209. }
  210. if (move_files_manually) {
  211. MoveFilesToLevel(2, cf_id);
  212. }
  213. // Generate 10 files @ L1 overlap with all 20 files @ L2
  214. for (int i = 0; i < 10; i++) {
  215. for (int j = 0; j < 10; j++) {
  216. int key_id = i * 20 + j * 2;
  217. ASSERT_OK(
  218. Put(cf_id, Key(key_id), "value_new" + std::to_string(key_id)));
  219. }
  220. ASSERT_OK(Flush(cf_id));
  221. }
  222. if (move_files_manually) {
  223. MoveFilesToLevel(1, cf_id);
  224. ASSERT_EQ(FilesPerLevel(cf_id), "0,10,20");
  225. }
  226. }
  227. }
  228. void VerifyTestData() {
  229. for (int cf_id = 0; cf_id < static_cast<int>(handles_.size()); cf_id++) {
  230. for (int i = 0; i < 200; i++) {
  231. auto result = Get(cf_id, Key(i));
  232. if (i % 2) {
  233. ASSERT_EQ(result, "value" + std::to_string(i));
  234. } else {
  235. ASSERT_EQ(result, "value_new" + std::to_string(i));
  236. }
  237. }
  238. }
  239. }
  240. std::vector<std::shared_ptr<EventListener>> remote_listeners;
  241. std::vector<std::shared_ptr<TablePropertiesCollectorFactory>>
  242. remote_table_properties_collector_factories;
  243. private:
  244. std::shared_ptr<Statistics> compactor_statistics_;
  245. std::shared_ptr<Statistics> primary_statistics_;
  246. std::shared_ptr<CompactionService> compaction_service_;
  247. };
  248. TEST_F(CompactionServiceTest, BasicCompactions) {
  249. Options options = CurrentOptions();
  250. ReopenWithCompactionService(&options);
  251. Statistics* primary_statistics = GetPrimaryStatistics();
  252. Statistics* compactor_statistics = GetCompactorStatistics();
  253. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  254. "BlockBasedTable::PrefetchTail::TaiSizeNotRecorded",
  255. [&](void* /* arg */) {
  256. // Trigger assertion to verify precise tail prefetch size calculation
  257. assert(false);
  258. });
  259. SyncPoint::GetInstance()->EnableProcessing();
  260. GenerateTestData();
  261. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  262. SyncPoint::GetInstance()->DisableProcessing();
  263. VerifyTestData();
  264. auto my_cs = GetCompactionService();
  265. ASSERT_GE(my_cs->GetCompactionNum(), 1);
  266. ASSERT_EQ(CompactionServiceJobStatus::kSuccess,
  267. my_cs->GetFinalCompactionServiceJobStatus());
  268. // make sure the compaction statistics is only recorded on the remote side
  269. ASSERT_GE(compactor_statistics->getTickerCount(COMPACT_WRITE_BYTES), 1);
  270. ASSERT_GE(compactor_statistics->getTickerCount(COMPACT_READ_BYTES), 1);
  271. ASSERT_EQ(primary_statistics->getTickerCount(COMPACT_WRITE_BYTES), 0);
  272. // even with remote compaction, primary host still needs to read SST files to
  273. // `verify_table()`.
  274. ASSERT_GE(primary_statistics->getTickerCount(COMPACT_READ_BYTES), 1);
  275. // all the compaction write happens on the remote side
  276. ASSERT_EQ(primary_statistics->getTickerCount(REMOTE_COMPACT_WRITE_BYTES),
  277. compactor_statistics->getTickerCount(COMPACT_WRITE_BYTES));
  278. ASSERT_GE(primary_statistics->getTickerCount(REMOTE_COMPACT_READ_BYTES), 1);
  279. ASSERT_GT(primary_statistics->getTickerCount(COMPACT_READ_BYTES),
  280. primary_statistics->getTickerCount(REMOTE_COMPACT_READ_BYTES));
  281. // compactor is already the remote side, which doesn't have remote
  282. ASSERT_EQ(compactor_statistics->getTickerCount(REMOTE_COMPACT_READ_BYTES), 0);
  283. ASSERT_EQ(compactor_statistics->getTickerCount(REMOTE_COMPACT_WRITE_BYTES),
  284. 0);
  285. // Test failed compaction
  286. SyncPoint::GetInstance()->SetCallBack(
  287. "DBImplSecondary::CompactWithoutInstallation::End", [&](void* status) {
  288. // override job status
  289. auto s = static_cast<Status*>(status);
  290. *s = Status::Aborted("MyTestCompactionService failed to compact!");
  291. });
  292. SyncPoint::GetInstance()->EnableProcessing();
  293. Status s;
  294. for (int i = 0; i < 10; i++) {
  295. for (int j = 0; j < 10; j++) {
  296. int key_id = i * 20 + j * 2;
  297. s = Put(Key(key_id), "value_new" + std::to_string(key_id));
  298. if (s.IsAborted()) {
  299. break;
  300. }
  301. }
  302. if (s.IsAborted()) {
  303. break;
  304. }
  305. s = Flush();
  306. if (s.IsAborted()) {
  307. break;
  308. }
  309. s = dbfull()->TEST_WaitForCompact();
  310. if (s.IsAborted()) {
  311. break;
  312. }
  313. }
  314. ASSERT_TRUE(s.IsAborted());
  315. // Test re-open and successful unique id verification
  316. std::atomic_int verify_passed{0};
  317. SyncPoint::GetInstance()->SetCallBack(
  318. "BlockBasedTable::Open::PassedVerifyUniqueId", [&](void* arg) {
  319. // override job status
  320. auto id = static_cast<UniqueId64x2*>(arg);
  321. assert(*id != kNullUniqueId64x2);
  322. verify_passed++;
  323. });
  324. Close();
  325. my_cs->SetCanceled(false);
  326. ReopenWithColumnFamilies({kDefaultColumnFamilyName, "cf_1", "cf_2", "cf_3"},
  327. options);
  328. ASSERT_GT(verify_passed, 0);
  329. CompactionServiceResult result;
  330. my_cs->GetResult(&result);
  331. if (s.IsAborted()) {
  332. ASSERT_NOK(result.status);
  333. } else {
  334. ASSERT_OK(result.status);
  335. }
  336. ASSERT_GE(result.internal_stats.output_level_stats.micros, 1);
  337. ASSERT_GE(result.internal_stats.output_level_stats.cpu_micros, 1);
  338. ASSERT_EQ(20, result.internal_stats.output_level_stats.num_output_records);
  339. ASSERT_EQ(result.output_files.size(),
  340. result.internal_stats.output_level_stats.num_output_files);
  341. uint64_t total_size = 0;
  342. for (auto output_file : result.output_files) {
  343. std::string file_name = result.output_path + "/" + output_file.file_name;
  344. uint64_t file_size = 0;
  345. ASSERT_OK(options.env->GetFileSize(file_name, &file_size));
  346. ASSERT_GT(file_size, 0);
  347. total_size += file_size;
  348. }
  349. ASSERT_EQ(total_size, result.internal_stats.TotalBytesWritten());
  350. ASSERT_TRUE(result.stats.is_remote_compaction);
  351. ASSERT_TRUE(result.stats.is_manual_compaction);
  352. ASSERT_FALSE(result.stats.is_full_compaction);
  353. Close();
  354. SyncPoint::GetInstance()->DisableProcessing();
  355. }
  356. TEST_F(CompactionServiceTest, ManualCompaction) {
  357. Options options = CurrentOptions();
  358. options.disable_auto_compactions = true;
  359. ReopenWithCompactionService(&options);
  360. GenerateTestData();
  361. auto my_cs = GetCompactionService();
  362. std::string start_str = Key(15);
  363. std::string end_str = Key(45);
  364. Slice start(start_str);
  365. Slice end(end_str);
  366. uint64_t comp_num = my_cs->GetCompactionNum();
  367. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &start, &end));
  368. ASSERT_GE(my_cs->GetCompactionNum(), comp_num + 1);
  369. VerifyTestData();
  370. start_str = Key(120);
  371. start = start_str;
  372. comp_num = my_cs->GetCompactionNum();
  373. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &start, nullptr));
  374. ASSERT_GE(my_cs->GetCompactionNum(), comp_num + 1);
  375. VerifyTestData();
  376. end_str = Key(92);
  377. end = end_str;
  378. comp_num = my_cs->GetCompactionNum();
  379. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, &end));
  380. ASSERT_GE(my_cs->GetCompactionNum(), comp_num + 1);
  381. VerifyTestData();
  382. comp_num = my_cs->GetCompactionNum();
  383. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  384. ASSERT_GE(my_cs->GetCompactionNum(), comp_num + 1);
  385. VerifyTestData();
  386. CompactionServiceResult result;
  387. my_cs->GetResult(&result);
  388. ASSERT_OK(result.status);
  389. ASSERT_TRUE(result.stats.is_manual_compaction);
  390. ASSERT_TRUE(result.stats.is_remote_compaction);
  391. auto info = my_cs->GetCompactionInfoForStart();
  392. ASSERT_EQ(0, info.cf_id);
  393. ASSERT_EQ(kDefaultColumnFamilyName, info.cf_name);
  394. info = my_cs->GetCompactionInfoForWait();
  395. ASSERT_EQ(0, info.cf_id);
  396. ASSERT_EQ(kDefaultColumnFamilyName, info.cf_name);
  397. // Test non-default CF
  398. ASSERT_OK(
  399. db_->CompactRange(CompactRangeOptions(), handles_[1], nullptr, nullptr));
  400. my_cs->GetResult(&result);
  401. ASSERT_OK(result.status);
  402. ASSERT_TRUE(result.stats.is_manual_compaction);
  403. ASSERT_TRUE(result.stats.is_remote_compaction);
  404. info = my_cs->GetCompactionInfoForStart();
  405. ASSERT_EQ(handles_[1]->GetID(), info.cf_id);
  406. ASSERT_EQ(handles_[1]->GetName(), info.cf_name);
  407. info = my_cs->GetCompactionInfoForWait();
  408. ASSERT_EQ(handles_[1]->GetID(), info.cf_id);
  409. ASSERT_EQ(handles_[1]->GetName(), info.cf_name);
  410. }
  411. TEST_F(CompactionServiceTest, StandaloneDeleteRangeTombstoneOptimization) {
  412. Options options = CurrentOptions();
  413. size_t num_files_after_filtered = 0;
  414. SyncPoint::GetInstance()->SetCallBack(
  415. "VersionSet::MakeInputIterator:NewCompactionMergingIterator",
  416. [&](void* arg) {
  417. num_files_after_filtered = *static_cast<size_t*>(arg);
  418. });
  419. SyncPoint::GetInstance()->EnableProcessing();
  420. for (auto compaction_style : {CompactionStyle::kCompactionStyleLevel,
  421. CompactionStyle::kCompactionStyleUniversal}) {
  422. SCOPED_TRACE("Style: " + std::to_string(compaction_style));
  423. options.compaction_style = compaction_style;
  424. ReopenWithCompactionService(&options);
  425. num_files_after_filtered = 0;
  426. std::vector<std::string> files;
  427. {
  428. // Writes first version of data in range partitioned files.
  429. SstFileWriter sst_file_writer(EnvOptions(), options);
  430. std::string file1 = dbname_ + "file1.sst";
  431. ASSERT_OK(sst_file_writer.Open(file1));
  432. ASSERT_OK(sst_file_writer.Put("a", "a1"));
  433. ASSERT_OK(sst_file_writer.Put("b", "b1"));
  434. ExternalSstFileInfo file1_info;
  435. ASSERT_OK(sst_file_writer.Finish(&file1_info));
  436. files.push_back(std::move(file1));
  437. std::string file2 = dbname_ + "file2.sst";
  438. ASSERT_OK(sst_file_writer.Open(file2));
  439. ASSERT_OK(sst_file_writer.Put("x", "x1"));
  440. ASSERT_OK(sst_file_writer.Put("y", "y1"));
  441. ExternalSstFileInfo file2_info;
  442. ASSERT_OK(sst_file_writer.Finish(&file2_info));
  443. files.push_back(std::move(file2));
  444. }
  445. IngestExternalFileOptions ifo;
  446. ASSERT_OK(db_->IngestExternalFile(files, ifo));
  447. ASSERT_EQ(Get("a"), "a1");
  448. ASSERT_EQ(Get("b"), "b1");
  449. ASSERT_EQ(Get("x"), "x1");
  450. ASSERT_EQ(Get("y"), "y1");
  451. ASSERT_EQ(2, NumTableFilesAtLevel(6));
  452. auto my_cs = GetCompactionService();
  453. uint64_t comp_num = my_cs->GetCompactionNum();
  454. {
  455. // Atomically delete old version of data with one range delete file.
  456. // And a new batch of range partitioned files with new version of data.
  457. files.clear();
  458. SstFileWriter sst_file_writer(EnvOptions(), options);
  459. std::string file2 = dbname_ + "file2.sst";
  460. ASSERT_OK(sst_file_writer.Open(file2));
  461. ASSERT_OK(sst_file_writer.DeleteRange("a", "z"));
  462. ExternalSstFileInfo file2_info;
  463. ASSERT_OK(sst_file_writer.Finish(&file2_info));
  464. files.push_back(std::move(file2));
  465. std::string file3 = dbname_ + "file3.sst";
  466. ASSERT_OK(sst_file_writer.Open(file3));
  467. ASSERT_OK(sst_file_writer.Put("a", "a2"));
  468. ASSERT_OK(sst_file_writer.Put("b", "b2"));
  469. ExternalSstFileInfo file3_info;
  470. ASSERT_OK(sst_file_writer.Finish(&file3_info));
  471. files.push_back(std::move(file3));
  472. std::string file4 = dbname_ + "file4.sst";
  473. ASSERT_OK(sst_file_writer.Open(file4));
  474. ASSERT_OK(sst_file_writer.Put("x", "x2"));
  475. ASSERT_OK(sst_file_writer.Put("y", "y2"));
  476. ExternalSstFileInfo file4_info;
  477. ASSERT_OK(sst_file_writer.Finish(&file4_info));
  478. files.push_back(std::move(file4));
  479. }
  480. ASSERT_OK(db_->IngestExternalFile(files, ifo));
  481. ASSERT_OK(db_->WaitForCompact(WaitForCompactOptions()));
  482. ASSERT_GE(my_cs->GetCompactionNum(), comp_num + 1);
  483. CompactionServiceResult result;
  484. my_cs->GetResult(&result);
  485. ASSERT_OK(result.status);
  486. ASSERT_TRUE(result.stats.is_manual_compaction);
  487. ASSERT_TRUE(result.stats.is_remote_compaction);
  488. if (compaction_style == kCompactionStyleUniversal) {
  489. ASSERT_EQ(num_files_after_filtered, 1);
  490. } else {
  491. // Not filtered
  492. ASSERT_EQ(num_files_after_filtered, 3);
  493. }
  494. Close();
  495. }
  496. SyncPoint::GetInstance()->DisableProcessing();
  497. }
  498. TEST_F(CompactionServiceTest, CompactionOutputFileIOError) {
  499. Options options = CurrentOptions();
  500. options.disable_auto_compactions = true;
  501. ReopenWithCompactionService(&options);
  502. GenerateTestData();
  503. auto my_cs = GetCompactionService();
  504. SyncPoint::GetInstance()->SetCallBack(
  505. "CompactionJob::FinishCompactionOutputFile()::AfterFinish",
  506. [&](void* status) {
  507. // override status
  508. auto s = static_cast<Status*>(status);
  509. *s = Status::IOError("Injected IOError!");
  510. });
  511. SyncPoint::GetInstance()->EnableProcessing();
  512. std::string start_str = Key(15);
  513. std::string end_str = Key(45);
  514. Slice start(start_str);
  515. Slice end(end_str);
  516. uint64_t comp_num = my_cs->GetCompactionNum();
  517. ASSERT_NOK(db_->CompactRange(CompactRangeOptions(), &start, &end));
  518. ASSERT_GE(my_cs->GetCompactionNum(), comp_num + 1);
  519. CompactionServiceResult result;
  520. my_cs->GetResult(&result);
  521. ASSERT_NOK(result.status);
  522. ASSERT_TRUE(result.stats.is_manual_compaction);
  523. ASSERT_TRUE(result.stats.is_remote_compaction);
  524. }
  525. TEST_F(CompactionServiceTest, PreservedOptionsLocalCompaction) {
  526. Options options = CurrentOptions();
  527. options.level0_file_num_compaction_trigger = 2;
  528. options.disable_auto_compactions = true;
  529. DestroyAndReopen(options);
  530. Random rnd(301);
  531. for (auto i = 0; i < 2; ++i) {
  532. for (auto j = 0; j < 10; ++j) {
  533. ASSERT_OK(
  534. Put("foo" + std::to_string(i * 10 + j), rnd.RandomString(1024)));
  535. }
  536. ASSERT_OK(Flush());
  537. }
  538. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  539. "CompactionJob::ProcessKeyValueCompaction()::Processing", [&](void* arg) {
  540. auto compaction = static_cast<Compaction*>(arg);
  541. std::string options_file_name = OptionsFileName(
  542. dbname_,
  543. compaction->input_version()->version_set()->options_file_number());
  544. // Change option twice to make sure the very first OPTIONS file gets
  545. // purged
  546. ASSERT_OK(dbfull()->SetOptions(
  547. {{"level0_file_num_compaction_trigger", "4"}}));
  548. ASSERT_EQ(4, dbfull()->GetOptions().level0_file_num_compaction_trigger);
  549. ASSERT_OK(dbfull()->SetOptions(
  550. {{"level0_file_num_compaction_trigger", "6"}}));
  551. ASSERT_EQ(6, dbfull()->GetOptions().level0_file_num_compaction_trigger);
  552. dbfull()->TEST_DeleteObsoleteFiles();
  553. // For non-remote compactions, OPTIONS file can be deleted while
  554. // using option at the start of the compaction
  555. Status s = env_->FileExists(options_file_name);
  556. ASSERT_NOK(s);
  557. ASSERT_TRUE(s.IsNotFound());
  558. // Should be old value
  559. ASSERT_EQ(2, compaction->mutable_cf_options()
  560. .level0_file_num_compaction_trigger);
  561. ASSERT_TRUE(dbfull()->min_options_file_numbers_.empty());
  562. });
  563. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  564. Status s = dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr);
  565. ASSERT_TRUE(s.ok());
  566. }
  567. TEST_F(CompactionServiceTest, PreservedOptionsRemoteCompaction) {
  568. // For non-remote compaction do not preserve options file
  569. Options options = CurrentOptions();
  570. options.level0_file_num_compaction_trigger = 2;
  571. options.disable_auto_compactions = true;
  572. ReopenWithCompactionService(&options);
  573. GenerateTestData();
  574. auto my_cs = GetCompactionService();
  575. Random rnd(301);
  576. for (auto i = 0; i < 2; ++i) {
  577. for (auto j = 0; j < 10; ++j) {
  578. ASSERT_OK(
  579. Put("foo" + std::to_string(i * 10 + j), rnd.RandomString(1024)));
  580. }
  581. ASSERT_OK(Flush());
  582. }
  583. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
  584. {{"CompactionServiceTest::OptionsFileChanged",
  585. "DBImplSecondary::OpenAndCompact::BeforeLoadingOptions:1"}});
  586. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  587. "DBImplSecondary::OpenAndCompact::BeforeLoadingOptions:0",
  588. [&](void* arg) {
  589. auto options_file_number = static_cast<uint64_t*>(arg);
  590. // Change the option twice before the compaction run
  591. ASSERT_OK(dbfull()->SetOptions(
  592. {{"level0_file_num_compaction_trigger", "4"}}));
  593. ASSERT_EQ(4, dbfull()->GetOptions().level0_file_num_compaction_trigger);
  594. ASSERT_TRUE(dbfull()->versions_->options_file_number() >
  595. *options_file_number);
  596. // Change the option twice before the compaction run
  597. ASSERT_OK(dbfull()->SetOptions(
  598. {{"level0_file_num_compaction_trigger", "5"}}));
  599. ASSERT_EQ(5, dbfull()->GetOptions().level0_file_num_compaction_trigger);
  600. ASSERT_TRUE(dbfull()->versions_->options_file_number() >
  601. *options_file_number);
  602. TEST_SYNC_POINT("CompactionServiceTest::OptionsFileChanged");
  603. });
  604. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  605. "CompactionServiceJob::ProcessKeyValueCompactionWithCompactionService",
  606. [&](void* arg) {
  607. auto input = static_cast<CompactionServiceInput*>(arg);
  608. std::string options_file_name =
  609. OptionsFileName(dbname_, input->options_file_number);
  610. ASSERT_OK(env_->FileExists(options_file_name));
  611. ASSERT_FALSE(dbfull()->min_options_file_numbers_.empty());
  612. ASSERT_EQ(dbfull()->min_options_file_numbers_.front(),
  613. input->options_file_number);
  614. DBOptions db_options;
  615. ConfigOptions config_options;
  616. std::vector<ColumnFamilyDescriptor> all_column_families;
  617. config_options.env = env_;
  618. ASSERT_OK(LoadOptionsFromFile(config_options, options_file_name,
  619. &db_options, &all_column_families));
  620. bool has_cf = false;
  621. for (auto& cf : all_column_families) {
  622. if (cf.name == input->cf_name) {
  623. // Should be old value
  624. ASSERT_EQ(2, cf.options.level0_file_num_compaction_trigger);
  625. has_cf = true;
  626. }
  627. }
  628. ASSERT_TRUE(has_cf);
  629. });
  630. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  631. "CompactionJob::ProcessKeyValueCompaction()::Processing", [&](void* arg) {
  632. auto compaction = static_cast<Compaction*>(arg);
  633. ASSERT_EQ(2, compaction->mutable_cf_options()
  634. .level0_file_num_compaction_trigger);
  635. });
  636. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
  637. Status s = dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr);
  638. ASSERT_TRUE(s.ok());
  639. CompactionServiceResult result;
  640. my_cs->GetResult(&result);
  641. ASSERT_OK(result.status);
  642. ASSERT_TRUE(result.stats.is_manual_compaction);
  643. ASSERT_TRUE(result.stats.is_remote_compaction);
  644. }
  645. class EventVerifier : public EventListener {
  646. public:
  647. explicit EventVerifier(uint64_t expected_num_input_records,
  648. size_t expected_num_input_files,
  649. uint64_t expected_num_output_records,
  650. size_t expected_num_output_files,
  651. const std::string& expected_smallest_output_key_prefix,
  652. const std::string& expected_largest_output_key_prefix,
  653. bool expected_is_remote_compaction_on_begin,
  654. bool expected_is_remote_compaction_on_complete)
  655. : expected_num_input_records_(expected_num_input_records),
  656. expected_num_input_files_(expected_num_input_files),
  657. expected_num_output_records_(expected_num_output_records),
  658. expected_num_output_files_(expected_num_output_files),
  659. expected_smallest_output_key_prefix_(
  660. expected_smallest_output_key_prefix),
  661. expected_largest_output_key_prefix_(expected_largest_output_key_prefix),
  662. expected_is_remote_compaction_on_begin_(
  663. expected_is_remote_compaction_on_begin),
  664. expected_is_remote_compaction_on_complete_(
  665. expected_is_remote_compaction_on_complete) {}
  666. void OnCompactionBegin(DB* /*db*/, const CompactionJobInfo& ci) override {
  667. ASSERT_EQ(expected_num_input_files_, ci.input_files.size());
  668. ASSERT_EQ(expected_num_input_files_, ci.input_file_infos.size());
  669. ASSERT_EQ(expected_is_remote_compaction_on_begin_,
  670. ci.stats.is_remote_compaction);
  671. ASSERT_TRUE(ci.stats.is_manual_compaction);
  672. ASSERT_FALSE(ci.stats.is_full_compaction);
  673. }
  674. void OnCompactionCompleted(DB* /*db*/, const CompactionJobInfo& ci) override {
  675. ASSERT_GT(ci.stats.elapsed_micros, 0);
  676. ASSERT_GT(ci.stats.cpu_micros, 0);
  677. ASSERT_EQ(expected_num_input_records_, ci.stats.num_input_records);
  678. ASSERT_EQ(expected_num_input_files_, ci.stats.num_input_files);
  679. ASSERT_EQ(expected_num_output_records_, ci.stats.num_output_records);
  680. ASSERT_EQ(expected_num_output_files_, ci.stats.num_output_files);
  681. ASSERT_EQ(expected_smallest_output_key_prefix_,
  682. ci.stats.smallest_output_key_prefix);
  683. ASSERT_EQ(expected_largest_output_key_prefix_,
  684. ci.stats.largest_output_key_prefix);
  685. ASSERT_GT(ci.stats.total_input_bytes, 0);
  686. ASSERT_GT(ci.stats.total_output_bytes, 0);
  687. ASSERT_EQ(ci.stats.num_input_records,
  688. ci.stats.num_output_records + ci.stats.num_records_replaced);
  689. ASSERT_EQ(expected_is_remote_compaction_on_complete_,
  690. ci.stats.is_remote_compaction);
  691. ASSERT_TRUE(ci.stats.is_manual_compaction);
  692. ASSERT_FALSE(ci.stats.is_full_compaction);
  693. }
  694. private:
  695. uint64_t expected_num_input_records_;
  696. size_t expected_num_input_files_;
  697. uint64_t expected_num_output_records_;
  698. size_t expected_num_output_files_;
  699. std::string expected_smallest_output_key_prefix_;
  700. std::string expected_largest_output_key_prefix_;
  701. bool expected_is_remote_compaction_on_begin_;
  702. bool expected_is_remote_compaction_on_complete_;
  703. };
  704. TEST_F(CompactionServiceTest, VerifyStats) {
  705. Options options = CurrentOptions();
  706. options.disable_auto_compactions = true;
  707. auto event_verifier = std::make_shared<EventVerifier>(
  708. 30 /* expected_num_input_records */, 3 /* expected_num_input_files */,
  709. 20 /* expected_num_output_records */, 1 /* expected_num_output_files */,
  710. "key00000" /* expected_smallest_output_key_prefix */,
  711. "key00001" /* expected_largest_output_key_prefix */,
  712. true /* expected_is_remote_compaction_on_begin */,
  713. true /* expected_is_remote_compaction_on_complete */);
  714. options.listeners.push_back(event_verifier);
  715. ReopenWithCompactionService(&options);
  716. GenerateTestData();
  717. auto my_cs = GetCompactionService();
  718. std::string start_str = Key(0);
  719. std::string end_str = Key(1);
  720. Slice start(start_str);
  721. Slice end(end_str);
  722. uint64_t comp_num = my_cs->GetCompactionNum();
  723. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &start, &end));
  724. ASSERT_GE(my_cs->GetCompactionNum(), comp_num + 1);
  725. VerifyTestData();
  726. CompactionServiceResult result;
  727. my_cs->GetResult(&result);
  728. ASSERT_OK(result.status);
  729. ASSERT_TRUE(result.stats.is_manual_compaction);
  730. ASSERT_TRUE(result.stats.is_remote_compaction);
  731. }
  732. TEST_F(CompactionServiceTest, VerifyStatsLocalFallback) {
  733. Options options = CurrentOptions();
  734. options.disable_auto_compactions = true;
  735. auto event_verifier = std::make_shared<EventVerifier>(
  736. 30 /* expected_num_input_records */, 3 /* expected_num_input_files */,
  737. 20 /* expected_num_output_records */, 1 /* expected_num_output_files */,
  738. "key00000" /* expected_smallest_output_key_prefix */,
  739. "key00001" /* expected_largest_output_key_prefix */,
  740. true /* expected_is_remote_compaction_on_begin */,
  741. false /* expected_is_remote_compaction_on_complete */);
  742. options.listeners.push_back(event_verifier);
  743. ReopenWithCompactionService(&options);
  744. GenerateTestData();
  745. auto my_cs = GetCompactionService();
  746. my_cs->OverrideStartStatus(CompactionServiceJobStatus::kUseLocal);
  747. std::string start_str = Key(0);
  748. std::string end_str = Key(1);
  749. Slice start(start_str);
  750. Slice end(end_str);
  751. uint64_t comp_num = my_cs->GetCompactionNum();
  752. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &start, &end));
  753. // Remote Compaction did not happen
  754. ASSERT_EQ(my_cs->GetCompactionNum(), comp_num);
  755. VerifyTestData();
  756. }
  757. TEST_F(CompactionServiceTest, VerifyInputRecordCount) {
  758. Options options = CurrentOptions();
  759. options.disable_auto_compactions = true;
  760. ReopenWithCompactionService(&options);
  761. GenerateTestData();
  762. auto my_cs = GetCompactionService();
  763. std::string start_str = Key(15);
  764. std::string end_str = Key(45);
  765. Slice start(start_str);
  766. Slice end(end_str);
  767. uint64_t comp_num = my_cs->GetCompactionNum();
  768. // Only iterator through 10 keys and force compaction to finish.
  769. int num_iter = 0;
  770. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  771. "CompactionJob::ProcessKeyValueCompaction()::stop", [&](void* stop_ptr) {
  772. num_iter++;
  773. if (num_iter == 10) {
  774. *(bool*)stop_ptr = true;
  775. }
  776. });
  777. SyncPoint::GetInstance()->EnableProcessing();
  778. // CompactRange() should fail
  779. Status s = db_->CompactRange(CompactRangeOptions(), &start, &end);
  780. ASSERT_NOK(s);
  781. ASSERT_TRUE(s.IsCorruption());
  782. const char* expected_message =
  783. "Compaction number of input keys does not match number of keys "
  784. "processed.";
  785. ASSERT_TRUE(std::strstr(s.getState(), expected_message));
  786. ASSERT_GE(my_cs->GetCompactionNum(), comp_num + 1);
  787. SyncPoint::GetInstance()->DisableProcessing();
  788. SyncPoint::GetInstance()->ClearAllCallBacks();
  789. }
  790. TEST_F(CompactionServiceTest, EmptyResult) {
  791. Options options = CurrentOptions();
  792. options.disable_auto_compactions = true;
  793. ReopenWithCompactionService(&options);
  794. GenerateTestData();
  795. auto my_cs = GetCompactionService();
  796. uint64_t comp_num = my_cs->GetCompactionNum();
  797. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  798. ASSERT_GE(my_cs->GetCompactionNum(), comp_num + 1);
  799. // Delete range to cover entire range
  800. ASSERT_OK(db_->DeleteRange(WriteOptions(), "key", "keyz"));
  801. ASSERT_OK(Flush());
  802. // In this unit test, both remote compaction and primary db instance are
  803. // running in the same process, so NewFileNumber will never have a collision.
  804. // In the real-world remote compactions, when the compaction is indeed running
  805. // in another process, this is not going to be the case.
  806. // To simulate the SST file with the same name created in the tmp directory,
  807. // override the file number in remote compaction to re-use old SST file
  808. // number.
  809. bool need_to_override_file_number = false;
  810. SyncPoint::GetInstance()->SetCallBack(
  811. "DBImplSecondary::OpenAndCompact::BeforeLoadingOptions:0",
  812. [&](void*) { need_to_override_file_number = true; });
  813. SyncPoint::GetInstance()->SetCallBack(
  814. "CompactionJob::OpenCompactionOutputFile::NewFileNumber",
  815. [&](void* file_number) {
  816. if (need_to_override_file_number) {
  817. auto n = static_cast<uint64_t*>(file_number);
  818. ColumnFamilyMetaData cf_meta;
  819. db_->GetColumnFamilyMetaData(&cf_meta);
  820. for (const auto& level : cf_meta.levels) {
  821. for (const auto& file : level.files) {
  822. // Use one of the existing file name
  823. *n = test::GetFileNumber(file.name);
  824. need_to_override_file_number = false;
  825. return;
  826. }
  827. }
  828. }
  829. });
  830. // Inject failure, so that the remote compaction fails after
  831. // ProcessKeyValueCompaction()
  832. SyncPoint::GetInstance()->SetCallBack(
  833. "DBImplSecondary::CompactWithoutInstallation::End", [&](void* status) {
  834. // override job status
  835. auto s = static_cast<Status*>(status);
  836. *s = Status::Aborted("MyTestCompactionService failed to compact!");
  837. });
  838. SyncPoint::GetInstance()->EnableProcessing();
  839. // Compaction should fail and SST files in the primary db should exist
  840. {
  841. ASSERT_NOK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  842. ColumnFamilyMetaData meta;
  843. db_->GetColumnFamilyMetaData(&meta);
  844. for (const auto& level : meta.levels) {
  845. for (const auto& file : level.files) {
  846. std::string fname = file.db_path + "/" + file.name;
  847. ASSERT_OK(db_->GetEnv()->FileExists(fname));
  848. }
  849. }
  850. }
  851. Close();
  852. SyncPoint::GetInstance()->DisableProcessing();
  853. SyncPoint::GetInstance()->ClearAllCallBacks();
  854. }
  855. TEST_F(CompactionServiceTest, CorruptedOutput) {
  856. Options options = CurrentOptions();
  857. options.disable_auto_compactions = true;
  858. ReopenWithCompactionService(&options);
  859. GenerateTestData();
  860. auto my_cs = GetCompactionService();
  861. std::string start_str = Key(15);
  862. std::string end_str = Key(45);
  863. Slice start(start_str);
  864. Slice end(end_str);
  865. uint64_t comp_num = my_cs->GetCompactionNum();
  866. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  867. "CompactionServiceCompactionJob::Run:0", [&](void* arg) {
  868. CompactionServiceResult* compaction_result =
  869. *(static_cast<CompactionServiceResult**>(arg));
  870. ASSERT_TRUE(compaction_result != nullptr &&
  871. !compaction_result->output_files.empty());
  872. // Corrupt files here
  873. for (const auto& output_file : compaction_result->output_files) {
  874. std::string file_name =
  875. compaction_result->output_path + "/" + output_file.file_name;
  876. uint64_t file_size = 0;
  877. Status s = options.env->GetFileSize(file_name, &file_size);
  878. ASSERT_OK(s);
  879. ASSERT_GT(file_size, 0);
  880. ASSERT_OK(test::CorruptFile(env_, file_name, 0,
  881. static_cast<int>(file_size),
  882. true /* verifyChecksum */));
  883. }
  884. });
  885. SyncPoint::GetInstance()->EnableProcessing();
  886. // CompactRange() should fail
  887. Status s = db_->CompactRange(CompactRangeOptions(), &start, &end);
  888. ASSERT_NOK(s);
  889. ASSERT_TRUE(s.IsCorruption());
  890. ASSERT_GE(my_cs->GetCompactionNum(), comp_num + 1);
  891. SyncPoint::GetInstance()->DisableProcessing();
  892. SyncPoint::GetInstance()->ClearAllCallBacks();
  893. // On the worker side, the compaction is considered success
  894. // Verification is done on the primary side
  895. CompactionServiceResult result;
  896. my_cs->GetResult(&result);
  897. ASSERT_OK(result.status);
  898. ASSERT_TRUE(result.stats.is_manual_compaction);
  899. ASSERT_TRUE(result.stats.is_remote_compaction);
  900. }
  901. TEST_F(CompactionServiceTest, CorruptedOutputParanoidFileCheck) {
  902. for (bool paranoid_file_check_enabled : {false, true}) {
  903. SCOPED_TRACE("paranoid_file_check_enabled=" +
  904. std::to_string(paranoid_file_check_enabled));
  905. Options options = CurrentOptions();
  906. Destroy(options);
  907. options.disable_auto_compactions = true;
  908. options.paranoid_file_checks = paranoid_file_check_enabled;
  909. ReopenWithCompactionService(&options);
  910. GenerateTestData();
  911. auto my_cs = GetCompactionService();
  912. std::string start_str = Key(15);
  913. std::string end_str = Key(45);
  914. Slice start(start_str);
  915. Slice end(end_str);
  916. uint64_t comp_num = my_cs->GetCompactionNum();
  917. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  918. "CompactionServiceCompactionJob::Run:0", [&](void* arg) {
  919. CompactionServiceResult* compaction_result =
  920. *(static_cast<CompactionServiceResult**>(arg));
  921. ASSERT_TRUE(compaction_result != nullptr &&
  922. !compaction_result->output_files.empty());
  923. // Corrupt files here
  924. for (const auto& output_file : compaction_result->output_files) {
  925. std::string file_name =
  926. compaction_result->output_path + "/" + output_file.file_name;
  927. // Corrupt very small range of bytes. This corruption is so small
  928. // that this isn't caught by default light-weight check
  929. ASSERT_OK(test::CorruptFile(env_, file_name, 0, 1,
  930. false /* verifyChecksum */));
  931. }
  932. });
  933. SyncPoint::GetInstance()->EnableProcessing();
  934. Status s = db_->CompactRange(CompactRangeOptions(), &start, &end);
  935. if (paranoid_file_check_enabled) {
  936. ASSERT_NOK(s);
  937. ASSERT_EQ(Status::Corruption("Paranoid checksums do not match"), s);
  938. } else {
  939. // CompactRange() goes through if paranoid file check is not enabled
  940. ASSERT_OK(s);
  941. }
  942. ASSERT_GE(my_cs->GetCompactionNum(), comp_num + 1);
  943. SyncPoint::GetInstance()->DisableProcessing();
  944. SyncPoint::GetInstance()->ClearAllCallBacks();
  945. // On the worker side, the compaction is considered success
  946. // Verification is done on the primary side
  947. CompactionServiceResult result;
  948. my_cs->GetResult(&result);
  949. ASSERT_OK(result.status);
  950. ASSERT_TRUE(result.stats.is_manual_compaction);
  951. ASSERT_TRUE(result.stats.is_remote_compaction);
  952. }
  953. }
  954. TEST_F(CompactionServiceTest, TruncatedOutput) {
  955. Options options = CurrentOptions();
  956. options.disable_auto_compactions = true;
  957. ReopenWithCompactionService(&options);
  958. GenerateTestData();
  959. auto my_cs = GetCompactionService();
  960. std::string start_str = Key(15);
  961. std::string end_str = Key(45);
  962. Slice start(start_str);
  963. Slice end(end_str);
  964. uint64_t comp_num = my_cs->GetCompactionNum();
  965. // Skip calculating tail size to avoid crashing due to truncated file size
  966. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  967. "FileMetaData::CalculateTailSize", [&](void* arg) {
  968. bool* skip = static_cast<bool*>(arg);
  969. *skip = true;
  970. });
  971. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  972. "CompactionServiceCompactionJob::Run:0", [&](void* arg) {
  973. CompactionServiceResult* compaction_result =
  974. *(static_cast<CompactionServiceResult**>(arg));
  975. ASSERT_TRUE(compaction_result != nullptr &&
  976. !compaction_result->output_files.empty());
  977. // Truncate files here
  978. for (const auto& output_file : compaction_result->output_files) {
  979. std::string file_name =
  980. compaction_result->output_path + "/" + output_file.file_name;
  981. uint64_t file_size = 0;
  982. Status s = options.env->GetFileSize(file_name, &file_size);
  983. ASSERT_OK(s);
  984. ASSERT_GT(file_size, 0);
  985. ASSERT_OK(test::TruncateFile(env_, file_name, file_size / 4));
  986. }
  987. });
  988. SyncPoint::GetInstance()->EnableProcessing();
  989. // CompactRange() should fail
  990. Status s = db_->CompactRange(CompactRangeOptions(), &start, &end);
  991. ASSERT_NOK(s);
  992. ASSERT_TRUE(s.IsCorruption());
  993. ASSERT_GE(my_cs->GetCompactionNum(), comp_num + 1);
  994. SyncPoint::GetInstance()->DisableProcessing();
  995. SyncPoint::GetInstance()->ClearAllCallBacks();
  996. // On the worker side, the compaction is considered success
  997. // Verification is done on the primary side
  998. CompactionServiceResult result;
  999. my_cs->GetResult(&result);
  1000. ASSERT_OK(result.status);
  1001. ASSERT_TRUE(result.stats.is_manual_compaction);
  1002. ASSERT_TRUE(result.stats.is_remote_compaction);
  1003. }
  1004. TEST_F(CompactionServiceTest, CustomFileChecksum) {
  1005. Options options = CurrentOptions();
  1006. options.file_checksum_gen_factory = GetFileChecksumGenCrc32cFactory();
  1007. ReopenWithCompactionService(&options);
  1008. GenerateTestData();
  1009. auto my_cs = GetCompactionService();
  1010. std::string start_str = Key(15);
  1011. std::string end_str = Key(45);
  1012. Slice start(start_str);
  1013. Slice end(end_str);
  1014. uint64_t comp_num = my_cs->GetCompactionNum();
  1015. ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
  1016. "CompactionServiceCompactionJob::Run:0", [&](void* arg) {
  1017. CompactionServiceResult* compaction_result =
  1018. *(static_cast<CompactionServiceResult**>(arg));
  1019. ASSERT_TRUE(compaction_result != nullptr &&
  1020. !compaction_result->output_files.empty());
  1021. // Validate Checksum files here
  1022. for (const auto& output_file : compaction_result->output_files) {
  1023. std::string file_name =
  1024. compaction_result->output_path + "/" + output_file.file_name;
  1025. FileChecksumGenContext gen_context;
  1026. gen_context.file_name = file_name;
  1027. std::unique_ptr<FileChecksumGenerator> file_checksum_gen =
  1028. options.file_checksum_gen_factory->CreateFileChecksumGenerator(
  1029. gen_context);
  1030. std::unique_ptr<SequentialFile> file_reader;
  1031. uint64_t file_size = 0;
  1032. Status s = options.env->GetFileSize(file_name, &file_size);
  1033. ASSERT_OK(s);
  1034. ASSERT_GT(file_size, 0);
  1035. s = options.env->NewSequentialFile(file_name, &file_reader,
  1036. EnvOptions());
  1037. ASSERT_OK(s);
  1038. Slice result;
  1039. std::unique_ptr<char[]> scratch(new char[file_size]);
  1040. s = file_reader->Read(file_size, &result, scratch.get());
  1041. ASSERT_OK(s);
  1042. file_checksum_gen->Update(scratch.get(), result.size());
  1043. file_checksum_gen->Finalize();
  1044. // Verify actual checksum and the func name
  1045. ASSERT_EQ(file_checksum_gen->Name(),
  1046. output_file.file_checksum_func_name);
  1047. ASSERT_EQ(file_checksum_gen->GetChecksum(),
  1048. output_file.file_checksum);
  1049. }
  1050. });
  1051. SyncPoint::GetInstance()->EnableProcessing();
  1052. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &start, &end));
  1053. ASSERT_GE(my_cs->GetCompactionNum(), comp_num + 1);
  1054. SyncPoint::GetInstance()->DisableProcessing();
  1055. SyncPoint::GetInstance()->ClearAllCallBacks();
  1056. CompactionServiceResult result;
  1057. my_cs->GetResult(&result);
  1058. ASSERT_OK(result.status);
  1059. ASSERT_TRUE(result.stats.is_manual_compaction);
  1060. ASSERT_TRUE(result.stats.is_remote_compaction);
  1061. }
  1062. TEST_F(CompactionServiceTest, CancelCompactionOnRemoteSide) {
  1063. Options options = CurrentOptions();
  1064. options.disable_auto_compactions = true;
  1065. ReopenWithCompactionService(&options);
  1066. GenerateTestData();
  1067. auto my_cs = GetCompactionService();
  1068. std::string start_str = Key(15);
  1069. std::string end_str = Key(45);
  1070. Slice start(start_str);
  1071. Slice end(end_str);
  1072. uint64_t comp_num = my_cs->GetCompactionNum();
  1073. // Test cancel compaction at the beginning
  1074. my_cs->SetCanceled(true);
  1075. auto s = db_->CompactRange(CompactRangeOptions(), &start, &end);
  1076. ASSERT_TRUE(s.IsIncomplete());
  1077. // compaction number is not increased
  1078. ASSERT_GE(my_cs->GetCompactionNum(), comp_num);
  1079. VerifyTestData();
  1080. // Test cancel compaction in progress
  1081. ReopenWithCompactionService(&options);
  1082. GenerateTestData();
  1083. my_cs = GetCompactionService();
  1084. my_cs->SetCanceled(false);
  1085. std::atomic_bool cancel_issued{false};
  1086. SyncPoint::GetInstance()->SetCallBack("CompactionJob::Run():Inprogress",
  1087. [&](void* /*arg*/) {
  1088. cancel_issued = true;
  1089. my_cs->SetCanceled(true);
  1090. });
  1091. SyncPoint::GetInstance()->EnableProcessing();
  1092. s = db_->CompactRange(CompactRangeOptions(), &start, &end);
  1093. ASSERT_TRUE(s.IsIncomplete());
  1094. ASSERT_TRUE(cancel_issued);
  1095. // compaction number is not increased
  1096. ASSERT_GE(my_cs->GetCompactionNum(), comp_num);
  1097. VerifyTestData();
  1098. }
  1099. TEST_F(CompactionServiceTest, CancelCompactionOnPrimarySide) {
  1100. Options options = CurrentOptions();
  1101. options.disable_auto_compactions = true;
  1102. ReopenWithCompactionService(&options);
  1103. GenerateTestData();
  1104. auto my_cs = GetCompactionService();
  1105. std::string start_str = Key(15);
  1106. std::string end_str = Key(45);
  1107. Slice start(start_str);
  1108. Slice end(end_str);
  1109. uint64_t comp_num = my_cs->GetCompactionNum();
  1110. ReopenWithCompactionService(&options);
  1111. GenerateTestData();
  1112. my_cs = GetCompactionService();
  1113. // Primary DB calls CancelAllBackgroundWork() while the compaction is running
  1114. SyncPoint::GetInstance()->SetCallBack(
  1115. "CompactionJob::Run():Inprogress",
  1116. [&](void* /*arg*/) { CancelAllBackgroundWork(db_, false /*wait*/); });
  1117. SyncPoint::GetInstance()->EnableProcessing();
  1118. Status s = db_->CompactRange(CompactRangeOptions(), &start, &end);
  1119. ASSERT_TRUE(s.IsIncomplete());
  1120. // Check canceled_ was set to true by CancelAwaitingJobs()
  1121. ASSERT_TRUE(my_cs->GetCanceled());
  1122. // compaction number is not increased
  1123. ASSERT_GE(my_cs->GetCompactionNum(), comp_num);
  1124. }
  1125. TEST_F(CompactionServiceTest, FailedToStart) {
  1126. Options options = CurrentOptions();
  1127. options.disable_auto_compactions = true;
  1128. ReopenWithCompactionService(&options);
  1129. GenerateTestData();
  1130. auto my_cs = GetCompactionService();
  1131. my_cs->OverrideStartStatus(CompactionServiceJobStatus::kFailure);
  1132. std::string start_str = Key(15);
  1133. std::string end_str = Key(45);
  1134. Slice start(start_str);
  1135. Slice end(end_str);
  1136. Status s = db_->CompactRange(CompactRangeOptions(), &start, &end);
  1137. ASSERT_TRUE(s.IsIncomplete());
  1138. }
  1139. TEST_F(CompactionServiceTest, InvalidResult) {
  1140. Options options = CurrentOptions();
  1141. options.disable_auto_compactions = true;
  1142. ReopenWithCompactionService(&options);
  1143. GenerateTestData();
  1144. auto my_cs = GetCompactionService();
  1145. my_cs->OverrideWaitResult("Invalid Str");
  1146. std::string start_str = Key(15);
  1147. std::string end_str = Key(45);
  1148. Slice start(start_str);
  1149. Slice end(end_str);
  1150. Status s = db_->CompactRange(CompactRangeOptions(), &start, &end);
  1151. ASSERT_FALSE(s.ok());
  1152. ASSERT_EQ(CompactionServiceJobStatus::kFailure,
  1153. my_cs->GetFinalCompactionServiceJobStatus());
  1154. }
  1155. TEST_F(CompactionServiceTest, SubCompaction) {
  1156. Options options = CurrentOptions();
  1157. options.max_subcompactions = 10;
  1158. options.target_file_size_base = 1 << 10; // 1KB
  1159. options.disable_auto_compactions = true;
  1160. ReopenWithCompactionService(&options);
  1161. GenerateTestData();
  1162. VerifyTestData();
  1163. auto my_cs = GetCompactionService();
  1164. int compaction_num_before = my_cs->GetCompactionNum();
  1165. auto cro = CompactRangeOptions();
  1166. cro.max_subcompactions = 10;
  1167. Status s = db_->CompactRange(cro, nullptr, nullptr);
  1168. ASSERT_OK(s);
  1169. VerifyTestData();
  1170. int compaction_num = my_cs->GetCompactionNum() - compaction_num_before;
  1171. // make sure there's sub-compaction by checking the compaction number
  1172. ASSERT_GE(compaction_num, 2);
  1173. }
  1174. class PartialDeleteCompactionFilter : public CompactionFilter {
  1175. public:
  1176. CompactionFilter::Decision FilterV2(
  1177. int /*level*/, const Slice& key, ValueType /*value_type*/,
  1178. const Slice& /*existing_value*/, std::string* /*new_value*/,
  1179. std::string* /*skip_until*/) const override {
  1180. int i = std::stoi(key.ToString().substr(3));
  1181. if (i > 5 && i <= 105) {
  1182. return CompactionFilter::Decision::kRemove;
  1183. }
  1184. return CompactionFilter::Decision::kKeep;
  1185. }
  1186. const char* Name() const override { return "PartialDeleteCompactionFilter"; }
  1187. };
  1188. TEST_F(CompactionServiceTest, CompactionFilter) {
  1189. Options options = CurrentOptions();
  1190. std::unique_ptr<CompactionFilter> delete_comp_filter(
  1191. new PartialDeleteCompactionFilter());
  1192. options.compaction_filter = delete_comp_filter.get();
  1193. ReopenWithCompactionService(&options);
  1194. GenerateTestData();
  1195. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  1196. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  1197. // verify result
  1198. for (int i = 0; i < 200; i++) {
  1199. auto result = Get(Key(i));
  1200. if (i > 5 && i <= 105) {
  1201. ASSERT_EQ(result, "NOT_FOUND");
  1202. } else if (i % 2) {
  1203. ASSERT_EQ(result, "value" + std::to_string(i));
  1204. } else {
  1205. ASSERT_EQ(result, "value_new" + std::to_string(i));
  1206. }
  1207. }
  1208. auto my_cs = GetCompactionService();
  1209. ASSERT_GE(my_cs->GetCompactionNum(), 1);
  1210. }
  1211. TEST_F(CompactionServiceTest, MergeOperator) {
  1212. Options options = CurrentOptions();
  1213. options.merge_operator.reset(new StringAppendOperator(','));
  1214. ReopenWithCompactionService(&options);
  1215. GenerateTestData();
  1216. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  1217. for (int i = 0; i < 200; i++) {
  1218. ASSERT_OK(db_->Merge(WriteOptions(), Key(i),
  1219. "merge_op_append_" + std::to_string(i)));
  1220. }
  1221. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  1222. // verify result
  1223. for (int i = 0; i < 200; i++) {
  1224. auto result = Get(Key(i));
  1225. if (i % 2) {
  1226. ASSERT_EQ(result, "value" + std::to_string(i) + ",merge_op_append_" +
  1227. std::to_string(i));
  1228. } else {
  1229. ASSERT_EQ(result, "value_new" + std::to_string(i) + ",merge_op_append_" +
  1230. std::to_string(i));
  1231. }
  1232. }
  1233. auto my_cs = GetCompactionService();
  1234. ASSERT_GE(my_cs->GetCompactionNum(), 1);
  1235. }
  1236. TEST_F(CompactionServiceTest, Snapshot) {
  1237. Options options = CurrentOptions();
  1238. ReopenWithCompactionService(&options);
  1239. ASSERT_OK(Put(Key(1), "value1"));
  1240. ASSERT_OK(Put(Key(2), "value1"));
  1241. const Snapshot* s1 = db_->GetSnapshot();
  1242. ASSERT_OK(Flush());
  1243. ASSERT_OK(Put(Key(1), "value2"));
  1244. ASSERT_OK(Put(Key(3), "value2"));
  1245. ASSERT_OK(Flush());
  1246. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  1247. auto my_cs = GetCompactionService();
  1248. ASSERT_GE(my_cs->GetCompactionNum(), 1);
  1249. ASSERT_EQ("value1", Get(Key(1), s1));
  1250. ASSERT_EQ("value2", Get(Key(1)));
  1251. db_->ReleaseSnapshot(s1);
  1252. }
  1253. TEST_F(CompactionServiceTest, PrecludeLastLevel) {
  1254. const int kNumTrigger = 4;
  1255. const int kNumLevels = 7;
  1256. const int kNumKeys = 100;
  1257. Options options = CurrentOptions();
  1258. options.compaction_style = kCompactionStyleUniversal;
  1259. options.last_level_temperature = Temperature::kCold;
  1260. options.level0_file_num_compaction_trigger = 4;
  1261. options.max_subcompactions = 10;
  1262. options.num_levels = kNumLevels;
  1263. ReopenWithCompactionService(&options);
  1264. // Alternate for comparison: DestroyAndReopen(options);
  1265. // This is simpler than setting up mock time to make the user option work,
  1266. // but is not as direct as testing with preclude option itself.
  1267. SyncPoint::GetInstance()->SetCallBack(
  1268. "Compaction::SupportsPerKeyPlacement:Enabled",
  1269. [&](void* arg) { *static_cast<bool*>(arg) = true; });
  1270. SyncPoint::GetInstance()->SetCallBack(
  1271. "CompactionJob::PrepareTimes():preclude_last_level_min_seqno",
  1272. [&](void* arg) { *static_cast<SequenceNumber*>(arg) = 100; });
  1273. SyncPoint::GetInstance()->EnableProcessing();
  1274. for (int i = 0; i < kNumTrigger; i++) {
  1275. for (int j = 0; j < kNumKeys; j++) {
  1276. ASSERT_OK(Put(Key(j * kNumTrigger + i), "v" + std::to_string(i)));
  1277. }
  1278. ASSERT_OK(Flush());
  1279. }
  1280. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  1281. // Data split between proximal (kUnknown) and last (kCold) levels
  1282. ASSERT_EQ("0,0,0,0,0,1,1", FilesPerLevel());
  1283. ASSERT_GT(GetSstSizeHelper(Temperature::kUnknown), 0);
  1284. ASSERT_GT(GetSstSizeHelper(Temperature::kCold), 0);
  1285. // TODO: Check FileSystem temperatures with FileTemperatureTestFS
  1286. for (int i = 0; i < kNumTrigger; i++) {
  1287. for (int j = 0; j < kNumKeys; j++) {
  1288. ASSERT_EQ(Get(Key(j * kNumTrigger + i)), "v" + std::to_string(i));
  1289. }
  1290. }
  1291. // Verify Output Stats
  1292. auto my_cs = GetCompactionService();
  1293. {
  1294. CompactionServiceResult result;
  1295. my_cs->GetResult(&result);
  1296. ASSERT_OK(result.status);
  1297. ASSERT_GT(result.internal_stats.output_level_stats.cpu_micros, 0);
  1298. ASSERT_GT(result.internal_stats.output_level_stats.micros, 0);
  1299. ASSERT_EQ(result.internal_stats.output_level_stats.num_output_records +
  1300. result.internal_stats.proximal_level_stats.num_output_records,
  1301. kNumTrigger * kNumKeys);
  1302. ASSERT_EQ(result.internal_stats.output_level_stats.num_output_files +
  1303. result.internal_stats.proximal_level_stats.num_output_files,
  1304. 2);
  1305. CompactionServiceJobInfo info = my_cs->GetCompactionInfoForStart();
  1306. ASSERT_EQ(0, info.base_input_level);
  1307. ASSERT_EQ(kNumLevels - 1, info.output_level);
  1308. }
  1309. SyncPoint::GetInstance()->DisableProcessing();
  1310. // Disable Preclude feature and run full compaction to the bottommost level
  1311. {
  1312. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
  1313. CompactionServiceJobInfo info = my_cs->GetCompactionInfoForStart();
  1314. ASSERT_EQ(kNumLevels - 2, info.base_input_level);
  1315. ASSERT_EQ(kNumLevels - 1, info.output_level);
  1316. }
  1317. }
  1318. TEST_F(CompactionServiceTest, ConcurrentCompaction) {
  1319. Options options = CurrentOptions();
  1320. options.level0_file_num_compaction_trigger = 100;
  1321. options.max_background_jobs = 20;
  1322. ReopenWithCompactionService(&options);
  1323. GenerateTestData(true);
  1324. ColumnFamilyMetaData meta;
  1325. db_->GetColumnFamilyMetaData(&meta);
  1326. std::vector<std::thread> threads;
  1327. for (const auto& file : meta.levels[1].files) {
  1328. threads.emplace_back([&]() {
  1329. std::string fname = file.db_path + "/" + file.name;
  1330. ASSERT_OK(db_->CompactFiles(CompactionOptions(), {fname}, 2));
  1331. });
  1332. }
  1333. for (auto& thread : threads) {
  1334. thread.join();
  1335. }
  1336. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  1337. // verify result
  1338. VerifyTestData();
  1339. auto my_cs = GetCompactionService();
  1340. ASSERT_EQ(my_cs->GetCompactionNum(), 10);
  1341. ASSERT_EQ(FilesPerLevel(), "0,0,10");
  1342. }
  1343. TEST_F(CompactionServiceTest, CompactionInfo) {
  1344. Options options = CurrentOptions();
  1345. ReopenWithCompactionService(&options);
  1346. GenerateTestData();
  1347. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  1348. auto my_cs =
  1349. static_cast_with_check<MyTestCompactionService>(GetCompactionService());
  1350. uint64_t comp_num = my_cs->GetCompactionNum();
  1351. ASSERT_GE(comp_num, 1);
  1352. CompactionServiceJobInfo info = my_cs->GetCompactionInfoForStart();
  1353. ASSERT_EQ(dbname_, info.db_name);
  1354. std::string db_id, db_session_id;
  1355. ASSERT_OK(db_->GetDbIdentity(db_id));
  1356. ASSERT_EQ(db_id, info.db_id);
  1357. ASSERT_OK(db_->GetDbSessionId(db_session_id));
  1358. ASSERT_EQ(db_session_id, info.db_session_id);
  1359. ASSERT_EQ(Env::LOW, info.priority);
  1360. info = my_cs->GetCompactionInfoForWait();
  1361. ASSERT_EQ(dbname_, info.db_name);
  1362. ASSERT_EQ(db_id, info.db_id);
  1363. ASSERT_EQ(db_session_id, info.db_session_id);
  1364. ASSERT_EQ(Env::LOW, info.priority);
  1365. // Test priority USER
  1366. ColumnFamilyMetaData meta;
  1367. db_->GetColumnFamilyMetaData(&meta);
  1368. SstFileMetaData file = meta.levels[1].files[0];
  1369. ASSERT_OK(db_->CompactFiles(CompactionOptions(),
  1370. {file.db_path + "/" + file.name}, 2));
  1371. info = my_cs->GetCompactionInfoForStart();
  1372. ASSERT_EQ(Env::USER, info.priority);
  1373. ASSERT_EQ(CompactionReason::kManualCompaction, info.compaction_reason);
  1374. ASSERT_EQ(true, info.is_manual_compaction);
  1375. ASSERT_EQ(false, info.is_full_compaction);
  1376. ASSERT_EQ(true, info.bottommost_level);
  1377. ASSERT_EQ(1, info.base_input_level);
  1378. ASSERT_EQ(2, info.output_level);
  1379. info = my_cs->GetCompactionInfoForWait();
  1380. ASSERT_EQ(Env::USER, info.priority);
  1381. ASSERT_EQ(CompactionReason::kManualCompaction, info.compaction_reason);
  1382. ASSERT_EQ(true, info.is_manual_compaction);
  1383. ASSERT_EQ(false, info.is_full_compaction);
  1384. ASSERT_EQ(true, info.bottommost_level);
  1385. ASSERT_EQ(1, info.base_input_level);
  1386. ASSERT_EQ(2, info.output_level);
  1387. ASSERT_EQ(kDefaultColumnFamilyName, info.cf_name);
  1388. // Test priority BOTTOM
  1389. env_->SetBackgroundThreads(1, Env::BOTTOM);
  1390. // This will set bottommost_level = true but is_full_compaction = false
  1391. options.num_levels = 2;
  1392. ReopenWithCompactionService(&options);
  1393. my_cs =
  1394. static_cast_with_check<MyTestCompactionService>(GetCompactionService());
  1395. for (int i = 0; i < 20; i++) {
  1396. for (int j = 0; j < 10; j++) {
  1397. int key_id = i * 10 + j;
  1398. ASSERT_OK(Put(Key(key_id), "value" + std::to_string(key_id)));
  1399. }
  1400. ASSERT_OK(Flush());
  1401. }
  1402. for (int i = 0; i < 4; i++) {
  1403. for (int j = 0; j < 10; j++) {
  1404. int key_id = i * 20 + j * 2;
  1405. ASSERT_OK(Put(Key(key_id), "value_new" + std::to_string(key_id)));
  1406. }
  1407. ASSERT_OK(Flush());
  1408. }
  1409. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  1410. info = my_cs->GetCompactionInfoForStart();
  1411. ASSERT_EQ(CompactionReason::kLevelL0FilesNum, info.compaction_reason);
  1412. ASSERT_EQ(false, info.is_manual_compaction);
  1413. ASSERT_EQ(false, info.is_full_compaction);
  1414. ASSERT_EQ(true, info.bottommost_level);
  1415. ASSERT_EQ(Env::BOTTOM, info.priority);
  1416. ASSERT_EQ(0, info.base_input_level);
  1417. ASSERT_EQ(db_->NumberLevels() - 1, info.output_level);
  1418. info = my_cs->GetCompactionInfoForWait();
  1419. ASSERT_EQ(Env::BOTTOM, info.priority);
  1420. ASSERT_EQ(CompactionReason::kLevelL0FilesNum, info.compaction_reason);
  1421. ASSERT_EQ(false, info.is_manual_compaction);
  1422. ASSERT_EQ(false, info.is_full_compaction);
  1423. ASSERT_EQ(true, info.bottommost_level);
  1424. ASSERT_EQ(0, info.base_input_level);
  1425. ASSERT_EQ(db_->NumberLevels() - 1, info.output_level);
  1426. // Test Non-Bottommost Level
  1427. options.num_levels = 4;
  1428. ReopenWithCompactionService(&options);
  1429. my_cs =
  1430. static_cast_with_check<MyTestCompactionService>(GetCompactionService());
  1431. int compaction_num = my_cs->GetCompactionNum();
  1432. ASSERT_EQ(0, compaction_num);
  1433. for (int i = 0; i < options.level0_file_num_compaction_trigger; i++) {
  1434. for (int j = 0; j < 10; j++) {
  1435. int key_id = i * 10 + j;
  1436. ASSERT_OK(Put(Key(key_id), "value_new_new" + std::to_string(key_id)));
  1437. }
  1438. ASSERT_OK(Flush());
  1439. }
  1440. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  1441. // This is trivial move. Done locally.
  1442. ASSERT_EQ(0, my_cs->GetCompactionNum());
  1443. info = my_cs->GetCompactionInfoForStart();
  1444. ASSERT_EQ(false, info.is_manual_compaction);
  1445. ASSERT_EQ(false, info.is_full_compaction);
  1446. ASSERT_EQ(false, info.bottommost_level);
  1447. ASSERT_EQ(-1, info.base_input_level);
  1448. ASSERT_EQ(-1, info.output_level);
  1449. info = my_cs->GetCompactionInfoForWait();
  1450. ASSERT_EQ(false, info.is_manual_compaction);
  1451. ASSERT_EQ(false, info.is_full_compaction);
  1452. ASSERT_EQ(false, info.bottommost_level);
  1453. ASSERT_EQ(-1, info.base_input_level);
  1454. ASSERT_EQ(-1, info.output_level);
  1455. // Test Full Compaction + Bottommost Level
  1456. options.num_levels = 6;
  1457. ReopenWithCompactionService(&options);
  1458. my_cs =
  1459. static_cast_with_check<MyTestCompactionService>(GetCompactionService());
  1460. for (int i = 0; i < 20; i++) {
  1461. for (int j = 0; j < 10; j++) {
  1462. int key_id = i * 10 + j;
  1463. ASSERT_OK(Put(Key(key_id), "value_new_new" + std::to_string(key_id)));
  1464. }
  1465. ASSERT_OK(Flush());
  1466. }
  1467. MoveFilesToLevel(options.num_levels - 1);
  1468. // Force final level compaction
  1469. // base_input_level == output_level == last_level
  1470. CompactRangeOptions cro;
  1471. cro.bottommost_level_compaction = BottommostLevelCompaction::kForce;
  1472. ASSERT_OK(db_->CompactRange(cro, nullptr, nullptr));
  1473. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  1474. info = my_cs->GetCompactionInfoForStart();
  1475. ASSERT_EQ(true, info.is_manual_compaction);
  1476. ASSERT_EQ(true, info.is_full_compaction);
  1477. ASSERT_EQ(true, info.bottommost_level);
  1478. ASSERT_EQ(CompactionReason::kManualCompaction, info.compaction_reason);
  1479. info = my_cs->GetCompactionInfoForWait();
  1480. ASSERT_EQ(options.num_levels - 1, info.base_input_level);
  1481. ASSERT_EQ(options.num_levels - 1, info.output_level);
  1482. ASSERT_EQ(true, info.is_manual_compaction);
  1483. ASSERT_EQ(true, info.is_full_compaction);
  1484. ASSERT_EQ(true, info.bottommost_level);
  1485. ASSERT_EQ(CompactionReason::kManualCompaction, info.compaction_reason);
  1486. ASSERT_EQ(options.num_levels - 1, info.base_input_level);
  1487. ASSERT_EQ(options.num_levels - 1, info.output_level);
  1488. ASSERT_EQ("0,0,0,0,0,1", FilesPerLevel());
  1489. }
  1490. TEST_F(CompactionServiceTest, FallbackLocalAuto) {
  1491. Options options = CurrentOptions();
  1492. ReopenWithCompactionService(&options);
  1493. auto my_cs = GetCompactionService();
  1494. Statistics* compactor_statistics = GetCompactorStatistics();
  1495. Statistics* primary_statistics = GetPrimaryStatistics();
  1496. uint64_t compactor_write_bytes =
  1497. compactor_statistics->getTickerCount(COMPACT_WRITE_BYTES);
  1498. uint64_t primary_write_bytes =
  1499. primary_statistics->getTickerCount(COMPACT_WRITE_BYTES);
  1500. my_cs->OverrideStartStatus(CompactionServiceJobStatus::kUseLocal);
  1501. GenerateTestData();
  1502. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  1503. VerifyTestData();
  1504. ASSERT_EQ(my_cs->GetCompactionNum(), 0);
  1505. // make sure the compaction statistics is only recorded on the local side
  1506. ASSERT_EQ(compactor_statistics->getTickerCount(COMPACT_WRITE_BYTES),
  1507. compactor_write_bytes);
  1508. ASSERT_GT(primary_statistics->getTickerCount(COMPACT_WRITE_BYTES),
  1509. primary_write_bytes);
  1510. ASSERT_EQ(primary_statistics->getTickerCount(REMOTE_COMPACT_READ_BYTES), 0);
  1511. ASSERT_EQ(primary_statistics->getTickerCount(REMOTE_COMPACT_WRITE_BYTES), 0);
  1512. }
  1513. TEST_F(CompactionServiceTest, FallbackLocalManual) {
  1514. Options options = CurrentOptions();
  1515. options.disable_auto_compactions = true;
  1516. ReopenWithCompactionService(&options);
  1517. GenerateTestData();
  1518. VerifyTestData();
  1519. auto my_cs = GetCompactionService();
  1520. Statistics* compactor_statistics = GetCompactorStatistics();
  1521. Statistics* primary_statistics = GetPrimaryStatistics();
  1522. uint64_t compactor_write_bytes =
  1523. compactor_statistics->getTickerCount(COMPACT_WRITE_BYTES);
  1524. uint64_t primary_write_bytes =
  1525. primary_statistics->getTickerCount(COMPACT_WRITE_BYTES);
  1526. // re-enable remote compaction
  1527. my_cs->ResetOverride();
  1528. std::string start_str = Key(15);
  1529. std::string end_str = Key(45);
  1530. Slice start(start_str);
  1531. Slice end(end_str);
  1532. uint64_t comp_num = my_cs->GetCompactionNum();
  1533. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &start, &end));
  1534. ASSERT_GE(my_cs->GetCompactionNum(), comp_num + 1);
  1535. // make sure the compaction statistics is only recorded on the remote side
  1536. ASSERT_GT(compactor_statistics->getTickerCount(COMPACT_WRITE_BYTES),
  1537. compactor_write_bytes);
  1538. ASSERT_EQ(primary_statistics->getTickerCount(REMOTE_COMPACT_WRITE_BYTES),
  1539. compactor_statistics->getTickerCount(COMPACT_WRITE_BYTES));
  1540. ASSERT_EQ(primary_statistics->getTickerCount(COMPACT_WRITE_BYTES),
  1541. primary_write_bytes);
  1542. // return run local again with API WaitForComplete
  1543. my_cs->OverrideWaitStatus(CompactionServiceJobStatus::kUseLocal);
  1544. start_str = Key(120);
  1545. start = start_str;
  1546. comp_num = my_cs->GetCompactionNum();
  1547. compactor_write_bytes =
  1548. compactor_statistics->getTickerCount(COMPACT_WRITE_BYTES);
  1549. primary_write_bytes = primary_statistics->getTickerCount(COMPACT_WRITE_BYTES);
  1550. ASSERT_OK(db_->CompactRange(CompactRangeOptions(), &start, nullptr));
  1551. ASSERT_EQ(my_cs->GetCompactionNum(),
  1552. comp_num); // no remote compaction is run
  1553. // make sure the compaction statistics is only recorded on the local side
  1554. ASSERT_EQ(compactor_statistics->getTickerCount(COMPACT_WRITE_BYTES),
  1555. compactor_write_bytes);
  1556. ASSERT_GT(primary_statistics->getTickerCount(COMPACT_WRITE_BYTES),
  1557. primary_write_bytes);
  1558. ASSERT_EQ(primary_statistics->getTickerCount(REMOTE_COMPACT_WRITE_BYTES),
  1559. compactor_write_bytes);
  1560. // verify result after 2 manual compactions
  1561. VerifyTestData();
  1562. }
  1563. TEST_F(CompactionServiceTest, AbortedWhileWait) {
  1564. Options options = CurrentOptions();
  1565. options.disable_auto_compactions = true;
  1566. ReopenWithCompactionService(&options);
  1567. GenerateTestData();
  1568. VerifyTestData();
  1569. auto my_cs = GetCompactionService();
  1570. Statistics* compactor_statistics = GetCompactorStatistics();
  1571. Statistics* primary_statistics = GetPrimaryStatistics();
  1572. my_cs->ResetOverride();
  1573. std::string start_str = Key(15);
  1574. std::string end_str = Key(45);
  1575. Slice start(start_str);
  1576. Slice end(end_str);
  1577. // Override Wait() result with kAborted
  1578. my_cs->OverrideWaitStatus(CompactionServiceJobStatus::kAborted);
  1579. start_str = Key(120);
  1580. start = start_str;
  1581. Status s = db_->CompactRange(CompactRangeOptions(), &start, nullptr);
  1582. ASSERT_NOK(s);
  1583. ASSERT_TRUE(s.IsAborted());
  1584. // no remote compaction is run
  1585. ASSERT_EQ(my_cs->GetCompactionNum(), 0);
  1586. // make sure the compaction statistics is not recorded any side
  1587. ASSERT_EQ(primary_statistics->getTickerCount(COMPACT_WRITE_BYTES), 0);
  1588. ASSERT_EQ(primary_statistics->getTickerCount(REMOTE_COMPACT_WRITE_BYTES), 0);
  1589. ASSERT_EQ(compactor_statistics->getTickerCount(COMPACT_WRITE_BYTES), 0);
  1590. }
  1591. TEST_F(CompactionServiceTest, RemoteEventListener) {
  1592. class RemoteEventListenerTest : public EventListener {
  1593. public:
  1594. const char* Name() const override { return "RemoteEventListenerTest"; }
  1595. void OnSubcompactionBegin(const SubcompactionJobInfo& info) override {
  1596. auto result = on_going_compactions.emplace(info.job_id);
  1597. ASSERT_TRUE(result.second); // make sure there's no duplication
  1598. compaction_num++;
  1599. EventListener::OnSubcompactionBegin(info);
  1600. }
  1601. void OnSubcompactionCompleted(const SubcompactionJobInfo& info) override {
  1602. auto num = on_going_compactions.erase(info.job_id);
  1603. ASSERT_TRUE(num == 1); // make sure the compaction id exists
  1604. EventListener::OnSubcompactionCompleted(info);
  1605. }
  1606. void OnTableFileCreated(const TableFileCreationInfo& info) override {
  1607. ASSERT_EQ(on_going_compactions.count(info.job_id), 1);
  1608. file_created++;
  1609. EventListener::OnTableFileCreated(info);
  1610. }
  1611. void OnTableFileCreationStarted(
  1612. const TableFileCreationBriefInfo& info) override {
  1613. ASSERT_EQ(on_going_compactions.count(info.job_id), 1);
  1614. file_creation_started++;
  1615. EventListener::OnTableFileCreationStarted(info);
  1616. }
  1617. bool ShouldBeNotifiedOnFileIO() override {
  1618. file_io_notified++;
  1619. return EventListener::ShouldBeNotifiedOnFileIO();
  1620. }
  1621. std::atomic_uint64_t file_io_notified{0};
  1622. std::atomic_uint64_t file_creation_started{0};
  1623. std::atomic_uint64_t file_created{0};
  1624. std::set<int> on_going_compactions; // store the job_id
  1625. std::atomic_uint64_t compaction_num{0};
  1626. };
  1627. auto listener = new RemoteEventListenerTest();
  1628. remote_listeners.emplace_back(listener);
  1629. Options options = CurrentOptions();
  1630. ReopenWithCompactionService(&options);
  1631. for (int i = 0; i < 20; i++) {
  1632. for (int j = 0; j < 10; j++) {
  1633. int key_id = i * 10 + j;
  1634. ASSERT_OK(Put(Key(key_id), "value" + std::to_string(key_id)));
  1635. }
  1636. ASSERT_OK(Flush());
  1637. }
  1638. for (int i = 0; i < 10; i++) {
  1639. for (int j = 0; j < 10; j++) {
  1640. int key_id = i * 20 + j * 2;
  1641. ASSERT_OK(Put(Key(key_id), "value_new" + std::to_string(key_id)));
  1642. }
  1643. ASSERT_OK(Flush());
  1644. }
  1645. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  1646. // check the events are triggered
  1647. ASSERT_TRUE(listener->file_io_notified > 0);
  1648. ASSERT_TRUE(listener->file_creation_started > 0);
  1649. ASSERT_TRUE(listener->file_created > 0);
  1650. ASSERT_TRUE(listener->compaction_num > 0);
  1651. ASSERT_TRUE(listener->on_going_compactions.empty());
  1652. // verify result
  1653. for (int i = 0; i < 200; i++) {
  1654. auto result = Get(Key(i));
  1655. if (i % 2) {
  1656. ASSERT_EQ(result, "value" + std::to_string(i));
  1657. } else {
  1658. ASSERT_EQ(result, "value_new" + std::to_string(i));
  1659. }
  1660. }
  1661. }
  1662. TEST_F(CompactionServiceTest, TablePropertiesCollector) {
  1663. const static std::string kUserPropertyName = "TestCount";
  1664. class TablePropertiesCollectorTest : public TablePropertiesCollector {
  1665. public:
  1666. Status Finish(UserCollectedProperties* properties) override {
  1667. *properties = UserCollectedProperties{
  1668. {kUserPropertyName, std::to_string(count_)},
  1669. };
  1670. return Status::OK();
  1671. }
  1672. UserCollectedProperties GetReadableProperties() const override {
  1673. return UserCollectedProperties();
  1674. }
  1675. const char* Name() const override { return "TablePropertiesCollectorTest"; }
  1676. Status AddUserKey(const Slice& /*user_key*/, const Slice& /*value*/,
  1677. EntryType /*type*/, SequenceNumber /*seq*/,
  1678. uint64_t /*file_size*/) override {
  1679. count_++;
  1680. return Status::OK();
  1681. }
  1682. private:
  1683. uint32_t count_ = 0;
  1684. };
  1685. class TablePropertiesCollectorFactoryTest
  1686. : public TablePropertiesCollectorFactory {
  1687. public:
  1688. TablePropertiesCollector* CreateTablePropertiesCollector(
  1689. TablePropertiesCollectorFactory::Context /*context*/) override {
  1690. return new TablePropertiesCollectorTest();
  1691. }
  1692. const char* Name() const override {
  1693. return "TablePropertiesCollectorFactoryTest";
  1694. }
  1695. };
  1696. auto factory = new TablePropertiesCollectorFactoryTest();
  1697. remote_table_properties_collector_factories.emplace_back(factory);
  1698. const int kNumSst = 3;
  1699. const int kLevel0Trigger = 4;
  1700. Options options = CurrentOptions();
  1701. options.level0_file_num_compaction_trigger = kLevel0Trigger;
  1702. ReopenWithCompactionService(&options);
  1703. // generate a few SSTs locally which should not have user property
  1704. for (int i = 0; i < kNumSst; i++) {
  1705. for (int j = 0; j < 100; j++) {
  1706. ASSERT_OK(Put(Key(i * 10 + j), "value"));
  1707. }
  1708. ASSERT_OK(Flush());
  1709. }
  1710. TablePropertiesCollection fname_to_props;
  1711. ASSERT_OK(db_->GetPropertiesOfAllTables(&fname_to_props));
  1712. for (const auto& file_props : fname_to_props) {
  1713. auto properties = file_props.second->user_collected_properties;
  1714. auto it = properties.find(kUserPropertyName);
  1715. ASSERT_EQ(it, properties.end());
  1716. }
  1717. // trigger compaction
  1718. for (int i = kNumSst; i < kLevel0Trigger; i++) {
  1719. for (int j = 0; j < 100; j++) {
  1720. ASSERT_OK(Put(Key(i * 10 + j), "value"));
  1721. }
  1722. ASSERT_OK(Flush());
  1723. }
  1724. ASSERT_OK(dbfull()->TEST_WaitForCompact());
  1725. ASSERT_OK(db_->GetPropertiesOfAllTables(&fname_to_props));
  1726. bool has_user_property = false;
  1727. for (const auto& file_props : fname_to_props) {
  1728. auto properties = file_props.second->user_collected_properties;
  1729. auto it = properties.find(kUserPropertyName);
  1730. if (it != properties.end()) {
  1731. has_user_property = true;
  1732. ASSERT_GT(std::stoi(it->second), 0);
  1733. }
  1734. }
  1735. ASSERT_TRUE(has_user_property);
  1736. }
  1737. class ResumableCompactionService : public MyTestCompactionService {
  1738. public:
  1739. enum class TestScenario {
  1740. // Test scenario 1: Two-phase compaction with resumption
  1741. // - Phase 1: Cancel the compaction running with resumption enabled (saves
  1742. // progress)
  1743. // - Phase 2: Resume from saved progress and complete
  1744. // Validates: Resumption reduces redundant work
  1745. kCancelThenResume,
  1746. // Test scenario 2: Two-phase compaction without resumption
  1747. // - Phase 1: Cancel the compaction running with resumption enabled (saves
  1748. // progress)
  1749. // - Phase 2: Start fresh without resumption (ignores saved progress) and
  1750. // complete
  1751. // Validates: Disabling resumption causes full reprocessing
  1752. kCancelThenFreshStart,
  1753. // Test scenario 3: Three-phase compaction toggling resumption on/off/on
  1754. // - Phase 1: Cancel the compaction running with resumption enabled (saves
  1755. // progress)
  1756. // - Phase 2: Start fresh wtihout resumption (ignores saved progress) and
  1757. // cancel agains
  1758. // - Phase 3: Resume with resumption support (loads Phase 1's progress) and
  1759. // complete
  1760. // Validates: Resumption state can be toggled;
  1761. kMultipleCancelToggleResumption
  1762. };
  1763. ResumableCompactionService(const std::string& db_path, Options& options,
  1764. std::shared_ptr<Statistics> statistics,
  1765. TestScenario scenario)
  1766. : MyTestCompactionService(db_path, options, statistics,
  1767. {} /* listeners */,
  1768. {} /* table_properties_collector_factories */),
  1769. scenario_(scenario) {}
  1770. CompactionServiceJobStatus Wait(const std::string& scheduled_job_id,
  1771. std::string* result) override {
  1772. std::string compaction_input = ExtractCompactionInput(scheduled_job_id);
  1773. EXPECT_FALSE(compaction_input.empty());
  1774. OpenAndCompactOptions open_and_compaction_options;
  1775. auto override_options = GetOptionsOverride();
  1776. // Force creation of one key per output file for test simplicity.
  1777. // ASSUMPTION: This makes stats.count directly proportional to keys
  1778. // processed.
  1779. SyncPoint::GetInstance()->SetCallBack(
  1780. "CompactionOutputs::ShouldStopBefore::manual_decision", [](void* p) {
  1781. auto* pair = static_cast<std::pair<bool*, const Slice>*>(p);
  1782. *(pair->first) = true;
  1783. });
  1784. // Simulate cancelled compaction by overriding status at completion. So
  1785. // compaction processes all keys before this point to make stats.count
  1786. // comparison straightforward.
  1787. SyncPoint::GetInstance()->SetCallBack(
  1788. "DBImplSecondary::CompactWithoutInstallation::End", [&](void* status) {
  1789. auto s = static_cast<Status*>(status);
  1790. *s = Status::Incomplete(Status::SubCode::kManualCompactionPaused);
  1791. });
  1792. SyncPoint::GetInstance()->EnableProcessing();
  1793. // Phase 1: Run compaction with resumption enabled and cancel it
  1794. // - Processes all input keys
  1795. // - Creates output files and saves progress
  1796. // - Status overridden to "paused"
  1797. open_and_compaction_options.allow_resumption = true;
  1798. auto phase1_stats =
  1799. RunCancelledCompaction(open_and_compaction_options, scheduled_job_id,
  1800. compaction_input, override_options);
  1801. HistogramData phase2_stats;
  1802. if (scenario_ == TestScenario::kMultipleCancelToggleResumption) {
  1803. // Phase 2: Run compaction WITHOUT resumption (fresh start) and cancel it
  1804. // - Delete all files left behind Phase 1 before calling OpenAndCompact()
  1805. // - Processes all input keys again from scratch
  1806. // - Creates output files but does NOT save progress
  1807. // - Status overridden to "paused"
  1808. open_and_compaction_options.allow_resumption = false;
  1809. // Clean up output folder for fresh start
  1810. std::string output_dir = GetOutputPath(scheduled_job_id);
  1811. Status cleanup_status = DestroyDir(override_options.env, output_dir);
  1812. EXPECT_TRUE(cleanup_status.ok());
  1813. EXPECT_OK(override_options.env->CreateDir(output_dir));
  1814. phase2_stats =
  1815. RunCancelledCompaction(open_and_compaction_options, scheduled_job_id,
  1816. compaction_input, override_options);
  1817. // Validation: Phase 2 starts from scratch, so it processes the same
  1818. // input keys as Phase 1.
  1819. // ASSUMPTION: With fixed input (10 keys) and deterministic cancellation
  1820. // (after processing), both phases create the same number of output files.
  1821. EXPECT_EQ(phase2_stats.count, phase1_stats.count);
  1822. }
  1823. SyncPoint::GetInstance()->ClearCallBack(
  1824. "DBImplSecondary::CompactWithoutInstallation::End");
  1825. // Final phase: Run compaction to completion (no cancellation)
  1826. if (scenario_ == TestScenario::kMultipleCancelToggleResumption) {
  1827. // Attempt to resume but it ends up starting fresh
  1828. open_and_compaction_options.allow_resumption = true;
  1829. } else if (scenario_ == TestScenario::kCancelThenResume) {
  1830. // Resume from Phase 1's saved progress
  1831. open_and_compaction_options.allow_resumption = true;
  1832. } else { // kCancelThenFreshStart
  1833. // Start fresh without resumption
  1834. open_and_compaction_options.allow_resumption = false;
  1835. // Clean up output folder for fresh start
  1836. std::string output_dir = GetOutputPath(scheduled_job_id);
  1837. Status cleanup_status = DestroyDir(override_options.env, output_dir);
  1838. EXPECT_TRUE(cleanup_status.ok());
  1839. EXPECT_OK(override_options.env->CreateDir(output_dir));
  1840. }
  1841. auto final_phase_stats =
  1842. RunCompaction(open_and_compaction_options, scheduled_job_id,
  1843. compaction_input, override_options, result);
  1844. SyncPoint::GetInstance()->DisableProcessing();
  1845. SyncPoint::GetInstance()->ClearAllCallBacks();
  1846. // Validate statistics based on scenario
  1847. if (scenario_ == TestScenario::kMultipleCancelToggleResumption) {
  1848. // ASSUMPTION: Phase 1 processes all keys before cancellation
  1849. EXPECT_GT(phase1_stats.count, 0);
  1850. // ASSUMPTION: Phase 2 runs with allow_resumption=false and an empty
  1851. // folder. Phase 2 then creates its own output files (but doesn't save
  1852. // progress). When Phase 3 starts with allow_resumption=true, it finds no
  1853. // progress file exists, so it cannot resume and must start from scratch,
  1854. // processing all input keys again.
  1855. // Result: Phase 3 does the same amount of work as Phase 1.
  1856. EXPECT_EQ(final_phase_stats.count, phase1_stats.count);
  1857. } else if (scenario_ == TestScenario::kCancelThenResume) {
  1858. // ASSUMPTION: Phase 1 processes all keys before cancellation
  1859. EXPECT_GT(phase1_stats.count, 0);
  1860. // ASSUMPTION: Phase 1 processes all keys and saves progress before
  1861. // cancellation. Final phase resumes from Phase 1's saved progress.
  1862. // Since Phase 1 completed all processing before being cancelled, the
  1863. // final phase should do less work than Phase 1.
  1864. EXPECT_LT(final_phase_stats.count, phase1_stats.count);
  1865. } else { // kCancelThenFreshStart
  1866. // ASSUMPTION: Phase 1 processes all keys before cancellation
  1867. EXPECT_GT(phase1_stats.count, 0);
  1868. // ASSUMPTION: Final phase starts fresh without resumption, so it
  1869. // processes all input keys again and creates the same number of files
  1870. EXPECT_EQ(final_phase_stats.count, phase1_stats.count);
  1871. }
  1872. StoreResult(*result);
  1873. return CompactionServiceJobStatus::kSuccess;
  1874. }
  1875. private:
  1876. std::string ExtractCompactionInput(const std::string& scheduled_job_id) {
  1877. InstrumentedMutexLock l(&mutex_);
  1878. auto job_index = jobs_.find(scheduled_job_id);
  1879. if (job_index == jobs_.end()) {
  1880. return "";
  1881. }
  1882. std::string compaction_input = std::move(job_index->second);
  1883. jobs_.erase(job_index);
  1884. auto info_index = infos_.find(scheduled_job_id);
  1885. if (info_index == infos_.end()) {
  1886. return "";
  1887. }
  1888. infos_.erase(info_index);
  1889. return compaction_input;
  1890. }
  1891. HistogramData RunCancelledCompaction(
  1892. const OpenAndCompactOptions& options, const std::string& scheduled_job_id,
  1893. const std::string& compaction_input,
  1894. const CompactionServiceOptionsOverride& override_options) {
  1895. std::string temp_result;
  1896. EXPECT_OK(statistics_->Reset());
  1897. Status s =
  1898. DB::OpenAndCompact(options, db_path_, GetOutputPath(scheduled_job_id),
  1899. compaction_input, &temp_result, override_options);
  1900. EXPECT_TRUE(s.IsManualCompactionPaused());
  1901. HistogramData stats;
  1902. statistics_->histogramData(FILE_WRITE_COMPACTION_MICROS, &stats);
  1903. return stats;
  1904. }
  1905. HistogramData RunCompaction(
  1906. const OpenAndCompactOptions& options, const std::string& scheduled_job_id,
  1907. const std::string& compaction_input,
  1908. const CompactionServiceOptionsOverride& override_options,
  1909. std::string* result) {
  1910. EXPECT_OK(statistics_->Reset());
  1911. Status s =
  1912. DB::OpenAndCompact(options, db_path_, GetOutputPath(scheduled_job_id),
  1913. compaction_input, result, override_options);
  1914. EXPECT_TRUE(s.ok());
  1915. HistogramData stats;
  1916. statistics_->histogramData(FILE_WRITE_COMPACTION_MICROS, &stats);
  1917. return stats;
  1918. }
  1919. void StoreResult(const std::string& result) {
  1920. InstrumentedMutexLock l(&mutex_);
  1921. result_ = result;
  1922. }
  1923. TestScenario scenario_;
  1924. };
  1925. class ResumableCompactionServiceTest : public CompactionServiceTest {
  1926. public:
  1927. explicit ResumableCompactionServiceTest() : CompactionServiceTest() {}
  1928. void RunCompactionCancelTest(
  1929. ResumableCompactionService::TestScenario scenario) {
  1930. Options options = CurrentOptions();
  1931. options.disable_auto_compactions = true;
  1932. std::shared_ptr<Statistics> statistics = CreateDBStatistics();
  1933. options.file_checksum_gen_factory = GetFileChecksumGenCrc32cFactory();
  1934. BlockBasedTableOptions table_options;
  1935. table_options.verify_compression = true;
  1936. options.table_factory.reset(NewBlockBasedTableFactory(table_options));
  1937. auto resume_cs = std::make_shared<ResumableCompactionService>(
  1938. dbname_, options, statistics, scenario);
  1939. options.compaction_service = resume_cs;
  1940. DestroyAndReopen(options);
  1941. GenerateTestData();
  1942. ASSERT_OK(statistics->Reset());
  1943. CompactRangeOptions cro;
  1944. cro.bottommost_level_compaction = BottommostLevelCompaction::kForce;
  1945. Status s = db_->CompactRange(cro, nullptr, nullptr);
  1946. ASSERT_OK(s);
  1947. VerifyTestData();
  1948. s = db_->VerifyChecksum();
  1949. ASSERT_OK(s);
  1950. s = db_->VerifyFileChecksums(ReadOptions());
  1951. ASSERT_OK(s);
  1952. CompactionServiceResult result;
  1953. resume_cs->GetResult(&result);
  1954. ASSERT_OK(result.status);
  1955. ASSERT_TRUE(result.stats.is_manual_compaction);
  1956. ASSERT_TRUE(result.stats.is_remote_compaction);
  1957. ASSERT_GT(result.output_files.size(), 0);
  1958. uint64_t resumed_bytes =
  1959. statistics->getTickerCount(REMOTE_COMPACT_RESUMED_BYTES);
  1960. if (scenario ==
  1961. ResumableCompactionService::TestScenario::kCancelThenResume) {
  1962. // When resuming compaction, some bytes should be resumed from previous
  1963. // progress
  1964. ASSERT_GT(resumed_bytes, 0);
  1965. } else if (scenario == ResumableCompactionService::TestScenario::
  1966. kCancelThenFreshStart) {
  1967. // When starting fresh (ignoring existing progress), no bytes should be
  1968. // resumed
  1969. ASSERT_EQ(resumed_bytes, 0);
  1970. } else { // kMultipleCancelToggleResumption
  1971. // Phase 2 ran without resumption (fresh start), so Phase 3 has no
  1972. // progress to resume from. It processes all keys again from scratch.
  1973. ASSERT_EQ(resumed_bytes, 0);
  1974. }
  1975. }
  1976. void GenerateTestData() {
  1977. for (int i = 0; i < kNumKeys; ++i) {
  1978. ASSERT_OK(Put(Key(i), "value"));
  1979. ASSERT_OK(Flush());
  1980. if (i % 2 == 0) {
  1981. ASSERT_OK(Delete(Key(i)));
  1982. ASSERT_OK(Flush());
  1983. }
  1984. }
  1985. }
  1986. void VerifyTestData() {
  1987. for (int i = 0; i < kNumKeys; ++i) {
  1988. if (i % 2 == 0) {
  1989. ASSERT_EQ("NOT_FOUND", Get((Key(i))));
  1990. } else {
  1991. ASSERT_EQ("value", Get((Key(i))));
  1992. }
  1993. }
  1994. }
  1995. private:
  1996. static constexpr int kNumKeys = 10;
  1997. };
  1998. TEST_F(ResumableCompactionServiceTest, CompactionCancelThenResume) {
  1999. RunCompactionCancelTest(
  2000. ResumableCompactionService::TestScenario::kCancelThenResume);
  2001. }
  2002. TEST_F(ResumableCompactionServiceTest, CompactionCancelThenFreshStart) {
  2003. RunCompactionCancelTest(
  2004. ResumableCompactionService::TestScenario::kCancelThenFreshStart);
  2005. }
  2006. TEST_F(ResumableCompactionServiceTest,
  2007. CompactionMultipleCancelToggleResumption) {
  2008. RunCompactionCancelTest(ResumableCompactionService::TestScenario::
  2009. kMultipleCancelToggleResumption);
  2010. }
  2011. } // namespace ROCKSDB_NAMESPACE
  2012. int main(int argc, char** argv) {
  2013. ROCKSDB_NAMESPACE::port::InstallStackTraceHandler();
  2014. ::testing::InitGoogleTest(&argc, argv);
  2015. RegisterCustomObjects(argc, argv);
  2016. return RUN_ALL_TESTS();
  2017. }