diff --git a/src/turtle_kv/core/merge_compactor.test.cpp b/src/turtle_kv/core/merge_compactor.test.cpp index 6474f53..32f1f0c 100644 --- a/src/turtle_kv/core/merge_compactor.test.cpp +++ b/src/turtle_kv/core/merge_compactor.test.cpp @@ -666,4 +666,4 @@ TEST_F(ResultSetConcatTest, ConcatDeath) "the second ResultSet!"); } -} // namespace \ No newline at end of file +} // namespace diff --git a/src/turtle_kv/tree/algo/segmented_levels.hpp b/src/turtle_kv/tree/algo/segmented_levels.hpp index f44e0a9..f8871a8 100644 --- a/src/turtle_kv/tree/algo/segmented_levels.hpp +++ b/src/turtle_kv/tree/algo/segmented_levels.hpp @@ -282,15 +282,22 @@ struct SegmentedLevelAlgorithms { return OkStatus(); } - /** \brief Merges the two given pivots, effectively erasing `right_pivot`. + /** \brief Merges the two given pivots, effectively erasing `right_pivot`. */ void merge_pivots(i32 left_pivot, i32 right_pivot) { const usize segment_count = this->level_.segment_count(); - for (usize segment_i = 0; segment_i < segment_count; ++segment_i) { + for (usize segment_i = 0; segment_i < segment_count;) { SegmentT& segment = this->level_.get_segment(segment_i); + in_segment(segment).merge_pivots(left_pivot, right_pivot, this->level_); + + if (segment.is_inactive()) { + this->level_.drop_segment(segment_i); + } else { + ++segment_i; + } } } diff --git a/src/turtle_kv/tree/in_memory_leaf.cpp b/src/turtle_kv/tree/in_memory_leaf.cpp index 081d2e6..df49135 100644 --- a/src/turtle_kv/tree/in_memory_leaf.cpp +++ b/src/turtle_kv/tree/in_memory_leaf.cpp @@ -6,10 +6,54 @@ #include #include +#include #include namespace turtle_kv { +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +/*static*/ std::unique_ptr InMemoryLeaf::unpack( + llfs::PinnedPage&& pinned_leaf_page, + const TreeOptions& tree_options, + const PackedLeafPage& packed_leaf, + batt::WorkerPool& worker_pool) noexcept +{ + std::unique_ptr new_leaf = + std::make_unique(batt::make_copy(pinned_leaf_page), tree_options); + + Slice packed_items = packed_leaf.items_slice(); + std::vector buffer; + buffer.reserve(packed_items.size()); + + { + batt::ScopedWorkContext context{worker_pool}; + + const ParallelAlgoDefaults& algo_defaults = parallel_algo_defaults(); + const batt::TaskCount max_tasks{worker_pool.size() + 1}; + + batt::parallel_transform( + context, + packed_items.begin(), + packed_items.end(), + buffer.data(), + [](const PackedKeyValue& pkv) -> EditView { + return to_edit_view(pkv); + }, + /*min_task_size = */ algo_defaults.copy_edits.min_task_size, + /*max_tasks = */ max_tasks); + } + + MergeCompactor::ResultSet result_set; + const ItemView* first_edit = (const ItemView*)buffer.data(); + result_set.append(std::move(buffer), as_slice(first_edit, packed_items.size())); + new_leaf->result_set = std::move(result_set); + + new_leaf->set_edit_size_totals(compute_running_total(worker_pool, *(new_leaf->result_set))); + + return {std::move(new_leaf)}; +} + //==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - // SubtreeViability InMemoryLeaf::get_viability() @@ -17,7 +61,9 @@ SubtreeViability InMemoryLeaf::get_viability() const usize total_size = this->get_items_size(); if (total_size < this->tree_options.flush_size() / 4) { - return NeedsMerge{}; + NeedsMerge needs_merge; + needs_merge.zero_items = (total_size == 0); + return needs_merge; } else if (total_size > this->tree_options.flush_size()) { return NeedsSplit{}; } else { @@ -152,6 +198,44 @@ auto InMemoryLeaf::make_split_plan() const -> StatusOr return plan; } +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +Status InMemoryLeaf::try_merge(BatchUpdateContext& context, + std::unique_ptr sibling) noexcept +{ + BATT_CHECK(this->result_set); + BATT_CHECK(sibling->result_set); + + if (sibling->result_set->empty()) { + BATT_CHECK(batt::is_case(this->get_viability())) + << "Sibling leaf is not viable, so this leaf must be viable!"; + return OkStatus(); + } + + if (this->result_set->empty()) { + BATT_CHECK(batt::is_case(sibling->get_viability())) + << "This leaf is not viable, so sibling leaf must be viable!"; + this->pinned_leaf_page_ = std::move(sibling->pinned_leaf_page_); + this->result_set = std::move(sibling->result_set); + this->shared_edit_size_totals_ = sibling->shared_edit_size_totals_; + this->edit_size_totals = std::move(sibling->edit_size_totals); + return OkStatus(); + } + + BATT_CHECK_LT(this->get_max_key(), sibling->get_min_key()); + + this->result_set = MergeCompactor::ResultSet::concat(std::move(*this->result_set), + std::move(*(sibling->result_set))); + + this->set_edit_size_totals(context.compute_running_total(*this->result_set)); + + // Retain a pin on the sibling's leaf page. + // + this->sibling_pages_.emplace_back(std::move(sibling->pinned_leaf_page_)); + + return OkStatus(); +} + //==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - // Status InMemoryLeaf::apply_batch_update(BatchUpdate& update) noexcept diff --git a/src/turtle_kv/tree/in_memory_leaf.hpp b/src/turtle_kv/tree/in_memory_leaf.hpp index 9c96efa..0e25465 100644 --- a/src/turtle_kv/tree/in_memory_leaf.hpp +++ b/src/turtle_kv/tree/in_memory_leaf.hpp @@ -32,6 +32,7 @@ struct InMemoryLeaf { //+++++++++++-+-+--+----- --- -- - - - - llfs::PinnedPage pinned_leaf_page_; + SmallVec sibling_pages_; TreeOptions tree_options; Optional> result_set; std::shared_ptr shared_edit_size_totals_; @@ -40,6 +41,13 @@ struct InMemoryLeaf { //+++++++++++-+-+--+----- --- -- - - - - + static std::unique_ptr unpack(llfs::PinnedPage&& pinned_leaf_page, + const TreeOptions& tree_options, + const PackedLeafPage& packed_leaf, + batt::WorkerPool& worker_pool) noexcept; + + //+++++++++++-+-+--+----- --- -- - - - - + explicit InMemoryLeaf(llfs::PinnedPage&& pinned_leaf_page, const TreeOptions& tree_options_arg) noexcept : pinned_leaf_page_{std::move(pinned_leaf_page)} @@ -98,6 +106,8 @@ struct InMemoryLeaf { StatusOr make_split_plan() const; + Status try_merge(BatchUpdateContext& context, std::unique_ptr sibling) noexcept; + Status apply_batch_update(BatchUpdate& update) noexcept; Status start_serialize(TreeSerializeContext& context); diff --git a/src/turtle_kv/tree/in_memory_node.cpp b/src/turtle_kv/tree/in_memory_node.cpp index 839473f..536e0c3 100644 --- a/src/turtle_kv/tree/in_memory_node.cpp +++ b/src/turtle_kv/tree/in_memory_node.cpp @@ -23,11 +23,12 @@ namespace turtle_kv { namespace { using UpdateBuffer = InMemoryNode::UpdateBuffer; -using Level = UpdateBuffer::Level; -using EmptyLevel = UpdateBuffer::EmptyLevel; -using MergedLevel = UpdateBuffer::MergedLevel; -using SegmentedLevel = UpdateBuffer::SegmentedLevel; -using Segment = UpdateBuffer::Segment; +using Level = InMemoryNodeLevel; +using EmptyLevel = InMemoryNodeEmptyLevel; +using MergedLevel = InMemoryNodeMergedLevel; +using SegmentedLevel = InMemoryNodeSegmentedLevel; +using HybridLevel = InMemoryNodeHybridLevel; +using Segment = InMemoryNodeSegment; using PackedUpdateBuffer = PackedNodePage::UpdateBuffer; using PackedLevel = PackedUpdateBuffer::SegmentedLevel; @@ -55,7 +56,7 @@ using PackedSegment = PackedUpdateBuffer::Segment; node->children.resize(pivot_count); node->child_pages.resize(pivot_count); node->pending_bytes.resize(pivot_count); - node->pending_bytes_is_exact = 0; + node->pending_bytes_is_exact = {}; node->pivot_keys_.resize(pivot_count + 1); node->max_key_ = packed_node.max_key(); node->common_key_prefix = packed_node.common_key_prefix(); @@ -221,9 +222,12 @@ Status InMemoryNode::apply_batch_update(BatchUpdate& update, // BATT_REQUIRE_OK(this->update_buffer_insert(update)); - // Check for flush. + // Check for flush. If a flush is not necessary, batt::StatusCode::kUnavailable is returned. // - BATT_REQUIRE_OK(this->flush_if_necessary(update.context)); + Status flush_status = this->flush_if_necessary(update.context); + if (flush_status != OkStatus() && flush_status != batt::StatusCode::kUnavailable) { + return flush_status; + } // We don't need to check whether _this_ node needs to be split; the caller will take care of // that! @@ -357,6 +361,10 @@ Status InMemoryNode::flush_if_necessary(BatchUpdateContext& context, bool force_ // const MaxPendingBytes max_pending = this->find_max_pending(); + if (!max_pending.byte_count) { + return {batt::StatusCode::kUnavailable}; + } + const bool flush_needed = force_flush || // (max_pending.byte_count >= this->tree_options.min_flush_size()) || // this->has_too_many_tiers(); @@ -518,8 +526,8 @@ Status InMemoryNode::flush_to_pivot(BatchUpdateContext& update_context, i32 pivo BATT_REQUIRE_OK(this->set_pivot_completely_flushed(pivot_i, pivot_key_range)); BATT_CHECK_EQ(trim_result.n_bytes_trimmed, 0); this->pending_bytes[pivot_i] = 0; - this->pending_bytes_is_exact = set_bit(this->pending_bytes_is_exact, pivot_i, true); - BATT_CHECK_EQ(get_bit(this->pending_bytes_is_exact, pivot_i), true); + this->pending_bytes_is_exact.set(pivot_i, true); + BATT_CHECK_EQ(this->pending_bytes_is_exact.get(pivot_i), true); return OkStatus(); } @@ -540,8 +548,8 @@ Status InMemoryNode::flush_to_pivot(BatchUpdateContext& update_context, i32 pivo << BATT_INSPECT(trim_result.n_bytes_trimmed) << BATT_INSPECT(child_update.get_byte_size()); this->pending_bytes[pivot_i] = trim_result.n_bytes_trimmed; - this->pending_bytes_is_exact = set_bit(this->pending_bytes_is_exact, pivot_i, true); - BATT_CHECK_EQ(get_bit(this->pending_bytes_is_exact, pivot_i), true); + this->pending_bytes_is_exact.set(pivot_i, true); + BATT_CHECK_EQ(this->pending_bytes_is_exact.get(pivot_i), true); // Recursively apply batch update. // @@ -597,8 +605,7 @@ Status InMemoryNode::make_child_viable(BatchUpdateContext& update_context, i32 p //----- --- -- - - - - [&](const NeedsMerge&) -> Status { - BATT_PANIC() << "TODO [tastolfi 2025-03-16] implement me!"; - return batt::StatusCode::kUnimplemented; + return this->merge_child(update_context, pivot_i); }); return status; @@ -672,6 +679,13 @@ Status InMemoryNode::split_child(BatchUpdateContext& update_context, i32 pivot_i update_context.page_loader, update_context.overcommit) // .split_pivot(pivot_i, pivot_key_range, sibling_min_key); + }, + [&](HybridLevel& hybrid_level) -> Status { + return hybrid_level.split_pivot(*this, + update_context, + pivot_i, + pivot_key_range, + sibling_min_key); })); } @@ -698,8 +712,8 @@ Status InMemoryNode::split_child(BatchUpdateContext& update_context, i32 pivot_i // The pending bytes counts for this pivot and its new sibling are not exact. // - this->pending_bytes_is_exact = set_bit(this->pending_bytes_is_exact, pivot_i, false); - this->pending_bytes_is_exact = insert_bit(this->pending_bytes_is_exact, sibling_i, false); + this->pending_bytes_is_exact.set(pivot_i, false); + this->pending_bytes_is_exact.insert(sibling_i, false); this->pending_bytes.insert(this->pending_bytes.begin() + sibling_i, sibling_pending_bytes); @@ -717,6 +731,176 @@ Status InMemoryNode::split_child(BatchUpdateContext& update_context, i32 pivot_i return OkStatus(); } +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +Subtree InMemoryNode::shrink_or_panic() +{ + BATT_CHECK_EQ(this->children.size(), 1); + BATT_CHECK_EQ(this->pending_bytes.size(), 1); + // TODO [tastolfi 2026-05-04] CHECK that pending bytes is exact == true? + BATT_CHECK_EQ(this->pending_bytes[0], 0); + + for (const auto& level : this->update_buffer.levels) { + BATT_CHECK(batt::is_case(level)); + } + + return {std::move(this->children[0])}; +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +Status InMemoryNode::merge_child(BatchUpdateContext& update_context, i32 pivot_i) noexcept +{ + static Metrics& r_metrics = Self::metrics(); + + LatencyTimer timer{Every2ToTheConst<0>{}, r_metrics.merge_latency}; + + // If there are no siblings to merge with, we must be in the middle of collapsing the tree + // (flush and shrink). + // + if (this->pivot_count() == 1) { + return OkStatus(); + } + + // Decide which sibling to merge with. Edge cases: child that needs merge is the leftmost or + // rightmost child in the node. + // + i32 sibling_i = pivot_i; + + if ((usize)pivot_i == this->pivot_count() - 1) { + sibling_i = pivot_i - 1; + } else { + sibling_i = pivot_i + 1; + } + + BATT_REQUIRE_OK(this->children[sibling_i].unpack_if_necessary(update_context.page_loader, + update_context.overcommit, + update_context.worker_pool, + this->tree_options, + this->height - 1)); + + // Erase rightmost of {child subtree, sibling} in all metadata of the parent. + // + const i32 right_pivot_i = std::max(pivot_i, sibling_i); + const i32 left_pivot_i = std::min(pivot_i, sibling_i); + + // Call Subtree::try_merge. + // + BATT_REQUIRE_OK(this->children[left_pivot_i].try_merge(update_context, + std::move(this->children[right_pivot_i]))); + + this->child_pages[left_pivot_i] = llfs::PinnedPage{}; + this->child_pages.erase(this->child_pages.begin() + right_pivot_i); + + // Update the update_buffer levels. Note that we only have to do this for levels containing + // segments, since merging two pivots entails updating the active pivots bit set. + // + for (Level& level : this->update_buffer.levels) { + batt::case_of( + level, + [](EmptyLevel&) { + // nothing to do + }, + [](MergedLevel&) { + // nothing to do + }, + [&](SegmentedLevel& segmented_level) { + in_segmented_level(*this, + segmented_level, + update_context.page_loader, + update_context.overcommit) + .merge_pivots(left_pivot_i, right_pivot_i); + }, + [&](HybridLevel& hybrid_level) { + hybrid_level.merge_pivots(*this, update_context, left_pivot_i, right_pivot_i); + }); + } + + // Update this->children. + // + this->children.erase(this->children.begin() + right_pivot_i); + + // Update pending_bytes. The leftmost of {subtree, sibling} should be incremented by the removed + // subtree's pending bytes values. Erase the pending bytes of the removed subtree. + // + this->pending_bytes[left_pivot_i] += this->pending_bytes[right_pivot_i]; + this->pending_bytes.erase(this->pending_bytes.begin() + right_pivot_i); + + bool is_pending_bytes_exact = this->pending_bytes_is_exact.get(left_pivot_i) && + this->pending_bytes_is_exact.get(right_pivot_i); + this->pending_bytes_is_exact.set(left_pivot_i, is_pending_bytes_exact); + this->pending_bytes_is_exact.remove(right_pivot_i); + + // Remove the pivot key of the removed child subtree from this->pivot_keys_. + // + this->pivot_keys_.erase(this->pivot_keys_.begin() + right_pivot_i); + + // Finally, split the newly merged child if needed. + // + SubtreeViability merged_viability = this->children[left_pivot_i].get_viability(); + if (batt::is_case(merged_viability)) { + r_metrics.merge_then_split_count.add(1); + BATT_REQUIRE_OK(this->make_child_viable(update_context, left_pivot_i)); + } else { + BATT_CHECK(batt::is_case(merged_viability)); + } + + return OkStatus(); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +Status InMemoryNode::try_merge(BatchUpdateContext& context, + std::unique_ptr sibling) noexcept +{ + BATT_CHECK_LT(this->get_max_key(), sibling->get_min_key()); + + //----- --- -- - - - - + // Concatenate the update buffers. + // + BATT_CHECK_EQ(this->update_buffer.levels.size(), sibling->update_buffer.levels.size()); + + for (usize i = 0; i < this->update_buffer.levels.size(); ++i) { + batt::case_of(this->update_buffer.levels[i], [&](auto& left_level) { + this->update_buffer.levels[i] = + std::move(left_level) + .merge(std::move(sibling->update_buffer.levels[i]), this->pivot_count()); + }); + } + + //----- --- -- - - - - + // Then, concatenate the two nodes' metadata. + // + this->max_key_ = sibling->max_key_; + + this->pending_bytes.insert(this->pending_bytes.end(), + sibling->pending_bytes.begin(), + sibling->pending_bytes.end()); + + sibling->pending_bytes_is_exact.push_front_pivots(this->pivot_count()); + this->pending_bytes_is_exact |= sibling->pending_bytes_is_exact; + + this->child_pages.insert(this->child_pages.end(), + std::make_move_iterator(sibling->child_pages.begin()), + std::make_move_iterator(sibling->child_pages.end())); + + // Modify the children Subtree vector after concatenating the update buffers, inserting into the + // vector will cause the pivot count to increase. + // + this->children.insert(this->children.end(), + std::make_move_iterator(sibling->children.begin()), + std::make_move_iterator(sibling->children.end())); + + // Remove the key upper bound for `this`. + // + this->pivot_keys_.pop_back(); + this->pivot_keys_.insert(this->pivot_keys_.end(), + sibling->pivot_keys_.begin(), + sibling->pivot_keys_.end()); + + return OkStatus(); +} + //==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - // Status InMemoryNode::set_pivot_items_flushed(BatchUpdateContext& update_context, @@ -739,18 +923,21 @@ Status InMemoryNode::set_pivot_items_flushed(BatchUpdateContext& update_context, // nothing to do }, [&](MergedLevel& merged_level) { - merged_level.result_set.drop_key_range(flush_key_crange); - - is_now_empty = merged_level.result_set.empty(); + is_now_empty = merged_level.set_items_flushed(flush_key_crange); }, [&](SegmentedLevel& segmented_level) { - segment_load_status.Update(in_segmented_level(*this, - segmented_level, - update_context.page_loader, - update_context.overcommit) - .drop_key_range(pivot_i, flush_key_crange.upper_bound)); - - is_now_empty = segmented_level.empty(); + is_now_empty = segmented_level.set_pivot_items_flushed(*this, + update_context, + pivot_i, + flush_key_crange, + segment_load_status); + }, + [&](HybridLevel& hybrid_level) { + is_now_empty = hybrid_level.set_pivot_items_flushed(*this, + update_context, + pivot_i, + flush_key_crange, + segment_load_status); }); if (is_now_empty) { @@ -779,23 +966,13 @@ Status InMemoryNode::set_pivot_completely_flushed(usize pivot_i, // nothing to do }, [&](MergedLevel& merged_level) { - merged_level.result_set.drop_key_range_half_open(pivot_key_range); - - is_now_empty = merged_level.result_set.empty(); + is_now_empty = merged_level.set_items_flushed(pivot_key_range); }, [&](SegmentedLevel& segmented_level) { - for (usize segment_i = 0; segment_i < segmented_level.segment_count();) { - Segment& segment = segmented_level.get_segment(segment_i); - - segment.set_pivot_active(pivot_i, false); - - if (segment.is_inactive()) { - segmented_level.drop_segment(segment_i); - } else { - ++segment_i; - } - } - is_now_empty = segmented_level.empty(); + is_now_empty = segmented_level.set_pivot_completely_flushed(pivot_i); + }, + [&](HybridLevel& hybrid_level) { + is_now_empty = hybrid_level.set_pivot_completely_flushed(pivot_i, pivot_key_range); }); if (is_now_empty) { @@ -869,26 +1046,26 @@ void InMemoryNode::push_levels_to_merge(MergeCompactor& compactor, }, [&](const MergedLevel& merged_level) -> BoxedSeq { has_page_refs = HasPageRefs{has_page_refs || merged_level.result_set.has_page_refs()}; - return merged_level.result_set.live_edit_slices(this->get_pivot_key(min_pivot_i)); + return merged_level.to_boxed_seq(*this, min_pivot_i); }, [&](const SegmentedLevel& segmented_level) -> BoxedSeq { //----- --- -- - - - - // TODO [tastolfi 2025-03-14] update has_page_refs here! //----- --- -- - - - - - if (only_pivot && !segmented_level.is_pivot_active(min_pivot_i)) { - return seq::Empty{} // - | seq::boxed(); - } - return SegmentedLevelScanner{ - *this, - segmented_level, - update_context.page_loader, - llfs::PinPageToJob::kDefault, - update_context.overcommit, - segment_load_status, - min_pivot_i, - min_key} // - | seq::boxed(); + return segmented_level.to_boxed_seq(*this, + update_context, + segment_load_status, + min_pivot_i, + only_pivot, + min_key); + }, + [&](const HybridLevel& hybrid_level) -> BoxedSeq { + return hybrid_level.to_boxed_seq(*this, + update_context, + segment_load_status, + min_pivot_i, + only_pivot, + min_key); })); } } @@ -909,6 +1086,9 @@ usize InMemoryNode::segment_count() const }, [](const SegmentedLevel& segmented_level) -> usize { return segmented_level.segment_count(); + }, + [this](const HybridLevel hybrid_level) -> usize { + return hybrid_level.segment_count(this->tree_options); }); } return total; @@ -953,10 +1133,18 @@ usize InMemoryNode::total_segment_filter_cut_points() const return 0; }, [](const SegmentedLevel& segmented_level) -> usize { + return segmented_level.segment_filter_cut_points(); + }, + [](const HybridLevel& hybrid_level) -> usize { usize n = 0; - for (const Segment& segment : segmented_level.segments) { - n += segment.num_cut_points(); + + for (const auto& sub_level : hybrid_level.get_levels()) { + if (batt::is_case(sub_level)) { + const SegmentedLevel& segmented_sub_level = std::get(sub_level); + n += segmented_sub_level.segment_filter_cut_points(); + } } + return n; }); } @@ -1110,7 +1298,7 @@ StatusOr> InMemoryNode::try_split_direct(BatchUpda SmallVec orig_child_pages = std::move(this->child_pages); SmallVec orig_pending_bytes = std::move(this->pending_bytes); KeyView orig_max_key = this->max_key_; - const u64 orig_pending_bytes_is_exact = this->pending_bytes_is_exact; + const ActivePivotsSet128 orig_pending_bytes_is_exact = this->pending_bytes_is_exact; auto reset_this_on_failure = batt::finally([&] { this->pivot_keys_ = std::move(orig_pivot_keys); @@ -1125,7 +1313,7 @@ StatusOr> InMemoryNode::try_split_direct(BatchUpda this->children.clear(); this->child_pages.clear(); this->pending_bytes.clear(); - this->pending_bytes_is_exact = u64{0}; + this->pending_bytes_is_exact = {}; BATT_CHECK_EQ(orig_pivot_count + 1, orig_pivot_keys.size()); @@ -1183,7 +1371,7 @@ StatusOr> InMemoryNode::try_split_direct(BatchUpda BATT_CHECK_EQ(split_pivot_i, lower_half_pivot_count); node_lower_half->pending_bytes.resize(lower_half_pivot_count); - node_lower_half->pending_bytes_is_exact = 0; + node_lower_half->pending_bytes_is_exact = {}; node_lower_half->child_pages.resize(lower_half_pivot_count); for (usize i = 0; i < lower_half_pivot_count; ++i) { @@ -1209,7 +1397,7 @@ StatusOr> InMemoryNode::try_split_direct(BatchUpda BATT_CHECK_EQ(split_pivot_i + upper_half_pivot_count, orig_children.size()); node_upper_half->pending_bytes.resize(upper_half_pivot_count); - node_upper_half->pending_bytes_is_exact = 0; + node_upper_half->pending_bytes_is_exact = {}; node_upper_half->child_pages.resize(upper_half_pivot_count); for (usize i = 0; i < upper_half_pivot_count; ++i) { @@ -1322,11 +1510,13 @@ StatusOr InMemoryNode::find_key_in_level(usize level_i, return {batt::StatusCode::kNotFound}; }, [&](const MergedLevel& merged_level) -> StatusOr { - return merged_level.result_set.find_key(query.key()); + return merged_level.find_key(query.key()); }, [&](const SegmentedLevel& segmented_level) -> StatusOr { - return in_segmented_level(*this, segmented_level, *query.page_loader, query.overcommit()) - .find_key(key_pivot_i, query); + return segmented_level.find_key(*this, query, key_pivot_i); + }, + [&](const HybridLevel& hybrid_level) -> StatusOr { + return hybrid_level.find_key(*this, query, key_pivot_i); }); } @@ -1335,7 +1525,7 @@ StatusOr InMemoryNode::find_key_in_level(usize level_i, bool InMemoryNode::is_packable() const { for (const Level& level : this->update_buffer.levels) { - if (batt::is_case(level)) { + if (batt::is_case(level) || batt::is_case(level)) { return false; } } @@ -1374,6 +1564,12 @@ Status InMemoryNode::start_serialize(TreeSerializeContext& context) [&total_segments](const SegmentedLevel& segmented_level) -> Status { total_segments += segmented_level.segment_count(); return OkStatus(); + }, + [this, &context, &total_segments](HybridLevel& hybrid_level) -> Status { + BATT_ASSIGN_OK_RESULT(usize segment_count, + hybrid_level.start_serialize(*this, context)); + total_segments += segment_count; + return OkStatus(); })); } @@ -1418,6 +1614,13 @@ StatusOr InMemoryNode::finish_serialize(TreeSerializeContext& cont r_metrics.serialized_nonempty_level_count.add(1); r_metrics.serialized_buffer_segment_count.add(segmented_level.segment_count()); return OkStatus(); + }, + [this, &context, &new_segmented_level](HybridLevel& hybrid_level) -> Status { + StatusOr result = hybrid_level.finish_serialize(*this, context); + if (result.ok()) { + new_segmented_level.emplace(std::move(*result)); + } + return result.status(); })); if (new_segmented_level) { @@ -1464,284 +1667,6 @@ StatusOr InMemoryNode::finish_serialize(TreeSerializeContext& cont return new_page_id; } -//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - -// -StatusOr Segment::load_leaf_page(llfs::PageLoader& page_loader, - llfs::PinPageToJob pin_page_to_job, - llfs::PageCacheOvercommit& overcommit) const -{ - return this->page_id_slot.load_through(page_loader, - llfs::PageLoadOptions{ - LeafPageView::page_layout_id(), - pin_page_to_job, - llfs::OkIfNotFound{false}, - llfs::LruPriority{kLeafLruPriority}, - overcommit, - }); -} - -//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - -// -StatusOr MergedLevel::start_serialize(const InMemoryNode& node, - TreeSerializeContext& context) -{ - batt::RunningTotal running_total = - compute_running_total(context.worker_pool(), this->result_set, DecayToItem{}); - - SplitParts page_parts = split_parts(running_total, - MinPartSize{context.tree_options().flush_size() / 4}, - MaxPartSize{context.tree_options().flush_size()}, - MaxItemSize{context.tree_options().max_item_size()}); - - BATT_CHECK_EQ(running_total.back() - running_total.front(), this->result_set.get_packed_size()); - - auto filter_bits_per_key = context.tree_options().filter_bits_per_key(); - const bool overcommit_triggered = context.overcommit().is_triggered(); - llfs::PageSize filter_page_size = context.tree_options().filter_page_size(); - - for (const Interval& part_extents : page_parts) { - BATT_ASSIGN_OK_RESULT( - TreeSerializeContext::BuildPageJobId id, - context.async_build_page( - context.tree_options().leaf_size(), - packed_leaf_page_layout_id(), - llfs::LruPriority{kNewLeafLruPriority}, - /*task_count=*/2, - [this, - &node, - part_extents, - filter_bits_per_key, - overcommit_triggered, - filter_page_size]( - TreeSerializeContext::BuildPageArgs args) -> TreeSerializeContext::PinPageToJobFn { - //----- --- -- - - - - - const auto all_items_in_level = this->result_set.get(); - const auto items_in_this_page = batt::slice_range(all_items_in_level, part_extents); - - if (args.task_i == 0) { - return build_leaf_page_in_job(node.tree_options.trie_index_reserve_size(), - args.page_buffer, - items_in_this_page); - } - BATT_CHECK_EQ(args.task_i, 1); - - return build_filter_for_leaf_in_job(batt::make_copy(args.filter_page_write_state), - args.page_cache, - overcommit_triggered, - filter_bits_per_key, - filter_page_size, - args.page_buffer.page_id(), - items_in_this_page); - })); - - this->segment_future_ids_.emplace_back(id); - } - - return page_parts.size(); -} - -//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - -// -StatusOr MergedLevel::finish_serialize(const InMemoryNode& node, - TreeSerializeContext& context) -{ - BATT_CHECK_EQ(node.tree_options.filter_bits_per_key(), - context.tree_options().filter_bits_per_key()); - BATT_CHECK_EQ(node.tree_options.expected_items_per_leaf(), - context.tree_options().expected_items_per_leaf()); - - SegmentedLevel segmented_level; - - const usize pivot_count = node.pivot_count(); - const usize segment_count = this->segment_future_ids_.size(); - segmented_level.segments.resize(segment_count); - - for (usize segment_i = 0; segment_i < segment_count; ++segment_i) { - Segment& segment = segmented_level.segments[segment_i]; - - BATT_ASSIGN_OK_RESULT(llfs::PinnedPage pinned_leaf_page, - context.get_build_page_result(this->segment_future_ids_[segment_i])); - - segment.page_id_slot.page_id = pinned_leaf_page.page_id(); - segment.active_pivots.clear(); - - const PackedLeafPage& leaf_page = PackedLeafPage::view_of(pinned_leaf_page); - - for (usize pivot_i = 0; pivot_i < pivot_count; ++pivot_i) { - const Interval pivot_key_range = in_node(node).get_pivot_key_range(pivot_i); - - const Interval pivot_range_in_leaf{ - .lower_bound = leaf_page.lower_bound(pivot_key_range.lower_bound), - .upper_bound = leaf_page.lower_bound(pivot_key_range.upper_bound), - }; - - segment.set_pivot_active(pivot_i, !pivot_range_in_leaf.empty()); - } - - segment.check_invariants(__FILE__, __LINE__); - } - - return {std::move(segmented_level)}; -} - -//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - -// -void InMemoryNode::UpdateBuffer::SegmentedLevel::drop_segment(usize i) -{ - this->segments.erase(this->segments.begin() + i); -} - -//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - -// -void InMemoryNode::UpdateBuffer::SegmentedLevel::drop_pivot_range( - const Interval& pivot_i_range, - const Interval& pivot_key_range, - llfs::PageLoader& page_loader, - const TreeOptions& tree_options) -{ - for (Segment& segment : this->segments) { - BATT_CHECK_OK(in_segment(segment).drop_pivot_range(pivot_i_range, - pivot_key_range, - page_loader, - tree_options)); - - if (pivot_i_range.lower_bound == 0) { - segment.pop_front_pivots(pivot_i_range.upper_bound); - } - } - - this->segments.erase(std::remove_if(this->segments.begin(), - this->segments.end(), - [](const Segment& segment) { - return segment.is_inactive(); - }), - this->segments.end()); -} - -//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - -// -void InMemoryNode::UpdateBuffer::SegmentedLevel::drop_before_pivot(i32 pivot_i, - const KeyView& pivot_key, - llfs::PageLoader& page_loader, - const TreeOptions& tree_options) -{ - this->drop_pivot_range((Interval{0, pivot_i}), - (Interval{global_min_key(), pivot_key}), - page_loader, - tree_options); -} - -//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - -// -void InMemoryNode::UpdateBuffer::SegmentedLevel::drop_after_pivot(i32 pivot_i, - const KeyView& pivot_key, - llfs::PageLoader& page_loader, - const TreeOptions& tree_options) -{ - this->drop_pivot_range((Interval{pivot_i, InMemoryNode::kMaxTempPivots}), - (Interval{pivot_key, global_max_key()}), - page_loader, - tree_options); -} - -//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - -// -bool InMemoryNode::UpdateBuffer::SegmentedLevel::is_pivot_active(i32 pivot_i) const -{ - for (const Segment& segment : this->segments) { - if (segment.is_pivot_active(pivot_i)) { - return true; - } - } - return false; -} - -//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - -// -void InMemoryNode::UpdateBuffer::SegmentedLevel::check_items_sorted( - const InMemoryNode& node, - llfs::PageLoader& page_loader) const -{ - SegmentedLevelScanner scanner{ - node, - *this, - page_loader, - llfs::PinPageToJob::kDefault, - llfs::PageCacheOvercommit::not_allowed(), - }; - - Optional prev_slice_max_key; - usize item_i = 0; - - for (;;) { - Optional edit_slice = scanner.next(); - - if (!edit_slice) { - break; - } - - batt::case_of(*edit_slice, [&](const auto& slice_impl) { - if (slice_impl.empty()) { - return; - } - if (prev_slice_max_key) { - BATT_CHECK_LE(*prev_slice_max_key, get_key(slice_impl.front())); - } - - prev_slice_max_key = std::string{get_key(slice_impl.back())}; - item_i += slice_impl.size(); - }); - } -} - -//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- - -//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - -// -void InMemoryNode::UpdateBuffer::Segment::check_invariants(const char* file, int line) const -{ - BATT_CHECK(this->filter.check_invariants()) << BATT_INSPECT(file) << BATT_INSPECT(line); -} - -//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - -// -void InMemoryNode::UpdateBuffer::Segment::insert_pivot(i32 pivot_i, bool is_active) -{ - this->check_invariants(__FILE__, __LINE__); - auto on_scope_exit = batt::finally([&] { - this->check_invariants(__FILE__, __LINE__); - }); - - this->active_pivots.insert(pivot_i, is_active); -} - -//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - -// -void InMemoryNode::UpdateBuffer::Segment::pop_front_pivots(i32 count) -{ - BATT_CHECK_LT(count, 64); - - // Shift the active pivot sets down by count. - // - this->active_pivots.pop_front_pivots(count); -} - -//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - -// -bool InMemoryNode::UpdateBuffer::Segment::is_inactive() const -{ - const bool inactive = this->active_pivots.is_empty(); - if (inactive) { - Slice> live_ranges = this->filter.live(); - BATT_CHECK_EQ(live_ranges.size(), 1) << BATT_INSPECT(live_ranges); - BATT_CHECK_EQ(live_ranges[0].upper_bound, PiecewiseFilter::kMaxUpperBound) - << BATT_INSPECT(live_ranges); - } - return inactive; -} - -//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- - //==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - // SmallFn InMemoryNode::UpdateBuffer::dump() const @@ -1757,52 +1682,4 @@ SmallFn InMemoryNode::UpdateBuffer::dump() const }; } -//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - -// -SmallFn InMemoryNode::UpdateBuffer::EmptyLevel::dump() const -{ - return [](std::ostream& out) { - out << "EmptyLevel{}"; - }; -} - -//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - -// -SmallFn InMemoryNode::UpdateBuffer::MergedLevel::dump() const -{ - return [this](std::ostream& out) { - out << "MergedLevel{" << this->result_set.debug_dump(" ") << "\n}"; - }; -} - -//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - -// -SmallFn InMemoryNode::UpdateBuffer::SegmentedLevel::dump() const -{ - return [this](std::ostream& out) { - out << "SegmentedLevel{\n"; - for (const Segment& segment : this->segments) { - out << " " << segment.dump(/*multi_line=*/false) << ",\n"; - } - out << " }"; - }; -} - -//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - -// -SmallFn InMemoryNode::UpdateBuffer::Segment::dump(bool multi_line) const -{ - return [this, multi_line](std::ostream& out) { - if (multi_line) { - out << "Segment:" << std::endl - << " active=" << this->active_pivots.printable() << std::endl - << " filter=" << this->filter.dump() << std::endl - << std::endl; - } else { - out << "Segment{.active=" << this->active_pivots.printable() - << ", .filter=" << this->filter.dump() << ",}"; - } - }; -} - } // namespace turtle_kv diff --git a/src/turtle_kv/tree/in_memory_node.hpp b/src/turtle_kv/tree/in_memory_node.hpp index d9a1813..1eec904 100644 --- a/src/turtle_kv/tree/in_memory_node.hpp +++ b/src/turtle_kv/tree/in_memory_node.hpp @@ -1,5 +1,10 @@ #pragma once +#include +#include +#include +#include + #include #include #include @@ -55,6 +60,14 @@ struct InMemoryNode { /** \brief Captures statistics about the number of levels per node. */ StatsMetric level_depth_stats; + + /** \brief The total time spent on merging two Subtrees and updating parent metadata. + */ + LatencyMetric merge_latency; + + /** \brief The number of times a merge operation was followed by a split operation. + */ + CountMetric merge_then_split_count; }; static Metrics& metrics() @@ -74,314 +87,12 @@ struct InMemoryNode { struct UpdateBuffer { using Self = UpdateBuffer; - struct SegmentedLevel; - - //==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - - // - /** \brief Mutable, in-memory representation of a serialized buffer segment (one leaf page). - */ - struct Segment { - using Self = Segment; - - /** \brief The id of the leaf page for this segment. - */ - llfs::PageIdSlot page_id_slot; - - /** \brief A bit set of pivots in whose key range this segment contains items. - */ - ActivePivotsSet128 active_pivots; - - /** \brief A filter over the flushed items in this segment. - */ - PiecewiseFilter filter; - - //+++++++++++-+-+--+----- --- -- - - - - - - /** \brief Returns a reference to the PageId of this segment's leaf page, plus weak reference - * to its cache slot (if known). - */ - const llfs::PageIdSlot& get_leaf_page_id() const - { - return this->page_id_slot; - } - - /** \brief Returns the active pivots bit set. - */ - ActivePivotsSet128 get_active_pivots() const - { - return this->active_pivots; - } - - /** \brief Marks this segment as containing (or not) active keys addressed to `pivot_i`. - */ - void set_pivot_active(i32 pivot_i, bool active) - { - this->active_pivots.set(pivot_i, active); - } - - /** \brief Returns true iff this segment has active keys addressed to `pivot_i`. - */ - bool is_pivot_active(i32 pivot_i) const - { - return this->active_pivots.get(pivot_i); - } - - template - Interval drop_key_range(const BasicInterval& key_range, - const Slice& items) - { - return drop_item_range(this->filter, items, key_range, llfs::KeyRangeOrder{}); - } - - void drop_index_range(Interval i) - { - this->filter.drop_index_range(i); - } - - bool is_index_filtered(const SegmentedLevel&, u32 index) const - { - return !this->filter.live_at_index(index); - } - - u32 live_lower_bound(const SegmentedLevel&, u32 item_i) const - { - return this->filter.live_lower_bound(item_i); - } - - Interval get_live_item_range(const SegmentedLevel&, Interval i) const - { - return this->filter.find_live_range(i); - } - - usize num_cut_points() const - { - Slice> live_ranges = this->filter.live(); - - // If the first element is live, don't include 0 as a cut point, only include the - // upper bound. - // - bool first_element_live = !live_ranges.empty() && live_ranges.front().lower_bound == - PiecewiseFilter::kMinLowerBound; - bool ends_at_max = !live_ranges.empty() && - live_ranges.back().upper_bound == PiecewiseFilter::kMaxUpperBound; - - return live_ranges.size() * 2 - (first_element_live ? 1 : 0) - (ends_at_max ? 1 : 0); - } - - //+++++++++++-+-+--+----- --- -- - - - - - - /** \brief Panic if filter invariants are not satisfied. - */ - void check_invariants(const char* file, int line) const; - - /** \brief Inserts a new pivot bit in this->active_pivots at position - * `pivot_i`. This is called when a child subtree needs to be split. - */ - void insert_pivot(i32 pivot_i, bool is_active); - - /** \brief Removes the specified number (`count`) pivots from the front of this segment. This - * is used while splitting a node's update buffer. - */ - void pop_front_pivots(i32 count); - - /** \brief Returns true iff this segment is not active for any pivots. - */ - bool is_inactive() const; - - /** \brief Loads the leaf page for this Segment, returning the resulting llfs::PinnedPage. - */ - StatusOr load_leaf_page(llfs::PageLoader& page_loader, - llfs::PinPageToJob pin_page_to_job, - llfs::PageCacheOvercommit& overcommit) const; - - /** \brief Prints a human-readable representation of this Segment. - */ - SmallFn dump(bool multi_line = true) const; - }; - - //==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - - // - /** \brief An empty update buffer level. - */ - struct EmptyLevel { - using Self = EmptyLevel; - - void drop_after_pivot(i32 split_pivot_i [[maybe_unused]], - const KeyView& split_pivot_key [[maybe_unused]], - llfs::PageLoader& page_loader [[maybe_unused]], - const TreeOptions& tree_options [[maybe_unused]]) - { - // Nothing to do! - } - - void drop_before_pivot(i32 split_pivot_i [[maybe_unused]], - const KeyView& split_pivot_key [[maybe_unused]], - llfs::PageLoader& page_loader [[maybe_unused]], - const TreeOptions& tree_options [[maybe_unused]]) - { - // Nothing to do! - } - - SmallFn dump() const; - }; - - //==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - - // - /** \brief Mutable, in-memory representation of a non-empty serialized update buffer level. - */ - struct SegmentedLevel { - using Self = SegmentedLevel; - using Segment = InMemoryNode::UpdateBuffer::Segment; - - //+++++++++++-+-+--+----- --- -- - - - - - - SmallVec segments; - - //+++++++++++-+-+--+----- --- -- - - - - - - bool empty() const - { - return this->segments.empty(); - } - - usize segment_count() const - { - return this->segments.size(); - } - - Segment& get_segment(usize i) - { - return this->segments[i]; - } - - const Segment& get_segment(usize i) const - { - return this->segments[i]; - } - - Slice get_segments_slice() const - { - return as_const_slice(this->segments); - } - - //+++++++++++-+-+--+----- --- -- - - - - - - /** \brief Removes the specified segment from this level. - * - * Should only be called by SegmentedLevelAlgorithms::flush_pivot_up_to_key. - */ - void drop_segment(usize i); - - /** \brief Removes the specified set of pivots from this level. - * - * Used to implement node splits. - */ - void drop_pivot_range(const Interval& pivot_i_range, - const Interval& pivot_key_range, - llfs::PageLoader& page_loader, - const TreeOptions& tree_options); - - /** \brief Drops all pivots before (but not including) the specified pivot. - * - */ - void drop_before_pivot(i32 pivot_i, - const KeyView& pivot_key, - llfs::PageLoader& page_loader, - const TreeOptions& tree_options); - - /** \brief Drops all pivots after (and including) the specified pivot. - * - */ - void drop_after_pivot(i32 pivot_i, - const KeyView& pivot_key, - llfs::PageLoader& page_loader, - const TreeOptions& tree_options); - - /** \brief Returns true iff the specified pivot is active for any of the Segments in this - * level. - */ - bool is_pivot_active(i32 pivot_i) const; - - /** \brief Verifies that all items appear in this level in key-sorted order; panic if this is - * not the case. - * - * Warning: This is a very expensive operation! Do not call it on a performance-critical code - * path. - */ - void check_items_sorted(const InMemoryNode& node, llfs::PageLoader& page_loader) const; - - /** \brief Prints a human-readable representation of the level. - */ - SmallFn dump() const; - }; - - //==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - - // - struct MergedLevel { - using Self = MergedLevel; - - //+++++++++++-+-+--+----- --- -- - - - - - - MergeCompactor::ResultSet result_set; - std::vector segment_future_ids_; - - //+++++++++++-+-+--+----- --- -- - - - - - - void drop_key_range(const Interval& key_drop_range) - { - this->result_set.drop_key_range_half_open(key_drop_range); - } - - void drop_after_pivot(i32 pivot_i [[maybe_unused]], - const KeyView& pivot_key, - llfs::PageLoader& page_loader [[maybe_unused]], - const TreeOptions& tree_options [[maybe_unused]]) - { - this->drop_key_range(Interval{ - .lower_bound = pivot_key, - .upper_bound = global_max_key(), - }); - } - - void drop_before_pivot(i32 pivot_i [[maybe_unused]], - const KeyView& pivot_key, - llfs::PageLoader& page_loader [[maybe_unused]], - const TreeOptions& tree_options [[maybe_unused]]) - { - this->drop_key_range(Interval{ - .lower_bound = global_min_key(), - .upper_bound = pivot_key, - }); - } - - usize estimate_segment_count(const TreeOptions& tree_options) const - { - const usize packed_size = this->result_set.get_packed_size(); - if (packed_size == 0) { - return 0; - } - - const usize capacity_per_segment = tree_options.flush_size() - tree_options.max_item_size(); - const usize estimated = (packed_size + capacity_per_segment - 1) / capacity_per_segment; - - BATT_CHECK_GE(estimated * capacity_per_segment, packed_size); - BATT_CHECK_LT((estimated - 1) * capacity_per_segment, packed_size) - << BATT_INSPECT(estimated) << BATT_INSPECT(capacity_per_segment); - - return estimated; - } - - /** \brief Returns the number of segment leaf page build jobs added to the context. - */ - StatusOr start_serialize(const InMemoryNode& node, TreeSerializeContext& context); - - StatusOr finish_serialize(const InMemoryNode& node, - TreeSerializeContext& context); - - SmallFn dump() const; - }; - - using Level = std::variant; + using Segment = InMemoryNodeSegment; + using EmptyLevel = InMemoryNodeEmptyLevel; + using MergedLevel = InMemoryNodeMergedLevel; + using SegmentedLevel = InMemoryNodeSegmentedLevel; + using HybridLevel = InMemoryNodeHybridLevel; + using Level = InMemoryNodeLevel; //+++++++++++-+-+--+----- --- -- - - - - @@ -412,7 +123,7 @@ struct InMemoryNode { SmallVec children; SmallVec child_pages; SmallVec pending_bytes; - u64 pending_bytes_is_exact = 0; + ActivePivotsSet128 pending_bytes_is_exact = {}; Optional latest_flush_pivot_i_; SmallVec pivot_keys_; KeyView max_key_; @@ -517,8 +228,8 @@ struct InMemoryNode { void add_pending_bytes(usize pivot_i, usize byte_count) { - this->pending_bytes_is_exact = set_bit(this->pending_bytes_is_exact, pivot_i, false); - BATT_CHECK_EQ(get_bit(this->pending_bytes_is_exact, pivot_i), false); + this->pending_bytes_is_exact.set(pivot_i, false); + BATT_CHECK_EQ(this->pending_bytes_is_exact.get(pivot_i), false); this->pending_bytes[pivot_i] += byte_count; } @@ -585,10 +296,26 @@ struct InMemoryNode { */ Status try_flush(BatchUpdateContext& context); + /** \brief Attempt to collapse one level of the tree. Returns the node's single pivot. + * TODO [tastolfi 2026-05-04] describe the conditions under which this fn will panic + */ + Subtree shrink_or_panic(); + + /** \brief Merge the node in place with its right sibling. + * + * Returns nullptr if `sibling` is completely consumed; otherwise, returns the modified sibling + * since a borrow occurred. + */ + Status try_merge(BatchUpdateContext& context, std::unique_ptr sibling) noexcept; + /** \brief Splits the specified child, inserting a new pivot immediately after `pivot_i`. */ Status split_child(BatchUpdateContext& update_context, i32 pivot_i); + /** \brief Merges the specified child with a sibling. + */ + Status merge_child(BatchUpdateContext& update_context, i32 pivot_i) noexcept; + /** \brief Returns true iff there are no MergedLevels or unserialized Subtree children in this * node. */ @@ -602,9 +329,9 @@ struct InMemoryNode { i32 pivot_i, const Interval& pivot_key_range); - /** \brief Merges and compacts all live edits in all levels/segments, producing a single level (if - * not size-tiered), or a series of non-key-overlapping levels with a single segment in each (if - * size-tiered). + /** \brief Merges and compacts all live edits in all levels/segments, producing a single level + * (if not size-tiered), or a series of non-key-overlapping levels with a single segment in each + * (if size-tiered). * * This can be done if node splitting fails, to reduce the serialized space required by getting * rid of all the non-zero flushed key upper bounds. This should NOT be done under normal diff --git a/src/turtle_kv/tree/in_memory_node.test.cpp b/src/turtle_kv/tree/in_memory_node.test.cpp index ebe56ca..0230b93 100644 --- a/src/turtle_kv/tree/in_memory_node.test.cpp +++ b/src/turtle_kv/tree/in_memory_node.test.cpp @@ -31,6 +31,7 @@ #include #include #include +#include #include namespace { @@ -56,6 +57,7 @@ using turtle_kv::KVStoreScanner; using turtle_kv::LatencyMetric; using turtle_kv::LatencyTimer; using turtle_kv::make_memory_page_cache; +using turtle_kv::NeedsMerge; using turtle_kv::NeedsSplit; using turtle_kv::None; using turtle_kv::OkStatus; @@ -75,7 +77,9 @@ using turtle_kv::TreeOptions; using turtle_kv::TreeSerializeContext; using turtle_kv::ValueView; using turtle_kv::testing::RandomResultSetGenerator; +using turtle_kv::testing::RandomStringGenerator; +using llfs::get_key; using llfs::StableStringStore; using batt::getenv_as; @@ -167,6 +171,56 @@ void verify_range_scan(LatencyMetric* scan_latency, } } +void perform_range_scan(Table& expected_table, + Subtree& tree, + const TreeOptions& tree_options, + PinningPageLoader& page_loader, + const KeyView& min_key, + usize scan_len, + LatencyMetric* scan_latency, + usize iteration) +{ + auto root_ptr = std::make_shared(tree.clone_serialized_or_panic()); + + std::array, kMaxScanSize> scan_items_buffer; + + PageSliceStorage page_slice_storage; + + KVStoreScanner kv_scanner{ + page_loader, + root_ptr->page_id_slot_or_panic(), + BATT_OK_RESULT_OR_PANIC(root_ptr->get_height(page_loader, // + llfs::PageCacheOvercommit::not_allowed())), + min_key, + tree_options.trie_index_sharded_view_size(), + &page_slice_storage}; + + usize n_read = 0; + { + LatencyTimer timer{*scan_latency}; + BATT_CHECK_OK(kv_scanner.start()); + for (auto& kv_pair : scan_items_buffer) { + Optional item = kv_scanner.next(); + if (!item) { + break; + } + kv_pair.first = item->key; + kv_pair.second = item->value; + ++n_read; + if (n_read == scan_len) { + break; + } + } + } + + ASSERT_NO_FATAL_FAILURE(verify_range_scan(nullptr, + expected_table, + as_slice(scan_items_buffer.data(), n_read), + min_key, + scan_len)) + << BATT_INSPECT(iteration) << BATT_INSPECT_STR(min_key) << BATT_INSPECT(scan_len); +} + struct SubtreeBatchUpdateScenario { static std::atomic& size_tiered_count() { @@ -191,6 +245,7 @@ struct BatchUpdateGenerator { StableStringStore strings; RandomResultSetGenerator result_set_generator; std::vector pending_deletes; + std::vector already_deleted; usize delete_frequency; explicit BatchUpdateGenerator(usize delete_frequency_param, @@ -206,6 +261,8 @@ struct BatchUpdateGenerator { ResultSet result_set = result_set_generator(DecayToItem{}, rng, this->strings, this->pending_deletes); + this->already_deleted = this->pending_deletes; + if (update_pending_deletes) { if (!this->pending_deletes.empty()) { this->pending_deletes.clear(); @@ -221,6 +278,14 @@ struct BatchUpdateGenerator { return result_set; } + + void verify_deleted_point_queries(Table& expected_table, Table& actual_table) + { + for (const KeyView& key : this->already_deleted) { + EXPECT_EQ(expected_table.get(key).status(), batt::StatusCode::kNotFound); + EXPECT_EQ(actual_table.get(key).status(), batt::StatusCode::kNotFound); + } + } }; //==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - @@ -333,9 +398,7 @@ void SubtreeBatchUpdateScenario::run() .metrics = metrics, .overcommit = llfs::PageCacheOvercommit::not_allowed(), }, - // TODO [vsilai 2026-01-09] Enable delete support for batch generation. - // - .result_set = update_generator.next_batch(i, rng, /*update_pending_deletes=*/false), + .result_set = update_generator.next_batch(i, rng, /*update_pending_deletes=*/true), .edit_size_totals = None, }; update.update_edit_size_totals(); @@ -360,7 +423,6 @@ void SubtreeBatchUpdateScenario::run() IsRoot{true}); ASSERT_TRUE(status.ok()) << BATT_INSPECT(status) << BATT_INSPECT(this->seed) << BATT_INSPECT(i); - ASSERT_FALSE(tree.is_serialized()); ASSERT_FALSE(batt::is_case(tree.get_viability())); if (my_id == 0) { @@ -372,6 +434,10 @@ void SubtreeBatchUpdateScenario::run() verify_table_point_queries(expected_table, actual_table, rng, batt::log2_ceil(i))) << BATT_INSPECT(this->seed) << BATT_INSPECT(i); + ASSERT_NO_FATAL_FAILURE( + update_generator.verify_deleted_point_queries(expected_table, actual_table)) + << BATT_INSPECT(this->seed) << BATT_INSPECT(i); + if (((i + 1) % chi) == 0) { if (my_id == 0) { LOG(INFO) << "taking checkpoint..."; @@ -407,48 +473,24 @@ void SubtreeBatchUpdateScenario::run() verify_table_point_queries(expected_table, actual_table, rng, batt::log2_ceil(i))) << BATT_INSPECT(this->seed) << BATT_INSPECT(i); + ASSERT_NO_FATAL_FAILURE( + update_generator.verify_deleted_point_queries(expected_table, actual_table)) + << BATT_INSPECT(this->seed) << BATT_INSPECT(i); + { auto root_ptr = std::make_shared(tree.clone_serialized_or_panic()); - std::unique_ptr scanner_page_job = page_cache->new_job(); const usize scan_len = pick_scan_len(rng); - std::array, kMaxScanSize> scan_items_buffer; KeyView min_key = update.result_set.get_min_key(); - PageSliceStorage page_slice_storage; - - KVStoreScanner kv_scanner{ - *page_loader, - root_ptr->page_id_slot_or_panic(), - BATT_OK_RESULT_OR_PANIC(root_ptr->get_height(*page_loader, // - llfs::PageCacheOvercommit::not_allowed())), - min_key, - tree_options.trie_index_sharded_view_size(), - &page_slice_storage}; - - usize n_read = 0; - { - LatencyTimer timer{scan_latency}; - BATT_CHECK_OK(kv_scanner.start()); - for (auto& kv_pair : scan_items_buffer) { - Optional item = kv_scanner.next(); - if (!item) { - break; - } - kv_pair.first = item->key; - kv_pair.second = item->value; - ++n_read; - if (n_read == scan_len) { - break; - } - } - } - ASSERT_NO_FATAL_FAILURE(verify_range_scan(nullptr, - expected_table, - as_slice(scan_items_buffer.data(), n_read), - min_key, - scan_len)) - << BATT_INSPECT(i) << BATT_INSPECT_STR(min_key) << BATT_INSPECT(scan_len); + perform_range_scan(expected_table, + *root_ptr, + tree_options, + *page_loader, + min_key, + scan_len, + &scan_latency, + i); } if (my_id == 0) { @@ -466,4 +508,1008 @@ void SubtreeBatchUpdateScenario::run() } } +TEST(InMemoryNodeTest, SubtreeDeletions) +{ + LatencyMetric scan_latency; + + const usize key_size = 24; + const usize value_size = 100; + const usize chi = 4; + + TreeOptions tree_options = TreeOptions::with_default_values() // + .set_leaf_size(32 * kKiB) + .set_node_size(4 * kKiB) + .set_key_size_hint(key_size) + .set_value_size_hint(value_size); + + usize items_per_leaf = tree_options.flush_size() / tree_options.expected_item_size(); + usize total_batches = 100; + + std::vector keys; + keys.reserve(total_batches * items_per_leaf); + + std::string value_str = std::string(value_size, 'a'); + ValueView value = ValueView::from_str(value_str); + + std::default_random_engine rng{/*seed=*/3}; + RandomStringGenerator generate_key; + llfs::StableStringStore store; + std::unordered_set keys_set; + while (keys.size() < total_batches * items_per_leaf) { + KeyView key = generate_key(rng, store); + if (keys_set.contains(key)) { + continue; + } + keys_set.emplace(key); + keys.emplace_back(key); + } + std::sort(keys.begin(), keys.end(), llfs::KeyOrder{}); + + std::shared_ptr page_cache = + make_memory_page_cache(batt::Runtime::instance().default_scheduler(), + tree_options, + /*byte_capacity=*/1500 * kMiB); + + Subtree tree = Subtree::make_empty(); + ASSERT_TRUE(tree.is_serialized()); + + turtle_kv::OrderedMapTable> expected_table; + SubtreeTable actual_table{*page_cache, tree_options, tree}; + + batt::WorkerPool& worker_pool = batt::WorkerPool::null_pool(); + turtle_kv::BatchUpdateMetrics metrics; + + Optional page_loader{*page_cache}; + + const auto create_insertion_batch = [&](usize batch_number) -> std::vector { + std::vector current_batch; + current_batch.reserve(items_per_leaf); + for (usize j = 0; j < items_per_leaf; ++j) { + current_batch.emplace_back(keys[(batch_number * items_per_leaf) + j], value); + } + + return current_batch; + }; + + const auto create_deletion_batch = [&](usize batch_number) -> std::vector { + std::vector current_batch; + current_batch.reserve(items_per_leaf); + + for (usize i = 0; i < items_per_leaf; ++i) { + usize key_i = batch_number + i * total_batches; + if (key_i < keys.size()) { + current_batch.emplace_back(keys[key_i], ValueView::deleted()); + } + } + + BATT_CHECK_LE(current_batch.size(), items_per_leaf) << BATT_INSPECT(batch_number); + + return current_batch; + }; + + const auto apply_tree_updates = [&](auto batch_creation_func) { + for (usize i = 0; i < total_batches; ++i) { + std::vector current_batch = batch_creation_func(i); + + ResultSet result; + result.append(std::move(current_batch)); + + BatchUpdate update{ + .context = + BatchUpdateContext{ + .worker_pool = worker_pool, + .page_loader = *page_loader, + .cancel_token = batt::CancelToken{}, + .metrics = metrics, + .overcommit = llfs::PageCacheOvercommit::not_allowed(), + }, + .result_set = std::move(result), + .edit_size_totals = None, + }; + update.update_edit_size_totals(); + + Status table_update_status = update_table(expected_table, update.result_set); + ASSERT_TRUE(table_update_status.ok()) << BATT_INSPECT(table_update_status); + + StatusOr tree_height_before = + tree.get_height(*page_loader, llfs::PageCacheOvercommit::not_allowed()); + ASSERT_TRUE(tree_height_before.ok()) << BATT_INSPECT(tree_height_before); + + Status status = // + tree.apply_batch_update(tree_options, + ParentNodeHeight{*tree_height_before + 1}, + update, + /*key_upper_bound=*/global_max_key(), + IsRoot{true}); + + ASSERT_TRUE(status.ok()) << BATT_INSPECT(status) << BATT_INSPECT(i); + + StatusOr tree_height_after = + tree.get_height(*page_loader, llfs::PageCacheOvercommit::not_allowed()); + ASSERT_TRUE(tree_height_after.ok()) << BATT_INSPECT(tree_height_after); + + if (*tree_height_after == 0) { + ASSERT_LT(*tree_height_after, *tree_height_before); + ASSERT_TRUE(tree.is_serialized()); + break; + } else { + ASSERT_FALSE(tree.is_serialized()); + } + + ASSERT_FALSE(batt::is_case(tree.get_viability())); + + ASSERT_NO_FATAL_FAILURE( + verify_table_point_queries(expected_table, actual_table, rng, batt::log2_ceil(i))) + << BATT_INSPECT(i); + + if (((i + 1) % chi) == 0) { + std::unique_ptr page_job = page_cache->new_job(); + TreeSerializeContext context{tree_options, + *page_job, + worker_pool, + llfs::PageCacheOvercommit::not_allowed(), + turtle_kv::FilterPageWriteState::make_new()}; + + Status start_status = tree.start_serialize(context); + ASSERT_TRUE(start_status.ok()) << BATT_INSPECT(start_status); + + Status build_status = context.build_all_pages(); + ASSERT_TRUE(build_status.ok()) << BATT_INSPECT(build_status); + + StatusOr finish_status = tree.finish_serialize(context); + ASSERT_TRUE(finish_status.ok()) << BATT_INSPECT(finish_status); + + page_job->new_root(*finish_status); + Status commit_status = llfs::unsafe_commit_job(std::move(page_job)); + ASSERT_TRUE(commit_status.ok()) << BATT_INSPECT(commit_status); + + ASSERT_NO_FATAL_FAILURE( + verify_table_point_queries(expected_table, actual_table, rng, batt::log2_ceil(i))) + << BATT_INSPECT(i); + + { + auto root_ptr = std::make_shared(tree.clone_serialized_or_panic()); + + const usize scan_len = 20; + KeyView min_key = update.result_set.get_min_key(); + + perform_range_scan(expected_table, + *root_ptr, + tree_options, + *page_loader, + min_key, + scan_len, + &scan_latency, + i); + } + + page_loader.emplace(*page_cache); + } + } + }; + + LOG(INFO) << "Inserting key/value pairs into tree..."; + apply_tree_updates(create_insertion_batch); + + LOG(INFO) << "Deleting key/value pairs from tree..."; + StatusOr tree_height = + tree.get_height(*page_loader, llfs::PageCacheOvercommit::not_allowed()); + ASSERT_TRUE(tree_height.ok()) << BATT_INSPECT(tree_height); + for (;;) { + if (*tree_height > 0) { + apply_tree_updates(create_deletion_batch); + } else { + break; + } + tree_height = tree.get_height(*page_loader, llfs::PageCacheOvercommit::not_allowed()); + ASSERT_TRUE(tree_height.ok()) << BATT_INSPECT(tree_height); + } + + LOG(INFO) << BATT_INSPECT(InMemoryNode::metrics().merge_latency); + + LOG(INFO) << BATT_INSPECT(InMemoryNode::metrics().merge_then_split_count); + + LOG(INFO) << BATT_INSPECT(scan_latency); +} + +//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- +// InMemoryNodeLevel::merge tests +//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- + +using turtle_kv::ActivePivotsSet128; +using turtle_kv::InMemoryNodeEmptyLevel; +using turtle_kv::InMemoryNodeHybridLevel; +using turtle_kv::InMemoryNodeLevel; +using turtle_kv::InMemoryNodeMergedLevel; +using turtle_kv::InMemoryNodeSegment; +using turtle_kv::InMemoryNodeSegmentedLevel; +using turtle_kv::KeyOrder; +using turtle_kv::MergeCompactor; +using turtle_kv::PiecewiseFilter; + +using EmptyLevel = InMemoryNodeEmptyLevel; +using MergedLevel = InMemoryNodeMergedLevel; +using SegmentedLevel = InMemoryNodeSegmentedLevel; +using HybridLevel = InMemoryNodeHybridLevel; +using Segment = InMemoryNodeSegment; +using Level = InMemoryNodeLevel; + +class InMemoryNodeLevelMergeTest : public ::testing::Test +{ + public: + Segment make_segment(u64 page_id, const std::vector& active_pivot_indices) + { + Segment segment; + segment.page_id_slot = llfs::PageIdSlot::from_page_id(llfs::PageId{page_id}); + for (i32 pivot_i : active_pivot_indices) { + segment.active_pivots.set(pivot_i, true); + } + return segment; + } + + SegmentedLevel make_segmented_level(const std::vector& segments) + { + SegmentedLevel level; + for (auto& seg : segments) { + level.segments.emplace_back(std::move(seg)); + } + return level; + } + + MergedLevel make_merged_level(usize item_count, std::string_view key_prefix) + { + const usize value_size = 100; + std::vector items; + items.reserve(item_count); + + RandomStringGenerator key_gen; + key_gen.set_size(24); + + std::unordered_set seen; + while (items.size() < item_count) { + std::string key_str(key_prefix); + key_str += key_gen(this->rng_); + + KeyView key = this->string_store_.store(key_str); + if (seen.count(key)) { + continue; + } + seen.emplace(key); + + char ch = 'a' + (items.size() % 26); + std::string_view value = this->string_store_.store(std::string(value_size, ch)); + items.emplace_back(key, ValueView::from_str(value)); + } + + std::sort(items.begin(), items.end(), KeyOrder{}); + + MergedLevel level; + level.result_set.append(std::move(items)); + return level; + } + + HybridLevel make_hybrid_level(const std::vector& sub_levels) + { + HybridLevel level; + for (auto& sl : sub_levels) { + level.sub_levels.emplace_back(std::move(sl)); + } + return level; + } + + u64 random_active_pivots(i32 max_pivot) + { + std::uniform_int_distribution dist(0, 1); + u64 pivots = 0; + for (i32 i = 0; i < max_pivot; ++i) { + if (dist(this->rng_)) { + pivots = turtle_kv::set_bit(pivots, i, true); + } + } + if (pivots == 0) { + // Make sure at leas one pivot in the bit set is active. + // + std::uniform_int_distribution fallback(0, max_pivot - 1); + pivots = turtle_kv::set_bit(pivots, fallback(this->rng_), true); + } + return pivots; + } + + static constexpr u32 kFilterItemCount = 1000; + + void apply_random_filter_drops(Segment& seg, usize max_drops) + { + std::uniform_int_distribution count_dist(0, max_drops); + usize n_drops = count_dist(this->rng_); + + for (usize i = 0; i < n_drops; ++i) { + std::uniform_int_distribution start_dist(0, kFilterItemCount - 1); + u32 start = start_dist(this->rng_); + + std::uniform_int_distribution end_dist(start, kFilterItemCount); + u32 end = end_dist(this->rng_); + + seg.filter.drop_index_range({start, end}); + } + } + + Segment make_random_segment(u64 page_id, i32 max_pivot) + { + u64 pivots = this->random_active_pivots(max_pivot); + Segment seg = this->make_segment(page_id, {}); + for (i32 p = 0; p < max_pivot; ++p) { + seg.active_pivots.set(p, turtle_kv::get_bit(pivots, p)); + } + this->apply_random_filter_drops(seg, /*max_drops=*/3); + return seg; + } + + SegmentedLevel make_random_segmented_level(u64 base_page_id, + i32 max_pivot, + usize min_count = 1, + usize max_count = 32) + { + std::uniform_int_distribution count_dist(min_count, max_count); + usize n_segments = count_dist(this->rng_); + + std::vector segments; + for (usize i = 0; i < n_segments; ++i) { + segments.push_back(this->make_random_segment(base_page_id + i, max_pivot)); + } + return this->make_segmented_level(std::move(segments)); + } + + void verify_pivots_shifted(const std::vector& originals, + const SegmentedLevel& result, + usize node_pivot_count, + usize offset = 0, + bool check_original_inactive = false) + { + for (usize i = 0; i < originals.size(); ++i) { + const auto& original = originals[i]; + const auto& seg = result.get_segment(offset + i); + EXPECT_EQ(seg.get_leaf_page_id().page_id, original.get_leaf_page_id().page_id); + + for (i32 p = 0; p < 64; ++p) { + if (original.is_pivot_active(p)) { + i32 shifted = p + static_cast(node_pivot_count); + EXPECT_TRUE(seg.is_pivot_active(shifted)) + << "Segment " << i << " pivot " << p << " should be shifted to " << shifted; + if (check_original_inactive) { + EXPECT_FALSE(seg.is_pivot_active(p)) + << "Segment " << i << " original pivot " << p << " should not be active"; + } + } + } + } + } + + void verify_pivots_unchanged(const std::vector& originals, + const SegmentedLevel& result, + usize offset = 0) + { + for (usize i = 0; i < originals.size(); ++i) { + const auto& original = originals[i]; + const auto& seg = result.get_segment(offset + i); + EXPECT_EQ(seg.get_leaf_page_id().page_id, original.get_leaf_page_id().page_id); + + for (i32 p = 0; p < 64; ++p) { + if (original.is_pivot_active(p)) { + EXPECT_TRUE(seg.is_pivot_active(p)) + << "Segment " << i << " pivot " << p << " should be active"; + } + } + } + } + + void verify_segmented_merge_no_duplicates(const std::vector& left_originals, + const std::vector& right_originals, + const SegmentedLevel& result, + usize node_pivot_count) + { + ASSERT_EQ(result.segment_count(), left_originals.size() + right_originals.size()); + this->verify_pivots_unchanged(left_originals, result); + this->verify_pivots_shifted(right_originals, + result, + node_pivot_count, + /*offset=*/left_originals.size(), + /*check_original_inactive=*/true); + } + + void verify_pivots_deduplication(const Segment& left_original, + const Segment& right_original, + const Segment& deduped, + usize node_pivot_count) + { + for (i32 p = 0; p < 64; ++p) { + if (left_original.is_pivot_active(p)) { + EXPECT_TRUE(deduped.is_pivot_active(p)) + << "Left pivot " << p << " should remain active after deduplication"; + } + if (right_original.is_pivot_active(p)) { + i32 shifted = p + static_cast(node_pivot_count); + EXPECT_TRUE(deduped.is_pivot_active(shifted)) + << "Right pivot " << p << " should be shifted to " << shifted << " after deduplication"; + } + } + } + + void verify_filter_union(const Segment& left_original, + const Segment& right_original, + const Segment& result_seg, + u32 check_range = 100) + { + for (u32 idx = 0; idx < check_range; ++idx) { + bool expected = + left_original.filter.live_at_index(idx) || right_original.filter.live_at_index(idx); + EXPECT_EQ(result_seg.filter.live_at_index(idx), expected) + << "Filter mismatch at index " << idx; + } + } + + //+++++++++++-+-+--+----- --- -- - - - - + + std::default_random_engine rng_{330}; + StableStringStore string_store_; +}; + +//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- +// EmptyLevel::merge tests +//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- + +TEST_F(InMemoryNodeLevelMergeTest, EmptyEmpty) +{ + EmptyLevel left; + Level right = EmptyLevel{}; + + Level result = std::move(left).merge(std::move(right), /*node_pivot_count=*/4); + + EXPECT_TRUE(batt::is_case(result)); +} + +TEST_F(InMemoryNodeLevelMergeTest, EmptyMerged) +{ + EmptyLevel left; + MergedLevel right = this->make_merged_level(64, "b_"); + const usize expected_size = right.result_set.size(); + + Level result = std::move(left).merge(Level{std::move(right)}, /*node_pivot_count=*/4); + + ASSERT_TRUE(batt::is_case(result)); + auto& merged = std::get(result); + EXPECT_EQ(merged.result_set.size(), expected_size); +} + +TEST_F(InMemoryNodeLevelMergeTest, EmptySegmented) +{ + constexpr usize kIterations = 100; + + for (usize iter = 0; iter < kIterations; ++iter) { + this->rng_ = std::default_random_engine{iter}; + + std::uniform_int_distribution pivot_count_dist(4, 64); + usize node_pivot_count = pivot_count_dist(this->rng_); + i32 max_pivot = static_cast(node_pivot_count); + + SegmentedLevel right = this->make_random_segmented_level( + /*base_page_id=*/iter * 100, + max_pivot); + + std::vector right_originals; + for (usize i = 0; i < right.segment_count(); ++i) { + right_originals.push_back(right.get_segment(i)); + } + + Level result = std::move(EmptyLevel{}).merge(Level{std::move(right)}, node_pivot_count); + + ASSERT_TRUE(batt::is_case(result)); + auto& segmented = std::get(result); + + ASSERT_EQ(segmented.segment_count(), right_originals.size()); + this->verify_pivots_shifted(right_originals, + segmented, + node_pivot_count, + /*offset=*/0, + /*check_original_inactive=*/true); + } +} + +TEST_F(InMemoryNodeLevelMergeTest, EmptyHybrid) +{ + constexpr usize kIterations = 100; + + for (usize iter = 0; iter < kIterations; ++iter) { + this->rng_ = std::default_random_engine{iter}; + + std::uniform_int_distribution pivot_count_dist(4, 64); + usize node_pivot_count = pivot_count_dist(this->rng_); + i32 max_pivot = static_cast(node_pivot_count); + + SegmentedLevel sub_segmented = this->make_random_segmented_level( + /*base_page_id=*/iter * 100, + max_pivot); + + std::vector sub_originals; + for (usize i = 0; i < sub_segmented.segment_count(); ++i) { + sub_originals.push_back(sub_segmented.get_segment(i)); + } + + HybridLevel right = this->make_hybrid_level({std::move(sub_segmented)}); + + Level result = std::move(EmptyLevel{}).merge(Level{std::move(right)}, node_pivot_count); + + ASSERT_TRUE(batt::is_case(result)); + auto& hybrid = std::get(result); + ASSERT_EQ(hybrid.sub_levels.size(), 1u); + ASSERT_TRUE(batt::is_case(hybrid.sub_levels[0])); + + auto& sub = std::get(hybrid.sub_levels[0]); + ASSERT_EQ(sub.segment_count(), sub_originals.size()); + this->verify_pivots_shifted(sub_originals, + sub, + node_pivot_count, + /*offset=*/0, + /*check_original_inactive=*/true); + } +} + +//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- +// MergedLevel::merge tests +//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- + +TEST_F(InMemoryNodeLevelMergeTest, MergedEmpty) +{ + MergedLevel left = this->make_merged_level(64, "a_"); + const usize expected_size = left.result_set.size(); + + Level result = std::move(left).merge(Level{EmptyLevel{}}, /*node_pivot_count=*/4); + + ASSERT_TRUE(batt::is_case(result)); + auto& merged = std::get(result); + EXPECT_EQ(merged.result_set.size(), expected_size); +} + +TEST_F(InMemoryNodeLevelMergeTest, MergedMerged) +{ + MergedLevel left = this->make_merged_level(128, "a_"); + MergedLevel right = this->make_merged_level(64, "b_"); + + auto left_items = left.result_set.get(); + auto right_items = right.result_set.get(); + std::vector all_keys; + for (const auto& item : left_items) { + all_keys.emplace_back(get_key(item)); + } + for (const auto& item : right_items) { + all_keys.emplace_back(get_key(item)); + } + + Level result = std::move(left).merge(Level{std::move(right)}, /*node_pivot_count=*/4); + + ASSERT_TRUE(batt::is_case(result)); + auto& merged = std::get(result); + EXPECT_EQ(merged.result_set.size(), all_keys.size()); + + auto result_items = merged.result_set.get(); + std::vector result_keys; + for (const auto& item : result_items) { + result_keys.emplace_back(get_key(item)); + } + + EXPECT_EQ(result_keys, all_keys); +} + +TEST_F(InMemoryNodeLevelMergeTest, MergedSegmented) +{ + constexpr usize kIterations = 100; + + for (usize iter = 0; iter < kIterations; ++iter) { + this->rng_ = std::default_random_engine{iter}; + + std::uniform_int_distribution pivot_count_dist(4, 64); + usize node_pivot_count = pivot_count_dist(this->rng_); + i32 max_pivot = static_cast(node_pivot_count); + + MergedLevel left = this->make_merged_level(32, "a_"); + usize left_size = left.result_set.size(); + + SegmentedLevel right = this->make_random_segmented_level( + /*base_page_id=*/iter * 100, + max_pivot); + + std::vector right_originals; + for (usize i = 0; i < right.segment_count(); ++i) { + right_originals.push_back(right.get_segment(i)); + } + + Level result = std::move(left).merge(Level{std::move(right)}, node_pivot_count); + + ASSERT_TRUE(batt::is_case(result)); + auto& hybrid = std::get(result); + + ASSERT_EQ(hybrid.sub_levels.size(), 2u); + ASSERT_TRUE(batt::is_case(hybrid.sub_levels[0])); + ASSERT_TRUE(batt::is_case(hybrid.sub_levels[1])); + + auto& merged_sub = std::get(hybrid.sub_levels[0]); + EXPECT_EQ(merged_sub.result_set.size(), left_size); + + auto& seg_sub = std::get(hybrid.sub_levels[1]); + ASSERT_EQ(seg_sub.segment_count(), right_originals.size()); + this->verify_pivots_shifted(right_originals, seg_sub, node_pivot_count); + } +} + +TEST_F(InMemoryNodeLevelMergeTest, MergedHybrid) +{ + constexpr usize kIterations = 100; + + for (usize iter = 0; iter < kIterations; ++iter) { + this->rng_ = std::default_random_engine{iter}; + + std::uniform_int_distribution pivot_count_dist(4, 64); + usize node_pivot_count = pivot_count_dist(this->rng_); + i32 max_pivot = static_cast(node_pivot_count); + + MergedLevel left = this->make_merged_level(32, "a_"); + usize left_size = left.result_set.size(); + + SegmentedLevel sub_seg = this->make_random_segmented_level( + /*base_page_id=*/iter * 100, + max_pivot); + + std::vector sub_originals; + for (usize i = 0; i < sub_seg.segment_count(); ++i) { + sub_originals.push_back(sub_seg.get_segment(i)); + } + + HybridLevel right = this->make_hybrid_level({std::move(sub_seg)}); + + Level result = std::move(left).merge(Level{std::move(right)}, node_pivot_count); + + ASSERT_TRUE(batt::is_case(result)); + auto& hybrid = std::get(result); + ASSERT_EQ(hybrid.sub_levels.size(), 2u); + + ASSERT_TRUE(batt::is_case(hybrid.sub_levels[0])); + ASSERT_TRUE(batt::is_case(hybrid.sub_levels[1])); + + auto& merged_sub = std::get(hybrid.sub_levels[0]); + EXPECT_EQ(merged_sub.result_set.size(), left_size); + + auto& seg_sub = std::get(hybrid.sub_levels[1]); + ASSERT_EQ(seg_sub.segment_count(), sub_originals.size()); + this->verify_pivots_shifted(sub_originals, seg_sub, node_pivot_count); + } +} + +//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- +// SegmentedLevel::merge tests +//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- + +TEST_F(InMemoryNodeLevelMergeTest, SegmentedEmpty) +{ + SegmentedLevel left = this->make_segmented_level({ + this->make_segment(500, {0, 1}), + this->make_segment(501, {1, 2}), + }); + + Level result = std::move(left).merge(Level{EmptyLevel{}}, /*node_pivot_count=*/4); + + ASSERT_TRUE(batt::is_case(result)); + auto& segmented = std::get(result); + EXPECT_EQ(segmented.segment_count(), 2u); + EXPECT_TRUE(segmented.get_segment(0).is_pivot_active(0)); + EXPECT_TRUE(segmented.get_segment(0).is_pivot_active(1)); +} + +TEST_F(InMemoryNodeLevelMergeTest, SegmentedMerged) +{ + SegmentedLevel left = this->make_segmented_level({this->make_segment(600, {0})}); + MergedLevel right = this->make_merged_level(32, "b_"); + + Level result = std::move(left).merge(Level{std::move(right)}, /*node_pivot_count=*/4); + + ASSERT_TRUE(batt::is_case(result)); + auto& hybrid = std::get(result); + EXPECT_EQ(hybrid.sub_levels.size(), 2u); + EXPECT_TRUE(batt::is_case(hybrid.sub_levels[0])); + EXPECT_TRUE(batt::is_case(hybrid.sub_levels[1])); +} + +TEST_F(InMemoryNodeLevelMergeTest, SegmentedSegmented_NoDuplicates) +{ + constexpr usize kIterations = 100; + + for (usize iter = 0; iter < kIterations; ++iter) { + this->rng_ = std::default_random_engine{iter}; + + std::uniform_int_distribution pivot_count_dist(4, 64); + usize node_pivot_count = pivot_count_dist(this->rng_); + i32 max_pivot = static_cast(node_pivot_count); + + SegmentedLevel left = this->make_random_segmented_level( + /*base_page_id=*/iter * 100, + max_pivot); + + SegmentedLevel right = this->make_random_segmented_level( + /*base_page_id=*/iter * 100 + 50, + max_pivot); + + std::vector left_originals; + for (usize i = 0; i < left.segment_count(); ++i) { + left_originals.push_back(left.get_segment(i)); + } + std::vector right_originals; + for (usize i = 0; i < right.segment_count(); ++i) { + right_originals.push_back(right.get_segment(i)); + } + + Level result = std::move(left).merge(Level{std::move(right)}, node_pivot_count); + + ASSERT_TRUE(batt::is_case(result)); + auto& segmented = std::get(result); + + this->verify_segmented_merge_no_duplicates(left_originals, + right_originals, + segmented, + node_pivot_count); + } +} + +TEST_F(InMemoryNodeLevelMergeTest, SegmentedSegmented_WithDuplicate) +{ + constexpr usize kIterations = 100; + + for (usize iter = 0; iter < kIterations; ++iter) { + this->rng_ = std::default_random_engine{iter}; + + std::uniform_int_distribution pivot_count_dist(4, 64); + usize node_pivot_count = pivot_count_dist(this->rng_); + i32 max_pivot = static_cast(node_pivot_count); + + constexpr u64 kSharedPageId = 99999; + + Segment left_shared = this->make_random_segment(kSharedPageId, max_pivot); + Segment right_shared = this->make_random_segment(kSharedPageId, max_pivot); + + Segment left_original = left_shared; + Segment right_original = right_shared; + + SegmentedLevel left = this->make_segmented_level({std::move(left_shared)}); + SegmentedLevel right = this->make_segmented_level({std::move(right_shared)}); + + Level result = std::move(left).merge(Level{std::move(right)}, node_pivot_count); + + ASSERT_TRUE(batt::is_case(result)); + auto& segmented = std::get(result); + + ASSERT_EQ(segmented.segment_count(), 1u); + + auto& deduped = segmented.get_segment(0); + EXPECT_EQ(deduped.get_leaf_page_id().page_id, llfs::PageId{kSharedPageId}); + this->verify_pivots_deduplication(left_original, right_original, deduped, node_pivot_count); + this->verify_filter_union(left_original, + right_original, + deduped, + /*check_range=*/kFilterItemCount); + } +} + +TEST_F(InMemoryNodeLevelMergeTest, SegmentedHybrid) +{ + constexpr usize kIterations = 100; + + for (usize iter = 0; iter < kIterations; ++iter) { + this->rng_ = std::default_random_engine{iter}; + + std::uniform_int_distribution pivot_count_dist(4, 64); + usize node_pivot_count = pivot_count_dist(this->rng_); + i32 max_pivot = static_cast(node_pivot_count); + + SegmentedLevel left = this->make_random_segmented_level( + /*base_page_id=*/iter * 100, + max_pivot); + + std::vector left_originals; + for (usize i = 0; i < left.segment_count(); ++i) { + left_originals.push_back(left.get_segment(i)); + } + + SegmentedLevel sub_seg = this->make_random_segmented_level( + /*base_page_id=*/iter * 100 + 50, + max_pivot); + + std::vector right_sub_originals; + for (usize i = 0; i < sub_seg.segment_count(); ++i) { + right_sub_originals.push_back(sub_seg.get_segment(i)); + } + + HybridLevel right = this->make_hybrid_level({std::move(sub_seg)}); + + Level result = std::move(left).merge(Level{std::move(right)}, node_pivot_count); + + ASSERT_TRUE(batt::is_case(result)); + auto& hybrid = std::get(result); + ASSERT_EQ(hybrid.sub_levels.size(), 2u); + ASSERT_TRUE(batt::is_case(hybrid.sub_levels[0])); + ASSERT_TRUE(batt::is_case(hybrid.sub_levels[1])); + + auto& left_sub = std::get(hybrid.sub_levels[0]); + this->verify_pivots_unchanged(left_originals, left_sub); + + auto& right_sub = std::get(hybrid.sub_levels[1]); + ASSERT_EQ(right_sub.segment_count(), right_sub_originals.size()); + this->verify_pivots_shifted(right_sub_originals, right_sub, node_pivot_count); + } +} + +//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- +// HybridLevel::merge tests +//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- + +TEST_F(InMemoryNodeLevelMergeTest, HybridEmpty) +{ + MergedLevel sub_merged = this->make_merged_level(32, "a_"); + const usize expected_size = sub_merged.result_set.size(); + HybridLevel left = this->make_hybrid_level({std::move(sub_merged)}); + + Level result = std::move(left).merge(Level{EmptyLevel{}}, /*node_pivot_count=*/4); + + ASSERT_TRUE(batt::is_case(result)); + auto& hybrid = std::get(result); + EXPECT_EQ(hybrid.sub_levels.size(), 1u); + auto& merged_sub = std::get(hybrid.sub_levels[0]); + EXPECT_EQ(merged_sub.result_set.size(), expected_size); +} + +TEST_F(InMemoryNodeLevelMergeTest, HybridMerged) +{ + SegmentedLevel sub_seg = this->make_segmented_level({this->make_segment(1000, {4})}); + HybridLevel left = this->make_hybrid_level({std::move(sub_seg)}); + + MergedLevel right = this->make_merged_level(32, "b_"); + + Level result = std::move(left).merge(Level{std::move(right)}, /*node_pivot_count=*/4); + + ASSERT_TRUE(batt::is_case(result)); + auto& hybrid = std::get(result); + EXPECT_EQ(hybrid.sub_levels.size(), 2u); + EXPECT_TRUE(batt::is_case(hybrid.sub_levels[0])); + EXPECT_TRUE(batt::is_case(hybrid.sub_levels[1])); +} + +TEST_F(InMemoryNodeLevelMergeTest, HybridSegmented) +{ + constexpr usize kIterations = 100; + + for (usize iter = 0; iter < kIterations; ++iter) { + this->rng_ = std::default_random_engine{iter}; + + std::uniform_int_distribution pivot_count_dist(4, 64); + usize node_pivot_count = pivot_count_dist(this->rng_); + i32 max_pivot = static_cast(node_pivot_count); + + MergedLevel sub_merged = this->make_merged_level(16, "a_"); + HybridLevel left = this->make_hybrid_level({std::move(sub_merged)}); + + SegmentedLevel right = this->make_random_segmented_level( + /*base_page_id=*/iter * 100, + max_pivot); + + std::vector right_originals; + for (usize i = 0; i < right.segment_count(); ++i) { + right_originals.push_back(right.get_segment(i)); + } + + Level result = std::move(left).merge(Level{std::move(right)}, node_pivot_count); + + ASSERT_TRUE(batt::is_case(result)); + auto& hybrid = std::get(result); + + ASSERT_EQ(hybrid.sub_levels.size(), 2u); + EXPECT_TRUE(batt::is_case(hybrid.sub_levels[0])); + ASSERT_TRUE(batt::is_case(hybrid.sub_levels[1])); + + auto& seg_sub = std::get(hybrid.sub_levels[1]); + ASSERT_EQ(seg_sub.segment_count(), right_originals.size()); + this->verify_pivots_shifted(right_originals, seg_sub, node_pivot_count); + } +} + +TEST_F(InMemoryNodeLevelMergeTest, HybridHybrid_NoDuplicate) +{ + constexpr usize kIterations = 100; + + for (usize iter = 0; iter < kIterations; ++iter) { + this->rng_ = std::default_random_engine{iter}; + + std::uniform_int_distribution pivot_count_dist(4, 64); + usize node_pivot_count = pivot_count_dist(this->rng_); + i32 max_pivot = static_cast(node_pivot_count); + + MergedLevel left_sub = this->make_merged_level(16, "a_"); + usize left_sub_size = left_sub.result_set.size(); + HybridLevel left = this->make_hybrid_level({std::move(left_sub)}); + + SegmentedLevel right_sub = this->make_random_segmented_level( + /*base_page_id=*/iter * 100, + max_pivot); + + std::vector right_sub_originals; + for (usize i = 0; i < right_sub.segment_count(); ++i) { + right_sub_originals.push_back(right_sub.get_segment(i)); + } + + HybridLevel right = this->make_hybrid_level({std::move(right_sub)}); + + Level result = std::move(left).merge(Level{std::move(right)}, node_pivot_count); + + ASSERT_TRUE(batt::is_case(result)); + auto& hybrid = std::get(result); + ASSERT_EQ(hybrid.sub_levels.size(), 2u); + ASSERT_TRUE(batt::is_case(hybrid.sub_levels[0])); + ASSERT_TRUE(batt::is_case(hybrid.sub_levels[1])); + + auto& merged_sub = std::get(hybrid.sub_levels[0]); + EXPECT_EQ(merged_sub.result_set.size(), left_sub_size); + + auto& seg_sub = std::get(hybrid.sub_levels[1]); + ASSERT_EQ(seg_sub.segment_count(), right_sub_originals.size()); + this->verify_pivots_shifted(right_sub_originals, seg_sub, node_pivot_count); + } +} + +TEST_F(InMemoryNodeLevelMergeTest, HybridHybrid_WithDuplicate) +{ + constexpr usize kIterations = 100; + + for (usize iter = 0; iter < kIterations; ++iter) { + this->rng_ = std::default_random_engine{iter}; + + std::uniform_int_distribution pivot_count_dist(4, 64); + usize node_pivot_count = pivot_count_dist(this->rng_); + i32 max_pivot = static_cast(node_pivot_count); + + constexpr u64 kSharedPageId = 1400; + + Segment left_shared = this->make_random_segment(kSharedPageId, max_pivot); + Segment right_shared = this->make_random_segment(kSharedPageId, max_pivot); + + Segment left_original = left_shared; + Segment right_original = right_shared; + + SegmentedLevel left_sub_seg = this->make_segmented_level({std::move(left_shared)}); + HybridLevel left = this->make_hybrid_level({std::move(left_sub_seg)}); + + Segment extra_seg = this->make_random_segment(/*page_id=*/iter * 100 + 1401, max_pivot); + SegmentedLevel right_sub_seg = this->make_segmented_level({ + std::move(right_shared), + std::move(extra_seg), + }); + HybridLevel right = this->make_hybrid_level({std::move(right_sub_seg)}); + + Level result = std::move(left).merge(Level{std::move(right)}, node_pivot_count); + + ASSERT_TRUE(batt::is_case(result)); + auto& hybrid = std::get(result); + + ASSERT_EQ(hybrid.sub_levels.size(), 2u); + + auto& left_final_sub = std::get(hybrid.sub_levels[0]); + EXPECT_EQ(left_final_sub.segment_count(), 0u); + + auto& right_final_sub = std::get(hybrid.sub_levels[1]); + EXPECT_EQ(right_final_sub.segment_count(), 2u); + + auto& deduped = right_final_sub.get_segment(0); + EXPECT_EQ(deduped.get_leaf_page_id().page_id, llfs::PageId{kSharedPageId}); + this->verify_pivots_deduplication(left_original, right_original, deduped, node_pivot_count); + this->verify_filter_union(left_original, + right_original, + deduped, + /*check_range=*/kFilterItemCount); + } +} + } // namespace diff --git a/src/turtle_kv/tree/in_memory_node_empty_level.cpp b/src/turtle_kv/tree/in_memory_node_empty_level.cpp new file mode 100644 index 0000000..2e636bd --- /dev/null +++ b/src/turtle_kv/tree/in_memory_node_empty_level.cpp @@ -0,0 +1,48 @@ +#include +// + +#include + +#include + +namespace turtle_kv { + +using Level = InMemoryNodeLevel; +using EmptyLevel = InMemoryNodeEmptyLevel; +using MergedLevel = InMemoryNodeMergedLevel; +using SegmentedLevel = InMemoryNodeSegmentedLevel; +using HybridLevel = InMemoryNodeHybridLevel; + + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +Level InMemoryNodeEmptyLevel::merge(Level&& sibling_level, usize node_pivot_count) && +{ + return batt::case_of( + sibling_level, + [&](EmptyLevel&) -> Level { + return *this; + }, + [&](MergedLevel& right_merged_level) -> Level { + return std::move(right_merged_level); + }, + [&](SegmentedLevel& right_segmented_level) -> Level { + right_segmented_level.push_front_pivots(node_pivot_count); + return std::move(right_segmented_level); + }, + [&](HybridLevel& right_hybrid_level) -> Level { + right_hybrid_level.push_front_pivots(node_pivot_count); + return std::move(right_hybrid_level); + }); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +SmallFn InMemoryNodeEmptyLevel::dump() const +{ + return [](std::ostream& out) { + out << "EmptyLevel{}"; + }; +} + +} // namespace turtle_kv diff --git a/src/turtle_kv/tree/in_memory_node_empty_level.hpp b/src/turtle_kv/tree/in_memory_node_empty_level.hpp new file mode 100644 index 0000000..5494822 --- /dev/null +++ b/src/turtle_kv/tree/in_memory_node_empty_level.hpp @@ -0,0 +1,42 @@ +#pragma once + +#include +#include + +#include + +#include + +#include + +namespace turtle_kv { + +//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- +// +/** \brief An empty update buffer level. + */ +struct InMemoryNodeEmptyLevel { + using Self = InMemoryNodeEmptyLevel; + + void drop_after_pivot(i32 split_pivot_i [[maybe_unused]], + const KeyView& split_pivot_key [[maybe_unused]], + llfs::PageLoader& page_loader [[maybe_unused]], + const TreeOptions& tree_options [[maybe_unused]]) + { + // Nothing to do! + } + + void drop_before_pivot(i32 split_pivot_i [[maybe_unused]], + const KeyView& split_pivot_key [[maybe_unused]], + llfs::PageLoader& page_loader [[maybe_unused]], + const TreeOptions& tree_options [[maybe_unused]]) + { + // Nothing to do! + } + + InMemoryNodeLevel merge(InMemoryNodeLevel&& sibling_level, usize node_pivot_count) &&; + + SmallFn dump() const; +}; + +} // namespace turtle_kv diff --git a/src/turtle_kv/tree/in_memory_node_hybrid_level.cpp b/src/turtle_kv/tree/in_memory_node_hybrid_level.cpp new file mode 100644 index 0000000..e950a0e --- /dev/null +++ b/src/turtle_kv/tree/in_memory_node_hybrid_level.cpp @@ -0,0 +1,435 @@ +#include +// + +#include +#include +#include +#include + +#include + +#include + +namespace turtle_kv { + +using Level = InMemoryNodeLevel; +using EmptyLevel = InMemoryNodeEmptyLevel; +using MergedLevel = InMemoryNodeMergedLevel; +using SegmentedLevel = InMemoryNodeSegmentedLevel; +using HybridLevel = InMemoryNodeHybridLevel; +using Segment = InMemoryNodeSegment; + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +bool InMemoryNodeHybridLevel::empty() const +{ + return this->sub_levels.empty(); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +Slice InMemoryNodeHybridLevel::get_levels() const +{ + return as_const_slice(this->sub_levels); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +HybridLevel::SubLevel* InMemoryNodeHybridLevel::front() +{ + if (this->empty()) { + return nullptr; + } + + return &this->sub_levels.front(); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +HybridLevel::SubLevel* InMemoryNodeHybridLevel::back() +{ + if (this->empty()) { + return nullptr; + } + + return &this->sub_levels.back(); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +void InMemoryNodeHybridLevel::add_new_sub_level(HybridLevel::SubLevel&& level, + usize push_pivot_count) +{ + if (push_pivot_count) { + BATT_CHECK(batt::is_case(level)); + SegmentedLevel& segmented_sub_level = std::get(level); + segmented_sub_level.push_front_pivots(push_pivot_count); + } + + this->sub_levels.emplace_back(std::move(level)); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +void InMemoryNodeHybridLevel::add_new_sub_level(HybridLevel&& other, usize push_pivot_count) +{ + if (push_pivot_count) { + other.push_front_pivots(push_pivot_count); + } + + this->sub_levels.insert(this->sub_levels.end(), + std::make_move_iterator(other.sub_levels.begin()), + std::make_move_iterator(other.sub_levels.end())); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +void InMemoryNodeHybridLevel::push_front_pivots(usize node_pivot_count) +{ + for (auto& sub_level : this->sub_levels) { + if (batt::is_case(sub_level)) { + SegmentedLevel& segmented_sub_level = std::get(sub_level); + segmented_sub_level.push_front_pivots(node_pivot_count); + } + } +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +bool InMemoryNodeHybridLevel::set_pivot_items_flushed(const InMemoryNode& node, + BatchUpdateContext& update_context, + usize pivot_i, + const CInterval& flush_key_crange, + Status segment_load_status) +{ + for (auto iter = this->sub_levels.begin(); iter != this->sub_levels.end();) { + bool sub_level_is_now_empty = false; + + batt::case_of( + *iter, + [&](MergedLevel& merged_sub_level) { + sub_level_is_now_empty = merged_sub_level.set_items_flushed(flush_key_crange); + }, + [&](SegmentedLevel& segmented_sub_level) { + sub_level_is_now_empty = segmented_sub_level.set_pivot_items_flushed(node, + update_context, + pivot_i, + flush_key_crange, + segment_load_status); + }); + + if (sub_level_is_now_empty) { + iter = this->sub_levels.erase(iter); + } else { + ++iter; + } + } + + return this->empty(); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +bool InMemoryNodeHybridLevel::set_pivot_completely_flushed(usize pivot_i, + const Interval& pivot_key_range) +{ + for (auto iter = this->sub_levels.begin(); iter != this->sub_levels.end();) { + bool sub_level_is_now_empty = false; + + batt::case_of( + *iter, + [&](MergedLevel& merged_sub_level) { + sub_level_is_now_empty = merged_sub_level.set_items_flushed(pivot_key_range); + }, + [&](SegmentedLevel& segmented_sub_level) { + sub_level_is_now_empty = segmented_sub_level.set_pivot_completely_flushed(pivot_i); + }); + + if (sub_level_is_now_empty) { + iter = this->sub_levels.erase(iter); + } else { + ++iter; + } + } + + return this->empty(); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +BoxedSeq InMemoryNodeHybridLevel::to_boxed_seq(const InMemoryNode& node, + BatchUpdateContext& update_context, + Status& segment_load_status, + i32 min_pivot_i, + bool only_pivot, + Optional min_key) const +{ + return as_seq(this->sub_levels) | + seq::map([&](const std::variant& v) -> BoxedSeq { + return batt::case_of( + v, + [&](const MergedLevel& merged_level) -> BoxedSeq { + return merged_level.to_boxed_seq(node, min_pivot_i); + }, + [&](const SegmentedLevel& segmented_level) -> BoxedSeq { + return segmented_level.to_boxed_seq(node, + update_context, + segment_load_status, + min_pivot_i, + only_pivot, + min_key); + }); + }) | + seq::flatten() | seq::boxed(); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +usize InMemoryNodeHybridLevel::segment_count(const TreeOptions& tree_options) const +{ + usize total = 0; + + for (auto iter = this->sub_levels.begin(); iter != this->sub_levels.end(); ++iter) { + total += batt::case_of( + *iter, + [&](const MergedLevel& merged_sub_level) -> usize { + return merged_sub_level.estimate_segment_count(tree_options); + }, + [&](const SegmentedLevel& segmented_sub_level) -> usize { + return segmented_sub_level.segment_count(); + }); + } + + return total; +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +void InMemoryNodeHybridLevel::drop_before_pivot(i32 pivot_i, + const KeyView& pivot_key, + llfs::PageLoader& page_loader, + const TreeOptions& tree_options) +{ + for (auto iter = this->sub_levels.begin(); iter != this->sub_levels.end(); ++iter) { + batt::case_of(*iter, [&](auto& sub_level) { + sub_level.drop_before_pivot(pivot_i, pivot_key, page_loader, tree_options); + }); + } +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +void InMemoryNodeHybridLevel::drop_after_pivot(i32 pivot_i, + const KeyView& pivot_key, + llfs::PageLoader& page_loader, + const TreeOptions& tree_options) +{ + for (auto iter = this->sub_levels.begin(); iter != this->sub_levels.end(); ++iter) { + batt::case_of(*iter, [&](auto& sub_level) { + sub_level.drop_after_pivot(pivot_i, pivot_key, page_loader, tree_options); + }); + } +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +Status InMemoryNodeHybridLevel::split_pivot(InMemoryNode& node, + BatchUpdateContext& update_context, + i32 pivot_i, + const Interval& pivot_key_range, + const KeyView& sibling_min_key) +{ + for (auto& sub_level : this->sub_levels) { + if (batt::is_case(sub_level)) { + SegmentedLevel& segmented_sub_level = std::get(sub_level); + BATT_REQUIRE_OK(in_segmented_level(node, + segmented_sub_level, + update_context.page_loader, + update_context.overcommit) // + .split_pivot(pivot_i, pivot_key_range, sibling_min_key)); + } + } + + return OkStatus(); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +void InMemoryNodeHybridLevel::merge_pivots(InMemoryNode& node, + BatchUpdateContext& update_context, + i32 left_pivot_i, + i32 right_pivot_i) +{ + for (auto& sub_level : this->sub_levels) { + if (batt::is_case(sub_level)) { + SegmentedLevel& segmented_sub_level = std::get(sub_level); + in_segmented_level(*this, + segmented_sub_level, + update_context.page_loader, + update_context.overcommit) + .merge_pivots(left_pivot_i, right_pivot_i); + } + } +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +StatusOr InMemoryNodeHybridLevel::find_key(const InMemoryNode& node, + KeyQuery& query, + i32 key_pivot_i) const +{ + StatusOr result{Status{batt::StatusCode::kNotFound}}; + + // TODO [vsilai 2026-04-28]: Implement a way to avoid iterating through all sub-levels. + // + for (const auto& sub_level : this->sub_levels) { + result = batt::case_of( + sub_level, + [&](const MergedLevel& merged_sub_level) -> StatusOr { + return merged_sub_level.find_key(query.key()); + }, + [&](const SegmentedLevel& segmented_sub_level) -> StatusOr { + return segmented_sub_level.find_key(node, query, key_pivot_i); + }); + + if (result.ok() || result.status() != batt::StatusCode::kNotFound) { + return result; + } + } + + return result; +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +template +void InMemoryNodeHybridLevel::deduplicate_and_add_sub_level(T&& right_level, usize push_pivot_count) +{ + right_level.push_front_pivots(push_pivot_count); + + BATT_CHECK_NOT_NULLPTR(this->back()); + BATT_CHECK_NOT_NULLPTR(right_level.front()); + + // Attempt deduplication if the last sub level in this HybridLevel is a SegmentedLevel. + // + bool attempt_deduplication = batt::is_case(*this->back()); + + if constexpr (std::is_same_v, HybridLevel>) { + // If `right_level` is also a HybridLevel, we will attempt deduplication if the first sub level + // is a SegmentedLevel. + // + attempt_deduplication = attempt_deduplication && + batt::is_case(*right_level.front()); + } + + if (attempt_deduplication) { + SegmentedLevel& left_sub_level = std::get(*this->back()); + BATT_CHECK_NOT_NULLPTR(left_sub_level.back()); + left_sub_level.deduplicate(right_level); + } + + this->add_new_sub_level(std::move(right_level)); +} + +template void InMemoryNodeHybridLevel::deduplicate_and_add_sub_level(SegmentedLevel&&, usize); +template void InMemoryNodeHybridLevel::deduplicate_and_add_sub_level(HybridLevel&&, usize); + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +Level InMemoryNodeHybridLevel::merge(Level&& sibling_level, usize node_pivot_count) && +{ + batt::case_of( + sibling_level, + [&](EmptyLevel&) { + }, + [&](MergedLevel& right_merged_level) { + this->add_new_sub_level(std::move(right_merged_level)); + }, + [&](SegmentedLevel& right_segmented_level) { + this->deduplicate_and_add_sub_level(std::move(right_segmented_level), node_pivot_count); + }, + [&](HybridLevel& right_hybrid_level) { + this->deduplicate_and_add_sub_level(std::move(right_hybrid_level), node_pivot_count); + }); + + return *this; +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +StatusOr InMemoryNodeHybridLevel::start_serialize(const InMemoryNode& node, + TreeSerializeContext& context) +{ + usize total_segment_count = 0; + + for (auto& sub_level : this->sub_levels) { + StatusOr sub_level_segment_count = batt::case_of( + sub_level, + [&](MergedLevel& merged_sub_level) -> StatusOr { + BATT_ASSIGN_OK_RESULT(usize sub_level_total, + merged_sub_level.start_serialize(node, context)); + return sub_level_total; + }, + [&](SegmentedLevel& segmented_sub_level) -> StatusOr { + return segmented_sub_level.segment_count(); + }); + + BATT_REQUIRE_OK(sub_level_segment_count); + + total_segment_count += *sub_level_segment_count; + } + + return total_segment_count; +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +StatusOr InMemoryNodeHybridLevel::finish_serialize( + const InMemoryNode& node, + TreeSerializeContext& context) +{ + static InMemoryNode::Metrics& r_metrics = InMemoryNode::metrics(); + + SegmentedLevel final_segmented_level; + + for (auto& sub_level : this->sub_levels) { + r_metrics.serialized_nonempty_level_count.add(1); + + StatusOr new_segmented_sub_level = batt::case_of( + sub_level, + [&](MergedLevel& merged_sub_level) -> StatusOr { + return merged_sub_level.finish_serialize(node, context); + }, + [&](SegmentedLevel& segmented_sub_level) -> StatusOr { + r_metrics.serialized_buffer_segment_count.add(segmented_sub_level.segment_count()); + + return {std::move(segmented_sub_level)}; + }); + + BATT_REQUIRE_OK(new_segmented_sub_level); + + final_segmented_level.segments.insert( + final_segmented_level.segments.end(), + std::make_move_iterator(new_segmented_sub_level->segments.begin()), + std::make_move_iterator(new_segmented_sub_level->segments.end())); + } + + return {std::move(final_segmented_level)}; +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +SmallFn InMemoryNodeHybridLevel::dump() const +{ + return [this](std::ostream& out) { + out << "HybridLevel{\n"; + for (auto iter = this->sub_levels.begin(); iter != this->sub_levels.end(); ++iter) { + batt::case_of(*iter, [&out](const auto& sub_level) { + out << " " << sub_level.dump() << ",\n"; + }); + } + out << " }"; + }; +} + +} // namespace turtle_kv diff --git a/src/turtle_kv/tree/in_memory_node_hybrid_level.hpp b/src/turtle_kv/tree/in_memory_node_hybrid_level.hpp new file mode 100644 index 0000000..b0eed78 --- /dev/null +++ b/src/turtle_kv/tree/in_memory_node_hybrid_level.hpp @@ -0,0 +1,105 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +namespace turtle_kv { + +struct InMemoryNode; +struct BatchUpdateContext; +class KeyQuery; + +//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- +// +struct InMemoryNodeHybridLevel { + using SubLevel = std::variant; + + SmallVec sub_levels; + + bool empty() const; + + Slice get_levels() const; + + SubLevel* front(); + + SubLevel* back(); + + void add_new_sub_level(SubLevel&& level, usize push_pivot_count = 0); + + void add_new_sub_level(InMemoryNodeHybridLevel&& other, usize push_pivot_count = 0); + + template + void deduplicate_and_add_sub_level(T&& right_level, usize push_pivot_count = 0); + + void push_front_pivots(usize node_pivot_count); + + bool set_pivot_items_flushed(const InMemoryNode& node, + BatchUpdateContext& update_context, + usize pivot_i, + const CInterval& flush_key_crange, + Status segment_load_status); + + bool set_pivot_completely_flushed(usize pivot_i, const Interval& pivot_key_range); + + BoxedSeq to_boxed_seq(const InMemoryNode& node, + BatchUpdateContext& update_context, + Status& segment_load_status, + i32 min_pivot_i, + bool only_pivot, + Optional min_key) const; + + usize segment_count(const TreeOptions& tree_options) const; + + void drop_before_pivot(i32 pivot_i, + const KeyView& pivot_key, + llfs::PageLoader& page_loader, + const TreeOptions& tree_options); + + void drop_after_pivot(i32 pivot_i, + const KeyView& pivot_key, + llfs::PageLoader& page_loader, + const TreeOptions& tree_options); + + Status split_pivot(InMemoryNode& node, + BatchUpdateContext& update_context, + i32 pivot_i, + const Interval& pivot_key_range, + const KeyView& sibling_min_key); + + void merge_pivots(InMemoryNode& node, + BatchUpdateContext& update_context, + i32 left_pivot_i, + i32 right_pivot_i); + + StatusOr find_key(const InMemoryNode& node, KeyQuery& query, i32 key_pivot_i) const; + + InMemoryNodeLevel merge(InMemoryNodeLevel&& sibling_level, usize node_pivot_count) &&; + + StatusOr start_serialize(const InMemoryNode& node, TreeSerializeContext& context); + + StatusOr finish_serialize(const InMemoryNode& node, + TreeSerializeContext& context); + + SmallFn dump() const; +}; + +} // namespace turtle_kv diff --git a/src/turtle_kv/tree/in_memory_node_merged_level.cpp b/src/turtle_kv/tree/in_memory_node_merged_level.cpp new file mode 100644 index 0000000..bef9665 --- /dev/null +++ b/src/turtle_kv/tree/in_memory_node_merged_level.cpp @@ -0,0 +1,230 @@ +#include +// + +#include +#include +#include +#include + +#include + +#include + +namespace turtle_kv { + +using Level = InMemoryNodeLevel; +using EmptyLevel = InMemoryNodeEmptyLevel; +using MergedLevel = InMemoryNodeMergedLevel; +using SegmentedLevel = InMemoryNodeSegmentedLevel; +using HybridLevel = InMemoryNodeHybridLevel; +using Segment = InMemoryNodeSegment; + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +usize InMemoryNodeMergedLevel::estimate_segment_count(const TreeOptions& tree_options) const +{ + const usize packed_size = this->result_set.get_packed_size(); + if (packed_size == 0) { + return 0; + } + + const usize capacity_per_segment = tree_options.flush_size() - tree_options.max_item_size(); + const usize estimated = (packed_size + capacity_per_segment - 1) / capacity_per_segment; + + BATT_CHECK_GE(estimated * capacity_per_segment, packed_size); + BATT_CHECK_LT((estimated - 1) * capacity_per_segment, packed_size) + << BATT_INSPECT(estimated) << BATT_INSPECT(capacity_per_segment); + + return estimated; +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +InMemoryNodeMergedLevel InMemoryNodeMergedLevel::concat(InMemoryNodeMergedLevel&& that) +{ + return InMemoryNodeMergedLevel{ + .result_set = MergeCompactor::ResultSet::concat(std::move(this->result_set), + std::move(that.result_set)), + .segment_future_ids_ = {}}; +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +bool InMemoryNodeMergedLevel::set_items_flushed(const CInterval& flush_key_crange) +{ + this->result_set.drop_key_range(flush_key_crange); + return this->result_set.empty(); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +bool InMemoryNodeMergedLevel::set_items_flushed(const Interval& flush_key_range) +{ + this->result_set.drop_key_range_half_open(flush_key_range); + return this->result_set.empty(); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +MergeCompactor::ResultSet* InMemoryNodeMergedLevel::front() +{ + if (this->result_set.empty()) { + return nullptr; + } + + return &this->result_set; +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +MergeCompactor::ResultSet* InMemoryNodeMergedLevel::back() +{ + return this->front(); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +BoxedSeq InMemoryNodeMergedLevel::to_boxed_seq(const InMemoryNode& node, + i32 min_pivot_i) const +{ + return this->result_set.live_edit_slices(node.get_pivot_key(min_pivot_i)); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +Level InMemoryNodeMergedLevel::merge(Level&& sibling_level, usize node_pivot_count) && +{ + return batt::case_of( + sibling_level, + [&](EmptyLevel&) -> Level { + return *this; + }, + [&](MergedLevel& right_merged_level) -> Level { + return this->concat(std::move(right_merged_level)); + }, + [&](auto& right_segmented_or_hybrid_level) -> Level { + HybridLevel new_hybrid_level; + new_hybrid_level.add_new_sub_level(std::move(*this)); + + new_hybrid_level.add_new_sub_level(std::move(right_segmented_or_hybrid_level), + node_pivot_count); + + return new_hybrid_level; + }); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +StatusOr InMemoryNodeMergedLevel::start_serialize(const InMemoryNode& node, + TreeSerializeContext& context) +{ + batt::RunningTotal running_total = + compute_running_total(context.worker_pool(), this->result_set, DecayToItem{}); + + SplitParts page_parts = split_parts(running_total, + MinPartSize{context.tree_options().flush_size() / 4}, + MaxPartSize{context.tree_options().flush_size()}, + MaxItemSize{context.tree_options().max_item_size()}); + + BATT_CHECK_EQ(running_total.back() - running_total.front(), this->result_set.get_packed_size()); + + auto filter_bits_per_key = context.tree_options().filter_bits_per_key(); + const bool overcommit_triggered = context.overcommit().is_triggered(); + llfs::PageSize filter_page_size = context.tree_options().filter_page_size(); + + for (const Interval& part_extents : page_parts) { + BATT_ASSIGN_OK_RESULT( + TreeSerializeContext::BuildPageJobId id, + context.async_build_page( + context.tree_options().leaf_size(), + packed_leaf_page_layout_id(), + llfs::LruPriority{kNewLeafLruPriority}, + /*task_count=*/2, + [this, + &node, + part_extents, + filter_bits_per_key, + overcommit_triggered, + filter_page_size]( + TreeSerializeContext::BuildPageArgs args) -> TreeSerializeContext::PinPageToJobFn { + //----- --- -- - - - - + const auto all_items_in_level = this->result_set.get(); + const auto items_in_this_page = batt::slice_range(all_items_in_level, part_extents); + + if (args.task_i == 0) { + return build_leaf_page_in_job(node.tree_options.trie_index_reserve_size(), + args.page_buffer, + items_in_this_page); + } + BATT_CHECK_EQ(args.task_i, 1); + + return build_filter_for_leaf_in_job(batt::make_copy(args.filter_page_write_state), + args.page_cache, + overcommit_triggered, + filter_bits_per_key, + filter_page_size, + args.page_buffer.page_id(), + items_in_this_page); + })); + + this->segment_future_ids_.emplace_back(id); + } + + return page_parts.size(); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +StatusOr InMemoryNodeMergedLevel::finish_serialize( + const InMemoryNode& node, + TreeSerializeContext& context) +{ + BATT_CHECK_EQ(node.tree_options.filter_bits_per_key(), + context.tree_options().filter_bits_per_key()); + BATT_CHECK_EQ(node.tree_options.expected_items_per_leaf(), + context.tree_options().expected_items_per_leaf()); + + SegmentedLevel segmented_level; + + const usize pivot_count = node.pivot_count(); + const usize segment_count = this->segment_future_ids_.size(); + segmented_level.segments.resize(segment_count); + + for (usize segment_i = 0; segment_i < segment_count; ++segment_i) { + Segment& segment = segmented_level.segments[segment_i]; + + BATT_ASSIGN_OK_RESULT(llfs::PinnedPage pinned_leaf_page, + context.get_build_page_result(this->segment_future_ids_[segment_i])); + + segment.page_id_slot.page_id = pinned_leaf_page.page_id(); + segment.active_pivots.clear(); + + const PackedLeafPage& leaf_page = PackedLeafPage::view_of(pinned_leaf_page); + + for (usize pivot_i = 0; pivot_i < pivot_count; ++pivot_i) { + const Interval pivot_key_range = in_node(node).get_pivot_key_range(pivot_i); + + const Interval pivot_range_in_leaf{ + .lower_bound = leaf_page.lower_bound(pivot_key_range.lower_bound), + .upper_bound = leaf_page.lower_bound(pivot_key_range.upper_bound), + }; + + segment.set_pivot_active(pivot_i, !pivot_range_in_leaf.empty()); + } + + segment.check_invariants(__FILE__, __LINE__); + } + + return {std::move(segmented_level)}; +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +SmallFn InMemoryNodeMergedLevel::dump() const +{ + return [this](std::ostream& out) { + out << "MergedLevel{" << this->result_set.debug_dump(" ") << "\n}"; + }; +} + +} // namespace turtle_kv diff --git a/src/turtle_kv/tree/in_memory_node_merged_level.hpp b/src/turtle_kv/tree/in_memory_node_merged_level.hpp new file mode 100644 index 0000000..f91e9ac --- /dev/null +++ b/src/turtle_kv/tree/in_memory_node_merged_level.hpp @@ -0,0 +1,98 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include + +namespace turtle_kv { + +struct InMemoryNode; + +//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- +// +struct InMemoryNodeMergedLevel { + using Self = InMemoryNodeMergedLevel; + + //+++++++++++-+-+--+----- --- -- - - - - + + MergeCompactor::ResultSet result_set; + std::vector segment_future_ids_; + + //+++++++++++-+-+--+----- --- -- - - - - + + void drop_key_range(const Interval& key_drop_range) + { + this->result_set.drop_key_range_half_open(key_drop_range); + } + + void drop_after_pivot(i32 pivot_i [[maybe_unused]], + const KeyView& pivot_key, + llfs::PageLoader& page_loader [[maybe_unused]], + const TreeOptions& tree_options [[maybe_unused]]) + { + this->drop_key_range(Interval{ + .lower_bound = pivot_key, + .upper_bound = global_max_key(), + }); + } + + void drop_before_pivot(i32 pivot_i [[maybe_unused]], + const KeyView& pivot_key, + llfs::PageLoader& page_loader [[maybe_unused]], + const TreeOptions& tree_options [[maybe_unused]]) + { + this->drop_key_range(Interval{ + .lower_bound = global_min_key(), + .upper_bound = pivot_key, + }); + } + + StatusOr find_key(const KeyView& key) const + { + return this->result_set.find_key(key); + } + + //+++++++++++-+-+--+----- --- -- - - - - + + usize estimate_segment_count(const TreeOptions& tree_options) const; + + InMemoryNodeMergedLevel concat(InMemoryNodeMergedLevel&& that); + + BoxedSeq to_boxed_seq(const InMemoryNode& node, i32 min_pivot_i) const; + + bool set_items_flushed(const CInterval& flush_key_crange); + + bool set_items_flushed(const Interval& flush_key_range); + + MergeCompactor::ResultSet* front(); + + MergeCompactor::ResultSet* back(); + + InMemoryNodeLevel merge(InMemoryNodeLevel&& sibling_level, usize node_pivot_count) &&; + + /** \brief Returns the number of segment leaf page build jobs added to the context. + */ + StatusOr start_serialize(const InMemoryNode& node, TreeSerializeContext& context); + + StatusOr finish_serialize(const InMemoryNode& node, + TreeSerializeContext& context); + + SmallFn dump() const; +}; + +} // namespace turtle_kv diff --git a/src/turtle_kv/tree/in_memory_node_segmented_level.cpp b/src/turtle_kv/tree/in_memory_node_segmented_level.cpp new file mode 100644 index 0000000..bba1672 --- /dev/null +++ b/src/turtle_kv/tree/in_memory_node_segmented_level.cpp @@ -0,0 +1,433 @@ +#include +// + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +namespace turtle_kv { + +using Level = InMemoryNodeLevel; +using EmptyLevel = InMemoryNodeEmptyLevel; +using MergedLevel = InMemoryNodeMergedLevel; +using SegmentedLevel = InMemoryNodeSegmentedLevel; +using HybridLevel = InMemoryNodeHybridLevel; +using Segment = InMemoryNodeSegment; + +//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- +// InMemoryNodeSegment +//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +StatusOr InMemoryNodeSegment::load_leaf_page( + llfs::PageLoader& page_loader, + llfs::PinPageToJob pin_page_to_job, + llfs::PageCacheOvercommit& overcommit) const +{ + return this->page_id_slot.load_through(page_loader, + llfs::PageLoadOptions{ + LeafPageView::page_layout_id(), + pin_page_to_job, + llfs::OkIfNotFound{false}, + llfs::LruPriority{kLeafLruPriority}, + overcommit, + }); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +void InMemoryNodeSegment::check_invariants(const char* file, int line) const +{ + BATT_CHECK(this->filter.check_invariants()) << BATT_INSPECT(file) << BATT_INSPECT(line); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +void InMemoryNodeSegment::insert_pivot(i32 pivot_i, bool is_active) +{ + this->check_invariants(__FILE__, __LINE__); + auto on_scope_exit = batt::finally([&] { + this->check_invariants(__FILE__, __LINE__); + }); + + this->active_pivots.insert(pivot_i, is_active); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +void InMemoryNodeSegment::remove_pivot(i32 pivot_i) +{ + this->check_invariants(__FILE__, __LINE__); + auto on_scope_exit = batt::finally([&] { + this->check_invariants(__FILE__, __LINE__); + }); + + this->active_pivots.remove(pivot_i); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +void InMemoryNodeSegment::pop_front_pivots(i32 count) +{ + BATT_CHECK_LT(count, 64); + + this->active_pivots.pop_front_pivots(count); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +bool InMemoryNodeSegment::is_inactive() const +{ + const bool inactive = this->active_pivots.is_empty(); + if (inactive) { + Slice> live_ranges = this->filter.live(); + BATT_CHECK_EQ(live_ranges.size(), 1) << BATT_INSPECT(live_ranges); + BATT_CHECK_EQ(live_ranges[0].upper_bound, PiecewiseFilter::kMaxUpperBound) + << BATT_INSPECT(live_ranges); + } + return inactive; +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +usize InMemoryNodeSegment::num_cut_points() const +{ + Slice> live_ranges = this->filter.live(); + + // If the first element is live, don't include 0 as a cut point, only include the + // upper bound. + // + bool first_element_live = !live_ranges.empty() && + live_ranges.front().lower_bound == PiecewiseFilter::kMinLowerBound; + bool ends_at_max = !live_ranges.empty() && + live_ranges.back().upper_bound == PiecewiseFilter::kMaxUpperBound; + + return live_ranges.size() * 2 - (first_element_live ? 1 : 0) - (ends_at_max ? 1 : 0); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +bool InMemoryNodeSegment::deduplicate(const InMemoryNodeSegment& other) +{ + if (this->page_id_slot.page_id != other.page_id_slot.page_id) { + return false; + } + this->active_pivots |= other.active_pivots; + this->filter.merge(other.filter); + return true; +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +SmallFn InMemoryNodeSegment::dump(bool multi_line) const +{ + return [this, multi_line](std::ostream& out) { + if (multi_line) { + out << "Segment:" << std::endl + << " active=" << this->active_pivots.printable() << std::endl + << " filter=" << this->filter.dump() << std::endl + << std::endl; + } else { + out << "Segment{.active=" << this->active_pivots.printable() + << ", .filter=" << this->filter.dump() << ",}"; + } + }; +} + +//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- +// InMemoryNodeSegmentedLevel +//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +void InMemoryNodeSegmentedLevel::drop_segment(usize i) +{ + this->segments.erase(this->segments.begin() + i); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +void InMemoryNodeSegmentedLevel::drop_pivot_range(const Interval& pivot_i_range, + const Interval& pivot_key_range, + llfs::PageLoader& page_loader, + const TreeOptions& tree_options) +{ + for (Segment& segment : this->segments) { + BATT_CHECK_OK(in_segment(segment).drop_pivot_range(pivot_i_range, + pivot_key_range, + page_loader, + tree_options)); + + if (pivot_i_range.lower_bound == 0) { + segment.pop_front_pivots(pivot_i_range.upper_bound); + } + } + + this->segments.erase(std::remove_if(this->segments.begin(), + this->segments.end(), + [](const Segment& segment) { + return segment.is_inactive(); + }), + this->segments.end()); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +void InMemoryNodeSegmentedLevel::drop_before_pivot(i32 pivot_i, + const KeyView& pivot_key, + llfs::PageLoader& page_loader, + const TreeOptions& tree_options) +{ + this->drop_pivot_range((Interval{0, pivot_i}), + (Interval{global_min_key(), pivot_key}), + page_loader, + tree_options); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +void InMemoryNodeSegmentedLevel::drop_after_pivot(i32 pivot_i, + const KeyView& pivot_key, + llfs::PageLoader& page_loader, + const TreeOptions& tree_options) +{ + this->drop_pivot_range((Interval{pivot_i, InMemoryNode::kMaxTempPivots}), + (Interval{pivot_key, global_max_key()}), + page_loader, + tree_options); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +bool InMemoryNodeSegmentedLevel::is_pivot_active(i32 pivot_i) const +{ + for (const Segment& segment : this->segments) { + if (segment.is_pivot_active(pivot_i)) { + return true; + } + } + return false; +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +void InMemoryNodeSegmentedLevel::check_items_sorted(const InMemoryNode& node, + llfs::PageLoader& page_loader) const +{ + SegmentedLevelScanner scanner{ + node, + *this, + page_loader, + llfs::PinPageToJob::kDefault, + llfs::PageCacheOvercommit::not_allowed(), + }; + + Optional prev_slice_max_key; + usize item_i = 0; + + for (;;) { + Optional edit_slice = scanner.next(); + + if (!edit_slice) { + break; + } + + batt::case_of(*edit_slice, [&](const auto& slice_impl) { + if (slice_impl.empty()) { + return; + } + if (prev_slice_max_key) { + BATT_CHECK_LE(*prev_slice_max_key, get_key(slice_impl.front())); + } + + prev_slice_max_key = std::string{get_key(slice_impl.back())}; + item_i += slice_impl.size(); + }); + } +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +BoxedSeq InMemoryNodeSegmentedLevel::to_boxed_seq(const InMemoryNode& node, + BatchUpdateContext& update_context, + Status& segment_load_status, + i32 min_pivot_i, + bool only_pivot, + Optional min_key) const +{ + if (only_pivot && !this->is_pivot_active(min_pivot_i)) { + return seq::Empty{} // + | seq::boxed(); + } + return SegmentedLevelScanner{ + node, + *this, + update_context.page_loader, + llfs::PinPageToJob::kDefault, + update_context.overcommit, + segment_load_status, + min_pivot_i, + min_key} // + | seq::boxed(); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +bool InMemoryNodeSegmentedLevel::set_pivot_items_flushed(const InMemoryNode& node, + BatchUpdateContext& update_context, + usize pivot_i, + const CInterval& flush_key_crange, + Status& segment_load_status) +{ + segment_load_status.Update( + in_segmented_level(node, *this, update_context.page_loader, update_context.overcommit) + .drop_key_range(pivot_i, flush_key_crange.upper_bound)); + + return this->empty(); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +bool InMemoryNodeSegmentedLevel::set_pivot_completely_flushed(usize pivot_i) +{ + for (usize segment_i = 0; segment_i < this->segment_count();) { + Segment& segment = this->get_segment(segment_i); + + segment.set_pivot_active(pivot_i, false); + + if (segment.is_inactive()) { + this->drop_segment(segment_i); + } else { + ++segment_i; + } + } + + return this->empty(); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +usize InMemoryNodeSegmentedLevel::segment_filter_cut_points() const +{ + usize n = 0; + for (const Segment& segment : this->segments) { + n += segment.num_cut_points(); + } + return n; +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +void InMemoryNodeSegmentedLevel::push_front_pivots(usize node_pivot_count) +{ + for (usize segment_i = 0; segment_i < this->segment_count(); ++segment_i) { + Segment& segment = this->segments[segment_i]; + segment.active_pivots.push_front_pivots(node_pivot_count); + }; +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +StatusOr InMemoryNodeSegmentedLevel::find_key(const InMemoryNode& node, + KeyQuery& query, + i32 key_pivot_i) const +{ + return in_segmented_level(node, *this, *query.page_loader, query.overcommit()) + .find_key(key_pivot_i, query); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +Level InMemoryNodeSegmentedLevel::merge(Level&& sibling_level, usize node_pivot_count) && +{ + return batt::case_of( + sibling_level, + [&](EmptyLevel&) -> Level { + return *this; + }, + [&](MergedLevel& right_merged_level) -> Level { + HybridLevel new_hybrid_level; + new_hybrid_level.add_new_sub_level(std::move(*this)); + new_hybrid_level.add_new_sub_level(std::move(right_merged_level)); + + return new_hybrid_level; + }, + [&](SegmentedLevel& right_segmented_level) -> Level { + // We need to find potential duplicate segments that have arisen from a previous + // split. For these duplicates, we need to merge their metadata. + // + this->deduplicate(right_segmented_level, node_pivot_count); + + // Concatenate the two segment vectors. + // + this->segments.insert(this->segments.end(), + std::make_move_iterator(right_segmented_level.segments.begin()), + std::make_move_iterator(right_segmented_level.segments.end())); + + return *this; + }, + [&](HybridLevel& right_hybrid_level) -> Level { + this->deduplicate(right_hybrid_level, node_pivot_count); + + HybridLevel new_hybrid_level; + new_hybrid_level.add_new_sub_level(std::move(*this)); + new_hybrid_level.add_new_sub_level(std::move(right_hybrid_level)); + + return new_hybrid_level; + }); +} + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +template +void InMemoryNodeSegmentedLevel::deduplicate(T& right_level, usize push_pivot_count) +{ + right_level.push_front_pivots(push_pivot_count); + + BATT_CHECK_NOT_NULLPTR(this->back()); + BATT_CHECK_NOT_NULLPTR(right_level.front()); + + if constexpr (std::is_same_v) { + // Base case: two segmented levels. If the two segements at the seam are the same, discard one. + // + if (right_level.front()->deduplicate(*this->back())) { + this->segments.pop_back(); + } + } else { + // If we have a HybridLevel, only try to deduplicate if the first sub level is + // a SegmentedLevel. + // + if (batt::is_case(*right_level.front())) { + auto& right_sub_level = std::get(*right_level.front()); + this->deduplicate(right_sub_level); + } + } +} + +template void InMemoryNodeSegmentedLevel::deduplicate(SegmentedLevel&, usize); +template void InMemoryNodeSegmentedLevel::deduplicate(HybridLevel&, usize); + +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +SmallFn InMemoryNodeSegmentedLevel::dump() const +{ + return [this](std::ostream& out) { + out << "SegmentedLevel{\n"; + for (const Segment& segment : this->segments) { + out << " " << segment.dump(/*multi_line=*/false) << ",\n"; + } + out << " }"; + }; +} + +} // namespace turtle_kv diff --git a/src/turtle_kv/tree/in_memory_node_segmented_level.hpp b/src/turtle_kv/tree/in_memory_node_segmented_level.hpp new file mode 100644 index 0000000..9e92f99 --- /dev/null +++ b/src/turtle_kv/tree/in_memory_node_segmented_level.hpp @@ -0,0 +1,314 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +namespace turtle_kv { + +struct InMemoryNodeHybridLevel; +struct InMemoryNode; +struct BatchUpdateContext; +class KeyQuery; + +//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- +// +/** \brief Mutable, in-memory representation of a serialized buffer segment (one leaf page). + */ +struct InMemoryNodeSegment { + using Self = InMemoryNodeSegment; + + /** \brief The id of the leaf page for this segment. + */ + llfs::PageIdSlot page_id_slot; + + /** \brief A bit set of pivots in whose key range this segment contains items. + */ + ActivePivotsSet128 active_pivots; + + /** \brief A filter over the flushed items in this segment. + */ + PiecewiseFilter filter; + + //+++++++++++-+-+--+----- --- -- - - - - + + /** \brief Returns a reference to the PageId of this segment's leaf page, plus weak reference + * to its cache slot (if known). + */ + const llfs::PageIdSlot& get_leaf_page_id() const + { + return this->page_id_slot; + } + + /** \brief Returns the active pivots bit set. + */ + ActivePivotsSet128 get_active_pivots() const + { + return this->active_pivots; + } + + /** \brief Marks this segment as containing (or not) active keys addressed to `pivot_i`. + */ + void set_pivot_active(i32 pivot_i, bool active) + { + this->active_pivots.set(pivot_i, active); + } + + /** \brief Returns true iff this segment has active keys addressed to `pivot_i`. + */ + bool is_pivot_active(i32 pivot_i) const + { + return this->active_pivots.get(pivot_i); + } + + template + Interval drop_key_range(const BasicInterval& key_range, + const Slice& items) + { + return drop_item_range(this->filter, items, key_range, llfs::KeyRangeOrder{}); + } + + void drop_index_range(Interval i) + { + this->filter.drop_index_range(i); + } + + bool is_index_filtered(const InMemoryNodeSegmentedLevel&, u32 index) const + { + return !this->filter.live_at_index(index); + } + + u32 live_lower_bound(const InMemoryNodeSegmentedLevel&, u32 item_i) const + { + return this->filter.live_lower_bound(item_i); + } + + Interval get_live_item_range(const InMemoryNodeSegmentedLevel&, Interval i) const + { + return this->filter.find_live_range(i); + } + + //+++++++++++-+-+--+----- --- -- - - - - + + /** \brief Panic if filter invariants are not satisfied. + */ + void check_invariants(const char* file, int line) const; + + /** \brief Inserts a new pivot bit in this->active_pivots at position + * `pivot_i`. This is called when a child subtree needs to be split. + */ + void insert_pivot(i32 pivot_i, bool is_active); + + /** \brief Removes a bit in the active pivots bit set at position `pivot_i`. + */ + void remove_pivot(i32 pivot_i); + + /** \brief Removes the specified number (`count`) pivots from the front of this segment. This + * is used while splitting a node's update buffer. + */ + void pop_front_pivots(i32 count); + + /** \brief Returns true iff this segment is not active for any pivots. + */ + bool is_inactive() const; + + /** \brief Loads the leaf page for this Segment, returning the resulting llfs::PinnedPage. + */ + StatusOr load_leaf_page(llfs::PageLoader& page_loader, + llfs::PinPageToJob pin_page_to_job, + llfs::PageCacheOvercommit& overcommit) const; + + /** \brief Calculates the number of element needed for the serialized array representation of + * PiecewiseFilter. + */ + usize num_cut_points() const; + + /** \brief Deduplicates two identical segments, if their page ids are the same. + * + * If the deduplication occurs, `true` is returned. Otherwise, `false` is returned. + */ + [[nodiscard]] bool deduplicate(const InMemoryNodeSegment& other); + + /** \brief Prints a human-readable representation of this Segment. + */ + SmallFn dump(bool multi_line = true) const; +}; + +//=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- +// +/** \brief Mutable, in-memory representation of a non-empty serialized update buffer level. + */ +struct InMemoryNodeSegmentedLevel { + using Self = InMemoryNodeSegmentedLevel; + using Segment = InMemoryNodeSegment; + + //+++++++++++-+-+--+----- --- -- - - - - + + SmallVec segments; + + //+++++++++++-+-+--+----- --- -- - - - - + + bool empty() const + { + return this->segments.empty(); + } + + usize segment_count() const + { + return this->segments.size(); + } + + Segment& get_segment(usize i) + { + return this->segments[i]; + } + + const Segment& get_segment(usize i) const + { + return this->segments[i]; + } + + Slice get_segments_slice() const + { + return as_const_slice(this->segments); + } + + InMemoryNodeSegment* front() + { + if (this->segments.empty()) { + return nullptr; + } + + return &this->segments.front(); + } + + InMemoryNodeSegment* back() + { + if (this->segments.empty()) { + return nullptr; + } + + return &this->segments.back(); + } + + //+++++++++++-+-+--+----- --- -- - - - - + + /** \brief Removes the specified segment from this level. + * + * Should only be called by SegmentedLevelAlgorithms::flush_pivot_up_to_key. + */ + void drop_segment(usize i); + + /** \brief Removes the specified set of pivots from this level. + * + * Used to implement node splits. + */ + void drop_pivot_range(const Interval& pivot_i_range, + const Interval& pivot_key_range, + llfs::PageLoader& page_loader, + const TreeOptions& tree_options); + + /** \brief Drops all pivots before (but not including) the specified pivot. + * + */ + void drop_before_pivot(i32 pivot_i, + const KeyView& pivot_key, + llfs::PageLoader& page_loader, + const TreeOptions& tree_options); + + /** \brief Drops all pivots after (and including) the specified pivot. + * + */ + void drop_after_pivot(i32 pivot_i, + const KeyView& pivot_key, + llfs::PageLoader& page_loader, + const TreeOptions& tree_options); + + /** \brief Returns true iff the specified pivot is active for any of the Segments in this + * level. + */ + bool is_pivot_active(i32 pivot_i) const; + + /** \brief Verifies that all items appear in this level in key-sorted order; panic if this is + * not the case. + * + * Warning: This is a very expensive operation! Do not call it on a performance-critical code + * path. + */ + void check_items_sorted(const InMemoryNode& node, llfs::PageLoader& page_loader) const; + + /** \brief Converts the unflushed items in this level to a boxed sequence. + */ + BoxedSeq to_boxed_seq(const InMemoryNode& node, + BatchUpdateContext& update_context, + Status& segment_load_status, + i32 min_pivot_i, + bool only_pivot, + Optional min_key) const; + + /** \brief Marks the items contained in `flush_key_crange` that are addressed to `pivot_i` + * as flushed within this level. + */ + bool set_pivot_items_flushed(const InMemoryNode& node, + BatchUpdateContext& update_context, + usize pivot_i, + const CInterval& flush_key_crange, + Status& segment_load_status); + + /** \brief Marks the pivot `pivot_i` as completely flushed within this level. + */ + bool set_pivot_completely_flushed(usize pivot_i); + + /** \brief Calculates the number of filter cut points needed for this level when it will + * be serialized. + */ + usize segment_filter_cut_points() const; + + /** \brief Removes the specified number pivots from the end of the `active_pivots` bit set for + * each segment in this level. + */ + void push_front_pivots(usize node_pivot_count); + + StatusOr find_key(const InMemoryNode& node, KeyQuery& query, i32 key_pivot_i) const; + + /** \brief Merges this level with a "sibling" level from another node. + * + * This function is called when two nodes are being merged and their update buffers are + * being merged as well. In this function, this level is the "left" level (i.e., the level + * comes from the left node in the merge) and `sibling_level` is the "right" level. + * + * `node_pivot_count` is the number of pivots in the left node (i.e., the node that this + * level exists in). + */ + InMemoryNodeLevel merge(InMemoryNodeLevel&& sibling_level, usize node_pivot_count) &&; + + /** \brief Deduplicates segments on the seam between two levels from two different nodes that + * have arisen due to a prior node split. + */ + template + void deduplicate(T& right_level, usize push_pivot_count = 0); + + /** \brief Prints a human-readable representation of the level. + */ + SmallFn dump() const; +}; + +} // namespace turtle_kv diff --git a/src/turtle_kv/tree/packed_node_page.cpp b/src/turtle_kv/tree/packed_node_page.cpp index 0cc066d..bff419e 100644 --- a/src/turtle_kv/tree/packed_node_page.cpp +++ b/src/turtle_kv/tree/packed_node_page.cpp @@ -102,9 +102,9 @@ PackedNodePage* build_node_page(const MutableBuffer& buffer, const InMemoryNode& //+++++++++++-+-+--+----- --- -- - - - - // Pack the update buffer - using EmptyLevel = InMemoryNode::UpdateBuffer::EmptyLevel; - using SegmentedLevel = InMemoryNode::UpdateBuffer::SegmentedLevel; - using Segment = InMemoryNode::UpdateBuffer::Segment; + using EmptyLevel = InMemoryNodeEmptyLevel; + using SegmentedLevel = InMemoryNodeSegmentedLevel; + using Segment = InMemoryNodeSegment; // Initialize the array containing cut points for segment filters. // @@ -129,7 +129,7 @@ PackedNodePage* build_node_page(const MutableBuffer& buffer, const InMemoryNode& packed_node->update_buffer.level_start[level_i] = BATT_CHECKED_CAST(u8, dst_segment_i); } - const InMemoryNode::UpdateBuffer::Level& src_level = src_node.update_buffer.levels[level_i]; + const InMemoryNodeLevel& src_level = src_node.update_buffer.levels[level_i]; if (batt::is_case(src_level)) { continue; diff --git a/src/turtle_kv/tree/subtree.cpp b/src/turtle_kv/tree/subtree.cpp index 59bb9e7..9bc6fda 100644 --- a/src/turtle_kv/tree/subtree.cpp +++ b/src/turtle_kv/tree/subtree.cpp @@ -221,7 +221,8 @@ Status Subtree::apply_batch_update(const TreeOptions& tree_options, // If this is the root level and tree needs to grow/shrink in height, do so now. // - if (is_root) { + SubtreeViability new_subtree_viability = new_subtree->get_viability(); + if (is_root && !is_root_viable(new_subtree_viability)) { BATT_REQUIRE_OK( Subtree::make_root_viable(*new_subtree, tree_options, update.context, key_upper_bound)); } @@ -245,8 +246,6 @@ Status Subtree::apply_batch_update(const TreeOptions& tree_options, return OkStatus(); }, [&](NeedsSplit needs_split) { - // TODO [vsilai 2025-12-09]: revist when VLDB changes are merged in. - // if (normal_flush_might_fix_root(needs_split)) { Status flush_status = new_subtree.try_flush(update_context); if (flush_status.ok() && batt::is_case(new_subtree.get_viability())) { @@ -262,9 +261,12 @@ Status Subtree::apply_batch_update(const TreeOptions& tree_options, return status; }, [&](const NeedsMerge& needs_merge) { - BATT_CHECK(!needs_merge.single_pivot) - << "TODO [tastolfi 2025-03-26] implement flush and shrink"; - return OkStatus(); + Status status = new_subtree.flush_and_shrink(update_context); + + if (!status.ok()) { + LOG(INFO) << "flush_and_shrink failed;" << BATT_INSPECT(needs_merge); + } + return status; })); return OkStatus(); @@ -300,6 +302,50 @@ Status Subtree::split_and_grow(BatchUpdateContext& update_context, return OkStatus(); } +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +Status Subtree::flush_and_shrink(BatchUpdateContext& context) noexcept +{ + BATT_CHECK(!this->locked_.load()); + + BATT_CHECK(!this->is_serialized()); + + usize retries = 0; + + // TODO [vsilai 2026-04-28]: Consider allowing shrink with non-empty levels (pending bytes > 0), + // when all the levels of this node and its child will fit in a single buffer. + // + SubtreeViability root_viability = this->get_viability(); + while (!is_root_viable(root_viability) && retries < kMaxPivots) { + BATT_CHECK(batt::is_case(root_viability)); + + ++retries; + + // First, try flushing. If flushing makes the root viable, return immediately. + // + Status flush_status = this->try_flush(context); + if (!flush_status.ok() && flush_status != batt::StatusCode::kUnavailable) { + return flush_status; + } + + // Nothing was available to flush since either the node's update buffer is empty or we have + // a leaf root. If possible and necessary, try collapsing one level of the tree. + // + if (flush_status == batt::StatusCode::kUnavailable) { + BATT_REQUIRE_OK(this->try_shrink()); + retries = 0; + } + + root_viability = this->get_viability(); + } + + if (retries >= kMaxPivots) { + return batt::Status{batt::StatusCode::kInternal}; + } + + return OkStatus(); +} + //==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - // StatusOr Subtree::get_height(llfs::PageLoader& page_loader, @@ -527,6 +573,41 @@ StatusOr> Subtree::try_split(BatchUpdateContext& context) }); } +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +Status Subtree::try_merge(BatchUpdateContext& context, Subtree&& sibling) noexcept +{ + BATT_CHECK(!this->locked_.load()); + + BATT_ASSIGN_OK_RESULT(i32 this_height, this->get_height(context.page_loader, context.overcommit)); + BATT_ASSIGN_OK_RESULT(i32 sibling_height, + sibling.get_height(context.page_loader, context.overcommit)); + + BATT_CHECK_EQ(this_height, sibling_height); + + return batt::case_of( + this->impl_, + + [&](const llfs::PageIdSlot& page_id_slot) -> Status { + BATT_PANIC() << "Cannot try merging a serialized subtree!"; + + return {batt::StatusCode::kUnimplemented}; + }, + + [&](auto& in_memory) -> Status { + using PtrT = std::decay_t; + + BATT_CHECK(batt::is_case(sibling.impl_)) + << "Sibling Subtree must be the same in-memory type as this Subtree!"; + auto& sibling_ptr = std::get(sibling.impl_); + BATT_CHECK_NOT_NULLPTR(sibling_ptr); + + BATT_REQUIRE_OK(in_memory->try_merge(context, std::move(sibling_ptr))); + + return OkStatus(); + }); +} + //==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - // Status Subtree::try_flush(BatchUpdateContext& context) @@ -541,7 +622,7 @@ Status Subtree::try_flush(BatchUpdateContext& context) }, [&](const std::unique_ptr& leaf [[maybe_unused]]) -> Status { - return OkStatus(); + return {batt::StatusCode::kUnavailable}; }, [&](const std::unique_ptr& node) -> Status { @@ -549,6 +630,41 @@ Status Subtree::try_flush(BatchUpdateContext& context) }); } +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +Status Subtree::try_shrink() noexcept +{ + BATT_CHECK(!this->locked_.load()); + + StatusOr new_root = batt::case_of( + this->impl_, + + [&](const llfs::PageIdSlot& page_id_slot [[maybe_unused]]) -> StatusOr { + return {batt::StatusCode::kUnimplemented}; + }, + + [&](const std::unique_ptr& leaf [[maybe_unused]]) -> StatusOr { + // If the root is a leaf and there are no items in the leaf, set the root to be an empty + // subtree. + // + if (!leaf->get_item_count()) { + return llfs::PageIdSlot::from_page_id(llfs::PageId{}); + } + + return {std::move(*this)}; + }, + + [&](const std::unique_ptr& node) -> StatusOr { + return node->shrink_or_panic(); + }); + + BATT_REQUIRE_OK(new_root); + + this->impl_ = std::move(new_root->impl_); + + return OkStatus(); +} + //==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - // llfs::PackedPageId Subtree::packed_page_id_or_panic() const @@ -646,4 +762,57 @@ void Subtree::lock() this->locked_.store(true); } +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +Status Subtree::unpack_if_necessary(llfs::PageLoader& page_loader, + llfs::PageCacheOvercommit& overcommit, + batt::WorkerPool& worker_pool, + const TreeOptions& tree_options, + i32 height) noexcept +{ + BATT_CHECK_GT(height, 0); + + if (this->is_serialized()) { + llfs::PageIdSlot& page_id_slot = std::get(this->impl_); + + BATT_CHECK(page_id_slot.is_valid()); + + const llfs::PageLayoutId expected_layout = Subtree::expected_layout_for_height(height); + + StatusOr status_or_pinned_page = page_id_slot.load_through( + page_loader, + llfs::PageLoadOptions{ + expected_layout, + llfs::PinPageToJob::kDefault, + llfs::OkIfNotFound{false}, + llfs::LruPriority{(height > 2) ? kNodeLruPriority : kLeafLruPriority}, + overcommit, + }); + + BATT_REQUIRE_OK(status_or_pinned_page) << BATT_INSPECT(height); + + llfs::PinnedPage& pinned_page = *status_or_pinned_page; + + if (height == 1) { + const PackedLeafPage& packed_leaf = PackedLeafPage::view_of(pinned_page); + + std::unique_ptr new_leaf = InMemoryLeaf::unpack(batt::make_copy(pinned_page), + tree_options, + packed_leaf, + worker_pool); + + this->impl_ = std::move(new_leaf); + } else { + const PackedNodePage& packed_node = PackedNodePage::view_of(pinned_page); + + BATT_ASSIGN_OK_RESULT( + std::unique_ptr node, + InMemoryNode::unpack(batt::make_copy(pinned_page), tree_options, packed_node)); + + this->impl_ = std::move(node); + } + } + + return OkStatus(); +} } // namespace turtle_kv diff --git a/src/turtle_kv/tree/subtree.hpp b/src/turtle_kv/tree/subtree.hpp index d26f8ad..db4ee8d 100644 --- a/src/turtle_kv/tree/subtree.hpp +++ b/src/turtle_kv/tree/subtree.hpp @@ -159,10 +159,19 @@ class Subtree */ StatusOr> try_split(BatchUpdateContext& context); - /** \brief Attempt to make the root viable by flushing a batch. + /** \brief Merges the Subtree in place with `sibling`. + */ + Status try_merge(BatchUpdateContext& context, Subtree&& sibling) noexcept; + + /** \brief Attempt to make the root viable by flushing a batch. If nothing is available to + * flush, returns batt::StatusCode::kUnavailable. */ Status try_flush(BatchUpdateContext& context); + /** \brief Attempt to collapse a level of the tree. + */ + Status try_shrink() noexcept; + /** \brief Returns true iff this Subtree has no in-memory modifications. */ bool is_serialized() const; @@ -193,12 +202,27 @@ class Subtree */ bool is_locked() const; + /** \brief Converts a serialized Subtree to its in-memory equivalent, modifying the Subtree in + * place. If the Subtree is already an in-memory type, this function does nothing. + */ + Status unpack_if_necessary(llfs::PageLoader& page_loader, + llfs::PageCacheOvercommit& overcommit, + batt::WorkerPool& worker_pool, + const TreeOptions& tree_options, + i32 height) noexcept; + //+++++++++++-+-+--+----- --- -- - - - - private: Status split_and_grow(BatchUpdateContext& context, const TreeOptions& tree_options, const KeyView& key_upper_bound); + /** \brief Called when the root of the tree is a node with a single pivot. This function + * flushes the root's update buffer until its is either empty + * (causing the tree to shrink in height) or until it gains more pivots. + */ + Status flush_and_shrink(BatchUpdateContext& context) noexcept; + //+++++++++++-+-+--+----- --- -- - - - - std::variant, std::unique_ptr> diff --git a/src/turtle_kv/tree/subtree_viability.hpp b/src/turtle_kv/tree/subtree_viability.hpp index 0f6416d..d4879b1 100644 --- a/src/turtle_kv/tree/subtree_viability.hpp +++ b/src/turtle_kv/tree/subtree_viability.hpp @@ -26,6 +26,7 @@ struct NeedsMerge { bool single_pivot : 1 = false; bool too_few_pivots : 1 = false; bool too_few_items : 1 = false; + bool zero_items : 1 = false; //+++++++++++-+-+--+----- --- -- - - - - @@ -40,7 +41,7 @@ inline std::ostream& operator<<(std::ostream& out, const NeedsMerge& t) { return out << "NeedsMerge{.single_pivot=" << t.single_pivot << ", .too_few_pivots=" << t.too_few_pivots << ", .too_few_items=" << t.too_few_items - << ",}"; + << ", .zero_items=" << t.zero_items << ",}"; } //=#=#==#==#===============+=+=+=+=++=++++++++++++++-++-+--+-+----+--------------- @@ -160,4 +161,21 @@ inline bool normal_flush_might_fix_root(const SubtreeViability& viability) }); } +//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - - +// +inline bool is_root_viable(const SubtreeViability& viability) +{ + return batt::case_of( + viability, + [](const Viable&) { + return true; + }, + [](const NeedsSplit&) { + return false; + }, + [](const NeedsMerge& needs_merge) { + return !needs_merge.single_pivot && !needs_merge.zero_items; + }); +} + } // namespace turtle_kv diff --git a/src/turtle_kv/tree/update_buffer_levels.hpp b/src/turtle_kv/tree/update_buffer_levels.hpp new file mode 100644 index 0000000..0ae88da --- /dev/null +++ b/src/turtle_kv/tree/update_buffer_levels.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include + +namespace turtle_kv { + +struct InMemoryNodeEmptyLevel; +struct InMemoryNodeMergedLevel; +struct InMemoryNodeSegmentedLevel; +struct InMemoryNodeHybridLevel; + +using InMemoryNodeLevel = std::variant; + +} // namespace turtle_kv