diff --git a/src/db/collection.cc b/src/db/collection.cc index 165e8b7..d6900dd 100644 --- a/src/db/collection.cc +++ b/src/db/collection.cc @@ -238,6 +238,13 @@ class CollectionImpl : public Collection { mutable std::shared_mutex schema_handle_mtx_; mutable std::shared_mutex write_mtx_; + // Serializes maintenance operations (Optimize, schema DDL, Close and + // Destroy) without holding schema_handle_mtx_, so a maintenance + // operation waiting for a running Optimize never becomes a pending + // exclusive acquirer of the schema lock (which would block new readers). + // Lock order: maintenance -> schema -> write -> SegmentManager; never + // acquire maintenance_mtx_ after any of the others. + mutable std::mutex maintenance_mtx_; std::atomic segment_id_allocator_; std::atomic tmp_segment_id_allocator_; @@ -330,6 +337,7 @@ Status CollectionImpl::Open(const CollectionOptions &options) { Status CollectionImpl::Close() { // only called in deconstructor + std::lock_guard maintenance_lock(maintenance_mtx_); std::lock_guard lock(schema_handle_mtx_); CHECK_DESTROY_RETURN_STATUS(destroyed_, false); @@ -363,6 +371,7 @@ Status CollectionImpl::close_unsafe() { Status CollectionImpl::Destroy() { CHECK_COLLECTION_READONLY_RETURN_STATUS; + std::lock_guard maintenance_lock(maintenance_mtx_); std::lock_guard lock(schema_handle_mtx_); CHECK_DESTROY_RETURN_STATUS(destroyed_, false); @@ -380,6 +389,9 @@ Status CollectionImpl::Destroy() { Status CollectionImpl::Flush() { CHECK_COLLECTION_READONLY_RETURN_STATUS; + // Only flushes the writing segment's WAL (no schema/segment-structure + // change), so it needs neither maintenance_mtx_ nor exclusion from a + // running Optimize. std::lock_guard lock(schema_handle_mtx_); CHECK_DESTROY_RETURN_STATUS(destroyed_, false); @@ -462,6 +474,7 @@ Status CollectionImpl::CreateIndex(const std::string &column_name, const CreateIndexOptions &options) { CHECK_COLLECTION_READONLY_RETURN_STATUS; + std::lock_guard maintenance_lock(maintenance_mtx_); std::lock_guard lock(schema_handle_mtx_); CHECK_DESTROY_RETURN_STATUS(destroyed_, false); @@ -650,6 +663,7 @@ Status CollectionImpl::execute_tasks( Status CollectionImpl::DropIndex(const std::string &column_name) { CHECK_COLLECTION_READONLY_RETURN_STATUS; + std::lock_guard maintenance_lock(maintenance_mtx_); std::lock_guard lock(schema_handle_mtx_); CHECK_DESTROY_RETURN_STATUS(destroyed_, false); @@ -779,20 +793,20 @@ std::vector CollectionImpl::build_drop_scalar_index_task( Status CollectionImpl::Optimize(const OptimizeOptions &options) { CHECK_COLLECTION_READONLY_RETURN_STATUS; - std::lock_guard lock(schema_handle_mtx_); - // when optimizing, schema operations(include another optimize) are not - // allowed - - CHECK_DESTROY_RETURN_STATUS(destroyed_, false); + // Serialize against other maintenance operations for the whole optimize. + std::lock_guard maintenance_lock(maintenance_mtx_); std::vector persist_segments; + // Phase 1: exclusively seal the current writing segment and snapshot + // the persisted segment set. { - // forbidden writing for a while + std::unique_lock schema_lock(schema_handle_mtx_); std::lock_guard write_lock(write_mtx_); + CHECK_DESTROY_RETURN_STATUS(destroyed_, false); + if (writing_segment_->has_record()) { - // Flush pending records and switch only when the segment contains docs. auto s = switch_to_new_segment_for_writing(); if (!s.ok()) { return s; @@ -801,15 +815,13 @@ Status CollectionImpl::Optimize(const OptimizeOptions &options) { persist_segments = get_all_persist_segments(); // will not return writing segment - // after leave this scope, writing action is allowed } if (persist_segments.size() == 0) { - // no need to optimize return Status::OK(); } - // build segment compact task + // Phase 2: lock-free compact. Readers and writers proceed freely. auto delete_store_clone = delete_store_->clone(); auto tasks = build_compact_task(schema_, persist_segments, options.concurrency_, @@ -819,9 +831,56 @@ Status CollectionImpl::Optimize(const OptimizeOptions &options) { auto s = execute_compact_task(tasks); CHECK_RETURN_STATUS(s); + // End of phase 2 (still lock-free): move built tmp segments to their + // final paths and open them before the manifest is persisted, so a + // failure aborts cleanly without a version/disk mismatch. + std::vector opened_segments; + std::vector moved_dirs; + auto cleanup_moved_dirs = [&]() { + for (auto &dir : moved_dirs) { + FileHelper::RemoveDirectory(dir); + } + }; + for (auto &task : tasks) { + auto task_info = task->task_info(); + if (!std::holds_alternative(task_info)) { + continue; + } + auto compact_task = std::get(task_info); + if (!compact_task.output_segment_meta_) { + continue; + } + + auto tmp_segment_path = + FileHelper::MakeTempSegmentPath(path_, compact_task.output_segment_id_); + auto new_segment_id = allocate_segment_id(); + auto new_segment_path = FileHelper::MakeSegmentPath(path_, new_segment_id); + + if (!FileHelper::MoveDirectory(tmp_segment_path, new_segment_path)) { + cleanup_moved_dirs(); + return Status::InternalError("move segment directory failed"); + } + moved_dirs.push_back(new_segment_path); + compact_task.output_segment_meta_->set_id(new_segment_id); + + auto new_segment = + Segment::Open(path_, *schema_, *compact_task.output_segment_meta_, + id_map_, delete_store_, version_manager_, + SegmentOptions{true, options_.enable_mmap_}); + if (!new_segment.has_value()) { + // best-effort cleanup: these directories are not referenced by any + // manifest yet, so remove them rather than leaking them on disk + cleanup_moved_dirs(); + return new_segment.error(); + } + opened_segments.push_back(new_segment.value()); + } + + // Phase 3: short exclusive commit. No readers can be using the old + // indexers — they all hold the shared schema lock — so in-place + // reload_vector_index() is safe. { - // forbidden writing for updating version - // writing action may trigger updating version where confict occurs + std::unique_lock schema_lock(schema_handle_mtx_); std::lock_guard write_lock(write_mtx_); Version new_version = version_manager_->get_current_version(); @@ -832,24 +891,7 @@ Status CollectionImpl::Optimize(const OptimizeOptions &options) { if (std::holds_alternative(task_info)) { auto compact_task = std::get(task_info); - // 0. check if has output segment meta if (compact_task.output_segment_meta_) { - // 1. rename built tmp segments - auto tmp_segment_id = compact_task.output_segment_id_; - auto tmp_segment_path = - FileHelper::MakeTempSegmentPath(path_, tmp_segment_id); - - auto new_segment_id = allocate_segment_id(); - auto new_segment_path = - FileHelper::MakeSegmentPath(path_, new_segment_id); - - if (!FileHelper::MoveDirectory(tmp_segment_path, new_segment_path)) { - return Status::InternalError("move segment directory failed"); - } - - // update output_segment_meta_'s segment id - compact_task.output_segment_meta_->set_id(new_segment_id); - s = new_version.add_persisted_segment_meta( compact_task.output_segment_meta_); CHECK_RETURN_STATUS(s); @@ -868,15 +910,15 @@ Status CollectionImpl::Optimize(const OptimizeOptions &options) { } } - // 2. update version s = version_manager_->apply(new_version); CHECK_RETURN_STATUS(s); - // 3. persist version s = version_manager_->flush(); CHECK_RETURN_STATUS(s); - // 4. remove old segments or block + // publish new segments, retire compacted inputs and reload rebuilt + // vector indexes + size_t opened_index = 0; for (auto &task : tasks) { auto task_info = task->task_info(); @@ -884,14 +926,10 @@ Status CollectionImpl::Optimize(const OptimizeOptions &options) { auto compact_task = std::get(task_info); if (compact_task.output_segment_meta_) { - auto new_segment = - Segment::Open(path_, *schema_, *compact_task.output_segment_meta_, - id_map_, delete_store_, version_manager_, - SegmentOptions{true, options_.enable_mmap_}); - if (!new_segment.has_value()) { - return new_segment.error(); + if (opened_index >= opened_segments.size()) { + return Status::InternalError("opened_segments index out of bounds"); } - s = segment_manager_->add_segment(new_segment.value()); + s = segment_manager_->add_segment(opened_segments[opened_index++]); CHECK_RETURN_STATUS(s); } @@ -1136,6 +1174,7 @@ Status CollectionImpl::AddColumn(const FieldSchema::Ptr &column_schema, const AddColumnOptions &options) { CHECK_COLLECTION_READONLY_RETURN_STATUS; + std::lock_guard maintenance_lock(maintenance_mtx_); std::lock_guard lock(schema_handle_mtx_); CHECK_DESTROY_RETURN_STATUS(destroyed_, false); @@ -1208,6 +1247,7 @@ Status CollectionImpl::AddColumn(const FieldSchema::Ptr &column_schema, Status CollectionImpl::DropColumn(const std::string &column_name) { CHECK_COLLECTION_READONLY_RETURN_STATUS; + std::lock_guard maintenance_lock(maintenance_mtx_); std::lock_guard lock(schema_handle_mtx_); CHECK_DESTROY_RETURN_STATUS(destroyed_, false); @@ -1282,6 +1322,7 @@ Status CollectionImpl::AlterColumn(const std::string &column_name, const AlterColumnOptions &options) { CHECK_COLLECTION_READONLY_RETURN_STATUS; + std::lock_guard maintenance_lock(maintenance_mtx_); std::lock_guard lock(schema_handle_mtx_); CHECK_DESTROY_RETURN_STATUS(destroyed_, false); diff --git a/src/db/index/segment/segment_manager.cc b/src/db/index/segment/segment_manager.cc index 7fb3e7a..f0a6e46 100644 --- a/src/db/index/segment/segment_manager.cc +++ b/src/db/index/segment/segment_manager.cc @@ -28,11 +28,13 @@ Status SegmentManager::add_segment(Segment::Ptr segment) { return Status::InvalidArgument("Segment is null"); } + std::unique_lock lock(mutex_); segments_map_[segment->id()] = segment; return Status::OK(); } Status SegmentManager::remove_segment(SegmentID segment_id) { + std::unique_lock lock(mutex_); auto iter = segments_map_.find(segment_id); if (iter == segments_map_.end()) { return Status::NotFound("Segment not found"); @@ -43,6 +45,7 @@ Status SegmentManager::remove_segment(SegmentID segment_id) { } Status SegmentManager::destroy_segment(SegmentID segment_id) { + std::unique_lock lock(mutex_); auto iter = segments_map_.find(segment_id); if (iter == segments_map_.end()) { return Status::NotFound("Segment not found"); @@ -51,14 +54,17 @@ Status SegmentManager::destroy_segment(SegmentID segment_id) { auto s = iter->second->destroy(); CHECK_RETURN_STATUS(s); - segments_map_.erase(segment_id); + segments_map_.erase(iter); return Status::OK(); } std::vector SegmentManager::get_segments() const { std::vector segments; - for (auto &pair : segments_map_) { - segments.push_back(pair.second); + { + std::shared_lock lock(mutex_); + for (auto &pair : segments_map_) { + segments.push_back(pair.second); + } } std::sort(segments.begin(), segments.end(), [](Segment::Ptr a, Segment::Ptr b) { @@ -69,8 +75,11 @@ std::vector SegmentManager::get_segments() const { std::vector SegmentManager::get_segments_meta() const { std::vector segments_meta; - for (auto &pair : segments_map_) { - segments_meta.push_back(pair.second->meta()); + { + std::shared_lock lock(mutex_); + for (auto &pair : segments_map_) { + segments_meta.push_back(pair.second->meta()); + } } std::sort(segments_meta.begin(), segments_meta.end(), @@ -89,17 +98,21 @@ Status SegmentManager::add_column(const FieldSchema::Ptr &column_schema, } std::vector> futures; - std::vector> segments( - segments_map_.begin(), segments_map_.end()); + std::vector> segments; + { + std::shared_lock lock(mutex_); + segments.assign(segments_map_.begin(), segments_map_.end()); + } for (size_t i = 0; i < segments.size(); i += concurrency) { size_t end = std::min(i + concurrency, segments.size()); for (size_t j = i; j < end; ++j) { auto &segment = segments[j].second; - futures.emplace_back(std::async(std::launch::async, [&]() -> Status { - return segment->add_column(column_schema, expression, - AddColumnOptions{concurrency}); - })); + futures.emplace_back( + std::async(std::launch::async, [&, segment]() -> Status { + return segment->add_column(column_schema, expression, + AddColumnOptions{concurrency}); + })); } for (auto it = futures.begin(); it != futures.end(); ++it) { @@ -122,17 +135,21 @@ Status SegmentManager::alter_column(const std::string &column_name, } std::vector> futures; - std::vector> segments( - segments_map_.begin(), segments_map_.end()); + std::vector> segments; + { + std::shared_lock lock(mutex_); + segments.assign(segments_map_.begin(), segments_map_.end()); + } for (size_t i = 0; i < segments.size(); i += concurrency) { size_t end = std::min(i + concurrency, segments.size()); for (size_t j = i; j < end; ++j) { auto &segment = segments[j].second; - futures.emplace_back(std::async(std::launch::async, [&]() -> Status { - return segment->alter_column(column_name, new_column_schema, - AlterColumnOptions{concurrency}); - })); + futures.emplace_back( + std::async(std::launch::async, [&, segment]() -> Status { + return segment->alter_column(column_name, new_column_schema, + AlterColumnOptions{concurrency}); + })); } for (auto it = futures.begin(); it != futures.end(); ++it) { @@ -148,7 +165,15 @@ Status SegmentManager::alter_column(const std::string &column_name, } Status SegmentManager::drop_column(const std::string &column_name) { - for (auto &[segment_id, segment] : segments_map_) { + std::vector segments; + { + std::shared_lock lock(mutex_); + for (auto &pair : segments_map_) { + segments.push_back(pair.second); + } + } + + for (auto &segment : segments) { auto s = segment->drop_column(column_name); CHECK_RETURN_STATUS(s); } diff --git a/src/db/index/segment/segment_manager.h b/src/db/index/segment/segment_manager.h index 9af2ac4..ae28517 100644 --- a/src/db/index/segment/segment_manager.h +++ b/src/db/index/segment/segment_manager.h @@ -13,6 +13,7 @@ // limitations under the License. #pragma once +#include #include #include #include "segment.h" @@ -27,6 +28,7 @@ class SegmentManager { public: uint32_t segment_count() const { + std::shared_lock lock(mutex_); return segments_map_.size(); } @@ -50,6 +52,10 @@ class SegmentManager { Status drop_column(const std::string &column_name); private: + // protects segments_map_ against concurrent readers (e.g. queries + // collecting segments) while segments are added/removed by writes, + // optimize or DDL operations + mutable std::shared_mutex mutex_; std::unordered_map segments_map_; }; } // namespace zvec \ No newline at end of file diff --git a/tests/db/collection_test.cc b/tests/db/collection_test.cc index f98ef44..5d9a3e4 100644 --- a/tests/db/collection_test.cc +++ b/tests/db/collection_test.cc @@ -14,6 +14,8 @@ #include "zvec/db/collection.h" #include +#include +#include #include #include #include @@ -23,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -2917,6 +2920,250 @@ TEST_F(CollectionTest, Feature_Optimize_General) { } } +TEST_F(CollectionTest, Feature_Optimize_Concurrent_ReadWrite_NonBlocking) { + // Regression: Optimize() no longer blocks writes/reads for its whole + // duration. Insert, Fetch and Query must all make progress during the + // long compact phase; only the seal/commit phases are exclusive. + int initial_doc_count = 20000; + + auto schema = TestHelper::CreateSchemaWithVectorIndex(); + auto options = CollectionOptions{false, true, 64 * 1024 * 1024}; + auto collection = TestHelper::CreateCollectionWithDoc( + col_path, *schema, options, 0, initial_doc_count, false); + ASSERT_NE(collection, nullptr); + ASSERT_TRUE(collection->Flush().ok()); + + std::atomic optimize_done{false}; + Status optimize_status; + std::thread optimizer([&] { + optimize_status = collection->Optimize(OptimizeOptions{0}); + optimize_done.store(true); + }); + + // let the optimizer reach the compact phase + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + + // worker failures are collected here and asserted after joins + struct WorkerResult { + int ops_during_optimize{0}; + int errors{0}; + std::string first_error; + }; + + auto record_error = [](WorkerResult *r, const std::string &msg) { + if (r->errors++ == 0) { + r->first_error = msg; + } + }; + + // writer: keeps inserting batches while Optimize is running + WorkerResult writer_result; + int batch_size = 100; + int inserted = 0; + uint64_t next_doc_id = initial_doc_count; + std::thread writer([&] { + while (!optimize_done.load() && inserted < 100000) { + bool started_during_optimize = !optimize_done.load(); + std::vector docs; + for (int i = 0; i < batch_size; i++) { + docs.push_back(TestHelper::CreateDoc(next_doc_id + i, *schema)); + } + auto res = collection->Insert(docs); + if (!res.has_value()) { + record_error(&writer_result, res.error().message()); + break; + } + for (auto &st : res.value()) { + if (!st.ok()) { + record_error(&writer_result, st.message()); + } + } + // advance only on full batch success + if (writer_result.errors == 0) { + next_doc_id += batch_size; + inserted += batch_size; + } else { + break; + } + if (started_during_optimize) { + writer_result.ops_during_optimize++; + } + } + }); + + // fetcher: point reads must return correct data throughout, including + // while Optimize commits its result + WorkerResult fetch_result; + std::thread fetcher([&] { + auto expect_doc = TestHelper::CreateDoc(0, *schema); + while (!optimize_done.load() && fetch_result.ops_during_optimize < 100000) { + bool started_during_optimize = !optimize_done.load(); + auto fetched = collection->Fetch({expect_doc.pk()}); + if (!fetched.has_value()) { + record_error(&fetch_result, fetched.error().message()); + break; + } + auto iter = fetched.value().find(expect_doc.pk()); + if (iter == fetched.value().end() || iter->second == nullptr || + *iter->second != expect_doc) { + record_error(&fetch_result, "fetched doc mismatch"); + } else if (started_during_optimize) { + fetch_result.ops_during_optimize++; + } + std::this_thread::yield(); + } + }); + + // querier: vector searches must keep succeeding while segments are being + // compacted + WorkerResult query_result; + std::thread querier([&] { + auto query_doc = TestHelper::CreateDoc(1, *schema); + auto vector = query_doc.get>("dense_fp32"); + if (!vector.has_value()) { + record_error(&query_result, "query vector missing"); + return; + } + while (!optimize_done.load() && query_result.ops_during_optimize < 100000) { + bool started_during_optimize = !optimize_done.load(); + SearchQuery query; + query.topk_ = 10; + query.target_.field_name_ = "dense_fp32"; + query.target_.set_vector( + std::string(reinterpret_cast(vector.value().data()), + vector.value().size() * sizeof(float))); + auto result = collection->Query(query); + if (!result.has_value()) { + // Tolerate only the known transient failure: a doc admitted by + // the writing segment's streaming vector index may not yet be + // visible in its forward store (pre-existing Insert/Query race, + // unrelated to Optimize). Any other error is a real regression. + const auto &error_msg = result.error().message(); + if (error_msg.find("fetch table failed") == std::string::npos) { + record_error(&query_result, error_msg); + break; + } + continue; + } + if (result.value().empty()) { + record_error(&query_result, "query returned no results"); + } else if (started_during_optimize) { + query_result.ops_during_optimize++; + } + std::this_thread::yield(); + } + }); + + optimizer.join(); + writer.join(); + fetcher.join(); + querier.join(); + + ASSERT_TRUE(optimize_status.ok()); + ASSERT_EQ(writer_result.errors, 0) << writer_result.first_error; + ASSERT_EQ(fetch_result.errors, 0) << fetch_result.first_error; + ASSERT_EQ(query_result.errors, 0) << query_result.first_error; + + // if any had been blocked for the whole Optimize, no ops could have + // completed while Optimize was still running + ASSERT_GE(writer_result.ops_during_optimize, 2); + ASSERT_GE(fetch_result.ops_during_optimize, 2); + ASSERT_GE(query_result.ops_during_optimize, 2); + + auto stats_result = collection->Stats(); + ASSERT_TRUE(stats_result.has_value()); + auto stats = stats_result.value(); + ASSERT_EQ(stats.doc_count, (uint64_t)(initial_doc_count + inserted)); + + // once quiescent, a vector search must return the full topk + { + auto query_doc = TestHelper::CreateDoc(1, *schema); + auto vector = query_doc.get>("dense_fp32"); + ASSERT_TRUE(vector.has_value()); + SearchQuery query; + query.topk_ = 10; + query.target_.field_name_ = "dense_fp32"; + query.target_.set_vector( + std::string(reinterpret_cast(vector.value().data()), + vector.value().size() * sizeof(float))); + auto result = collection->Query(query); + ASSERT_TRUE(result.has_value()); + ASSERT_EQ(result.value().size(), (size_t)query.topk_); + } + + // spot-check data written before, during and after the optimize; docs + // beyond initial_doc_count only exist when the writer actually made + // progress during Optimize, so guard against a no-insert run + std::vector spot_check_ids{0, (uint64_t)initial_doc_count - 1}; + if (inserted > 0) { + spot_check_ids.push_back((uint64_t)initial_doc_count); + spot_check_ids.push_back(next_doc_id - 1); + } + for (uint64_t doc_id : spot_check_ids) { + auto expect_doc = TestHelper::CreateDoc(doc_id, *schema); + auto result = collection->Fetch({expect_doc.pk()}); + ASSERT_TRUE(result.has_value()); + ASSERT_EQ(result.value().count(expect_doc.pk()), 1); + auto doc = result.value()[expect_doc.pk()]; + ASSERT_NE(doc, nullptr); + ASSERT_EQ(*doc, expect_doc); + } +} + +TEST_F(CollectionTest, Feature_Optimize_Superseded_Index_File_Removed) { + namespace fs = std::filesystem; + int doc_count = 1000; + + auto schema = TestHelper::CreateSchemaWithVectorIndex(); + auto options = CollectionOptions{false, true, 64 * 1024 * 1024}; + auto collection = TestHelper::CreateCollectionWithDoc( + col_path, *schema, options, 0, doc_count, false); + ASSERT_NE(collection, nullptr); + ASSERT_TRUE(collection->Flush().ok()); + + ASSERT_TRUE(collection->Optimize(OptimizeOptions{0}).ok()); + + auto stats_result = collection->Stats(); + ASSERT_TRUE(stats_result.has_value()); + auto stats = stats_result.value(); + ASSERT_EQ(stats.doc_count, (uint64_t)doc_count); + ASSERT_EQ(stats.index_completeness["dense_fp32"], 1); + + // Vector index build supersedes the flat vector file from the segment + // dump. The commit phase eagerly removes the superseded file under the + // exclusive schema lock, leaving exactly one index file per column. + // Walk all segment directories (segment ids are an implementation + // detail) instead of assuming the persisted segment lives in "/0". + int dense_fp32_index_files = 0; + for (const auto &entry : fs::recursive_directory_iterator(col_path)) { + if (!entry.is_regular_file()) { + continue; + } + auto name = entry.path().filename().string(); + if (name.rfind("dense_fp32.index.", 0) == 0) { + dense_fp32_index_files++; + } + } + ASSERT_EQ(dense_fp32_index_files, 1); + + // the removed file must not be one the collection still needs: a fresh + // open must read every doc correctly through the new index + collection.reset(); + auto result = Collection::Open(col_path, options); + ASSERT_TRUE(result.has_value()); + collection = std::move(result.value()); + + for (int i : {0, doc_count / 2, doc_count - 1}) { + auto expect_doc = TestHelper::CreateDoc(i, *schema); + auto fetched = collection->Fetch({expect_doc.pk()}); + ASSERT_TRUE(fetched.has_value()); + ASSERT_EQ(fetched.value().count(expect_doc.pk()), 1); + auto doc = fetched.value()[expect_doc.pk()]; + ASSERT_NE(doc, nullptr); + ASSERT_EQ(*doc, expect_doc); + } +} + TEST_F(CollectionTest, Feature_Optimize_Repeated) { auto run_repeated_optimize_test = [&](bool enable_mmap, IndexParams::Ptr index_params) {