diff --git a/bindings/c/src/dispatcher_dynamic_vamana.cpp b/bindings/c/src/dispatcher_dynamic_vamana.cpp index eeb2ef458..f8b515591 100644 --- a/bindings/c/src/dispatcher_dynamic_vamana.cpp +++ b/bindings/c/src/dispatcher_dynamic_vamana.cpp @@ -301,17 +301,10 @@ svs::index::vamana::MemoryBreakdown dispatch_dynamic_vamana_memory_estimate( estimate_data_size_blocked(storage, num_vectors, dimension, block_params); // Metadata: single entry point held as Idx, plus the SlotMetadata vector, plus the - // IDTranslator maps. + // IDTranslator tables. size_t metadata_bytes = sizeof(index_type) + sizeof(svs::index::vamana::SlotMetadata) * num_vectors; - // The IDTranslator holds two tsl::robin_map instances (external->internal and - // internal->external), neither of which exposes its allocated byte count. We - // approximate the storage as the id pair held in each of the two directions. This - // ignores the maps' load-factor slack and control bytes, so it is an estimate of - // the hash-map overhead that is accurate to within a few percent. - metadata_bytes += - 2 * num_vectors * - (sizeof(IDTranslator::external_id_type) + sizeof(IDTranslator::internal_id_type)); + metadata_bytes += IDTranslator::estimate_memory_usage(num_vectors); breakdown.metadata_bytes = metadata_bytes; return breakdown; } diff --git a/include/svs/concurrent/dynamic_index.h b/include/svs/concurrent/dynamic_index.h index 1fc1a8980..fe217a458 100644 --- a/include/svs/concurrent/dynamic_index.h +++ b/include/svs/concurrent/dynamic_index.h @@ -229,7 +229,7 @@ class MutableVamanaIndex { // < *first_reusable_ is Empty. std::unique_ptr> first_reusable_{ std::make_unique>(0)}; - IDTranslator translator_; + ConcurrentIDTranslator translator_; // Count of Valid slots. Maintained atomically in add_points/delete_entry. // Wrapped in unique_ptr because std::atomic is not movable. std::unique_ptr> num_valid_{ @@ -596,7 +596,7 @@ class MutableVamanaIndex { /// /// Reports the capacity-based bytes reserved by the graph adjacency lists, the vector /// data, and the dynamic metadata (per-slot status, entry-point list, and the - /// external/internal ID translation maps). Capacity-based accounting includes the + /// external/internal ID translation tables). Capacity-based accounting includes the /// block over-allocation so integrators can report the true memory footprint. MemoryBreakdown get_memory_breakdown() const { MemoryBreakdown usage{}; @@ -606,14 +606,7 @@ class MutableVamanaIndex { size_t metadata_bytes = status_.capacity() * sizeof(SlotMetadata); metadata_bytes += entry_point_.capacity() * sizeof(typename entry_point_type::value_type); - // The IDTranslator holds two tsl::robin_map instances (external->internal and - // internal->external), neither of which exposes its allocated byte count. We - // approximate the storage as the id pair held in each of the two directions. This - // ignores the maps' load-factor slack and control bytes, so it is an estimate of - // the hash-map overhead that is accurate to within a few percent. - metadata_bytes += 2 * translator_.size() * - (sizeof(IDTranslator::external_id_type) + - sizeof(IDTranslator::internal_id_type)); + metadata_bytes += translator_.get_memory_usage(); usage.metadata_bytes = metadata_bytes; if (const auto* reverse_edges = graph_.reverse_edges()) { usage.reverse_edges_bytes = reverse_edges->memory_bytes(); @@ -646,26 +639,18 @@ class MutableVamanaIndex { ///// Index translation. // - // The translator is a pair of hash maps mutated by `add_points` (insert), - // `consolidate` (erase), and `compact` (remap) under `translator_mutex_` exclusive. A - // hash-map read concurrent with an insert is a data race in the strict sense and a - // crash in practice: an insert can rehash and free the bucket array a reader is - // walking. + // `add_points`, `consolidate`, and `compact` mutate the translator under the exclusive + // lock. Its external-to-internal hash map can rehash, so reads also require the shared + // lock. This ensures each batch sees a consistent state. // - // So every read of `translator_` happens under `translator_mutex_` shared. Each - // translation operation comes in two flavours: + // Locking accessors (`foo`) acquire the shared lock; `unsafe_foo` accessors require + // the caller to hold `lock_for_translation()`. Use the latter for batches or when + // already holding the lock: `std::shared_mutex` is non-recursive, so reacquiring it + // can deadlock. Internal-to-external reads follow the same locking scheme. // - // * `foo(...)` -- takes the shared lock itself. Use this by default. - // * `unsafe_foo(...)` -- assumes the caller already holds the shared lock (via - // `lock_for_translation()`). Use this to translate a *batch* - // of ids under one lock acquisition, and inside code that - // already holds the lock. - // - // The split is not merely an optimization: `std::shared_mutex` is not recursive, so a - // self-locking accessor called from a context that already holds the lock is a latent - // deadlock (a writer arriving between the two shared acquisitions blocks the second). - // That is why the batch paths below, and `BatchIterator::next`, use the `unsafe_` - // variants under an explicit lock rather than paying per-id locking. + // TODO: `ConcurrentIDTranslator` would allow internal->external reads without the + // lock, but the accessors below do not rely on that. Consider using it to avoid + // unnecessary locks. /// /// @brief Get the internal ID mapped to be `e`. @@ -1871,7 +1856,7 @@ class MutableVamanaIndex { const Graph& view_graph() const { return graph_; } // Not synchronized: callers must exclude concurrent mutation. - const IDTranslator& view_translator() const { return translator_; } + const ConcurrentIDTranslator& view_translator() const { return translator_; } // Not synchronized: callers must exclude concurrent mutation. std::vector status_snapshot() const { diff --git a/include/svs/core/translation.h b/include/svs/core/translation.h index 88b95311f..e937c0f62 100644 --- a/include/svs/core/translation.h +++ b/include/svs/core/translation.h @@ -27,6 +27,7 @@ #include "svs/lib/narrow.h" #include "svs/lib/readwrite.h" #include "svs/lib/saveload.h" +#include "svs/lib/segmented_vector.h" #include "svs/lib/threads.h" #include "svs/third-party/fmt.h" @@ -35,13 +36,90 @@ #include "tsl/robin_map.h" // stl +#include +#include #include #include +#include +#include #include +#include +#include namespace svs { -class IDTranslator { +namespace detail { + +// Storage and slot access for the internal->external table of ``IDTranslatorBase``. +// ``load`` yields ``default_val`` for an index beyond the table, and ``store`` fills the +// slots it has to add below the stored index with its last argument. +template struct VectorMapTraits; + +template struct VectorMapTraits { + using value_type = T; + using vector_type = std::vector; + + static value_type load(vector_type const& table, size_t i, value_type default_val) { + return i < table.size() ? table[i] : default_val; + } + + static void store(vector_type& table, size_t i, value_type external, value_type def) { + if (i >= table.size()) { + table.resize(i + 1, def); + } + table[i] = external; + } +}; + +// Readers may run without a lock against one writer: ``SegmentedVector`` never relocates a +// slot when it grows, and every slot access after construction is atomic. A plain read or +// write of a slot here would race with those readers. +template struct VectorMapTraits { + using value_type = T; + using vector_type = lib::SegmentedVector; + + static value_type load(vector_type const& table, size_t i, value_type default_val) { + if (i >= table.size()) { + return default_val; + } + // C++20 has no ``std::atomic_ref``; the cast only removes the constness + // of the table reference, the slot itself is never a const object. + return std::atomic_ref(const_cast(table[i])) + .load(std::memory_order_acquire); + } + + static void + store(vector_type& table, size_t i, value_type external, value_type default_val) { + if (i >= table.size()) { + table.resize(i + 1, default_val); + } + std::atomic_ref(table[i]).store(external, std::memory_order_release); + } +}; + +/// +/// @brief Two-way translation between external IDs and internal IDs. +/// +/// External IDs map to internal IDs through a hash map. Internal IDs map back through a +/// table indexed by internal ID, so internal IDs are expected to be dense: the table +/// holds one ``external_id_type`` per slot up to the largest internal ID ever stored. +/// +/// @tparam Concurrent Selects the storage of the internal-to-external table. Use the +/// aliases ``svs::IDTranslator`` (``false``) and ``svs::ConcurrentIDTranslator`` +/// (``true``); the template itself is not part of the public API. +/// +/// With ``Concurrent == false`` the translator offers no thread safety beyond concurrent +/// ``const`` access. +/// +/// With ``Concurrent == true``: +/// * Mutating methods must be serialized by the caller (one writer at a time). +/// * ``has_internal``, ``get_external`` and ``get_external_or`` may be called without a +/// lock while a writer is running. They observe each slot either before or after the +/// writer's update of that slot. +/// * Every other method reads the external-to-internal hash map and must be synchronized +/// with writers by the caller, e.g. with a shared lock. +/// +template class IDTranslatorBase { public: using internal_id_type = uint32_t; using external_id_type = uint64_t; @@ -50,6 +128,11 @@ class IDTranslator { tsl::robin_map::const_iterator; using value_type = typename const_iterator::value_type; + /// Marks an unmapped slot in the internal-to-external table. Reserved: it is rejected + /// as an external ID. + static constexpr external_id_type invalid_external_id = + std::numeric_limits::max(); + // Construct the identity transformation of size `n`. struct Identity { Identity() = delete; @@ -58,25 +141,48 @@ class IDTranslator { size_t n_; }; - IDTranslator() = default; - IDTranslator(Identity tag) { + IDTranslatorBase() = default; + IDTranslatorBase(Identity tag) { auto ids = threads::UnitRange{0, tag.n_}; insert(ids, ids); } + /// + /// @brief Construct from the other variant, keeping every translation. + /// + /// @param other The translator to take the translations from. + /// + explicit IDTranslatorBase(IDTranslatorBase other) + : external_to_internal_{std::move(other.external_to_internal_)} { + for (const auto& [external, internal] : external_to_internal_) { + store_external(internal, external); + } + } + /// /// @brief Return the number of translations. /// - size_t size() const { - if constexpr (checkbounds_v) { - const size_t e2i = external_to_internal_.size(); - const size_t i2e = internal_to_external_.size(); + size_t size() const { return external_to_internal_.size(); } - if (e2i != i2e) { - throw ANNEXCEPTION("Size mismatch! E2I is {} while I2E is {}!", e2i, i2e); - } - } - return external_to_internal_.size(); + /// + /// @brief Return the number of bytes allocated for both translation tables. + /// + size_t get_memory_usage() const { + // The external->internal map is approximated by its entries, ignoring load-factor + // slack. An exact count depends on tsl::robin_map internals: + // using bucket_type = tsl::detail_robin_hash:: + // bucket_entry, false>; + // external_to_internal_.bucket_count() * sizeof(bucket_type) + return size() * (sizeof(external_id_type) + sizeof(internal_id_type)) + + internal_to_external_.capacity() * sizeof(external_id_type); + } + + /// + /// @brief Estimate ``get_memory_usage()`` for ``n`` translations over slots ``[0, n)``. + /// + static constexpr size_t estimate_memory_usage(size_t n) { + return n * (sizeof(external_id_type) + sizeof(internal_id_type)) + + n * sizeof(external_id_type); } /// @@ -124,6 +230,7 @@ class IDTranslator { if (!lib::all_unique(int_begin, int_end)) { throw ANNEXCEPTION("Internal IDs contain repeat elements!"); } + check_external_not_reserved(ext_begin, ext_end); check_external_free(ext_begin, ext_end); check_internal_free(int_begin, int_end); } @@ -138,10 +245,23 @@ class IDTranslator { } } + /// + /// @brief Insert one translation without checking for an existing mapping. + /// + /// @param external_id The external ID. Must not be ``invalid_external_id``. + /// @param internal_id The internal ID. + /// + /// Throws without modifying the translator if either ID does not fit its ID type or + /// ``external_id`` is reserved. Only safe if neither ID has a mapping yet. + /// template void insert_translation(Ext external_id, Int internal_id) { - external_to_internal_[external_id] = lib::narrow(internal_id); - internal_to_external_[internal_id] = lib::narrow(external_id); + auto e = lib::narrow(external_id); + auto i = lib::narrow(internal_id); + // Storing the reserved ID would leave `e` mapped while slot `i` reads as unmapped. + check_external_not_reserved(&e, &e + 1); + external_to_internal_[e] = i; + store_external(i, e); } /// @@ -183,6 +303,8 @@ class IDTranslator { throw ANNEXCEPTION("Internal IDs contain repeat elements!"); } + check_external_not_reserved(ext_begin, ext_end); + // Validation pass for (auto e = ext_begin; e != ext_end; ++e) { auto found = external_to_internal_.find(*e); @@ -197,7 +319,7 @@ class IDTranslator { for (; e != ext_end; ++e, ++i) { auto found = external_to_internal_.find(*e); if (found != external_to_internal_.end()) { - internal_to_external_.erase(found->second); + store_external(found->second, invalid_external_id); } insert_translation(*e, *i); } @@ -218,7 +340,7 @@ class IDTranslator { /// @param e The internal ID to check. /// bool has_internal(internal_id_type e) const { - return internal_to_external_.contains(e); + return load_external(e) != invalid_external_id; } /// @@ -236,20 +358,31 @@ class IDTranslator { /// @param i The internal ID to translate to an external ID. /// external_id_type get_external(internal_id_type i) const { - return internal_to_external_.at(i); + auto e = load_external(i); + if (e == invalid_external_id) { + throw std::out_of_range("IDTranslator: internal ID not found"); + } + return e; } - /// @brief Return the external ID, or a default if not found. + /// + /// @brief Return the external ID mapped to by the internal ID, or a default. + /// + /// @param i The internal ID to translate to an external ID. + /// @param default_val The value returned when ``i`` has no mapping. + /// external_id_type get_external_or(internal_id_type i, external_id_type default_val) const { - auto it = internal_to_external_.find(i); - if (it == internal_to_external_.end()) { - return default_val; - } - return it->second; + auto e = load_external(i); + return e == invalid_external_id ? default_val : e; } - /// @brief Return the internal ID, or a default if not found. + /// + /// @brief Return the internal ID mapped to by the external ID, or a default. + /// + /// @param e The external ID to translate to an internal ID. + /// @param default_val The value returned when ``e`` has no mapping. + /// internal_id_type get_internal_or(external_id_type e, internal_id_type default_val) const { auto it = external_to_internal_.find(e); @@ -280,27 +413,27 @@ class IDTranslator { assert(has_internal(from)); assert(!has_internal(to)); - auto itr = internal_to_external_.find(from); - auto external = itr->second; + auto external = load_external(from); // Updating the internal-to-external ID is easy. external_to_internal_[external] = to; - internal_to_external_.erase(itr); - internal_to_external_.insert({to, external}); + store_external(from, invalid_external_id); + store_external(to, external); } /// /// @brief Remap the external ID, keeping the same internal ID. /// /// @param from The existing external ID to rename. - /// @param to The external ID to rename it to. + /// @param to The external ID to rename it to. Must not be ``invalid_external_id``. /// @param check Check that ``from`` exists and ``to`` does not yet exist. Only safe /// to set to ``false`` if this holds true. /// - /// Note, if ``check == true`` and either condition fails, the underlying translation - /// tables will not be modified. + /// Note, if ``check == true`` and either condition fails, or if ``to`` is reserved, + /// the underlying translation tables will not be modified. /// void remap_external_id(external_id_type from, external_id_type to, bool check = true) { + check_external_not_reserved(&to, &to + 1); if (check) { if (!has_external(from)) { throw ANNEXCEPTION("Index does not contain external ID {}!", from); @@ -314,7 +447,7 @@ class IDTranslator { auto internal = itr->second; // Updating the external-to-internal ID is easy. - internal_to_external_[internal] = to; + store_external(internal, to); external_to_internal_.erase(itr); external_to_internal_.insert({to, internal}); } @@ -340,7 +473,7 @@ class IDTranslator { for (const auto i : internal_ids) { auto e = get_external(i); - internal_to_external_.erase(i); + store_external(i, invalid_external_id); external_to_internal_.erase(e); } } @@ -366,11 +499,28 @@ class IDTranslator { for (const auto e : external_ids) { auto i = get_internal(e); - internal_to_external_.erase(i); + store_external(i, invalid_external_id); external_to_internal_.erase(e); } } + /// + /// @brief Ensure that **none** of the external ids in the iterator is the reserved + /// ``invalid_external_id``. + /// + /// @param begin Start forward iterator to the external IDs to check. + /// @param end End forward iterator to the external IDs to check. + /// + template + void check_external_not_reserved(const Begin& begin, const End& end) const { + check( + begin, + end, + [](auto e) { return std::cmp_equal(e, invalid_external_id); }, + "Reserved external" + ); + } + /// /// @brief Ensure that **none** of the external ids in the iterator exist yet. /// @@ -379,7 +529,12 @@ class IDTranslator { /// template void check_external_free(const Begin& begin, const End& end) const { - check(begin, end, external_to_internal_, "Index already contains external"); + check( + begin, + end, + [this](auto e) { return has_external(e); }, + "Index already contains external" + ); } /// @@ -393,7 +548,7 @@ class IDTranslator { check( begin, end, - external_to_internal_, + [this](auto e) { return has_external(e); }, "Index does not contain external", std::logical_not() ); @@ -407,7 +562,12 @@ class IDTranslator { /// template void check_internal_free(const Begin& begin, const End& end) const { - check(begin, end, internal_to_external_, "Index already contains internal"); + check( + begin, + end, + [this](auto i) { return has_internal(i); }, + "Index already contains internal" + ); } /// @@ -421,7 +581,7 @@ class IDTranslator { check( begin, end, - internal_to_external_, + [this](auto i) { return has_internal(i); }, "Index does not contain internal", std::logical_not() ); @@ -477,11 +637,11 @@ class IDTranslator { } } - static IDTranslator load(const lib::ContextFreeLoadTable& table, std::istream& is) { - IDTranslator::validate(table); + static IDTranslatorBase load(const lib::ContextFreeLoadTable& table, std::istream& is) { + IDTranslatorBase::validate(table); auto num_points = lib::load_at(table, "num_points"); - auto translator = IDTranslator{}; + auto translator = IDTranslatorBase{}; for (size_t i = 0; i < num_points; ++i) { auto external_id = lib::read_binary(is); auto internal_id = lib::read_binary(is); @@ -490,34 +650,57 @@ class IDTranslator { return translator; } - static IDTranslator load(const lib::LoadTable& table) { - IDTranslator::validate(table); + static IDTranslatorBase load(const lib::LoadTable& table) { + IDTranslatorBase::validate(table); // Now that we've more-or-less validated the metadata, time to start loading // the points. auto resolved = table.resolve_at("filename"); auto is = lib::open_read(resolved); - return IDTranslator::load(table, is); + return IDTranslatorBase::load(table, is); } private: - template + // The converting constructor takes the other variant's external->internal map. + friend class IDTranslatorBase; + + using i_to_e_traits = VectorMapTraits; + + template void check( const Begin& begin, const End& end, - const Map& map, + const Contains& contains, const char* message, Modifier modify = lib::identity() ) const { for (auto i = begin; i != end; ++i) { - if (modify(map.contains(*i))) { + if (modify(contains(*i))) { throw ANNEXCEPTION("{} ID {}!", message, *i); } } } tsl::robin_map external_to_internal_{}; - tsl::robin_map internal_to_external_{}; + // `typename` is required by compilers without P0634 (clang before 16). + typename i_to_e_traits::vector_type internal_to_external_{}; + + // Returns `invalid_external_id` for a slot that is unmapped or beyond the table. + external_id_type load_external(internal_id_type i) const { + return i_to_e_traits::load(internal_to_external_, size_t{i}, invalid_external_id); + } + + // Writers only; grows the table with unmapped slots first when `i` is beyond it. + void store_external(internal_id_type i, external_id_type e) { + i_to_e_traits::store(internal_to_external_, size_t{i}, e, invalid_external_id); + } }; +} // namespace detail + +/// The translator for single-threaded use. See ``detail::IDTranslatorBase``. +using IDTranslator = detail::IDTranslatorBase; +/// The translator whose internal-to-external lookups may run without a lock against one +/// writer. See ``detail::IDTranslatorBase``. +using ConcurrentIDTranslator = detail::IDTranslatorBase; } // namespace svs diff --git a/include/svs/index/vamana/dynamic_index.h b/include/svs/index/vamana/dynamic_index.h index 8a9a64dd1..61570e099 100644 --- a/include/svs/index/vamana/dynamic_index.h +++ b/include/svs/index/vamana/dynamic_index.h @@ -506,8 +506,8 @@ class MutableVamanaIndex { /// /// Reports the allocated memory for graph, data, and metadata components. Uses /// capacity-based accounting for datasets that expose ``capacity()``, so that block - /// over-allocation is reflected. Metadata includes status array, entry points, and an - /// estimated size of the ID translation maps (external/internal ID translation maps). + /// over-allocation is reflected. Metadata includes status array, entry points, and the + /// allocated size of the ID translation tables. MemoryBreakdown get_memory_breakdown() const { using namespace svs::data; MemoryBreakdown usage{}; @@ -517,14 +517,7 @@ class MutableVamanaIndex { size_t metadata_bytes = status_.capacity() * sizeof(SlotMetadata); metadata_bytes += entry_point_.capacity() * sizeof(typename entry_point_type::value_type); - // The IDTranslator holds two tsl::robin_map instances (external->internal and - // internal->external), neither of which exposes its allocated byte count. We - // approximate the storage as the id pair held in each of the two directions. This - // ignores the maps' load-factor slack and control bytes, so it is an estimate of - // the hash-map overhead that is accurate to within a few percent. - metadata_bytes += 2 * translator_.size() * - (sizeof(IDTranslator::external_id_type) + - sizeof(IDTranslator::internal_id_type)); + metadata_bytes += translator_.get_memory_usage(); usage.metadata_bytes = metadata_bytes; return usage; } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 88a9ae412..c2655e7fa 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -286,6 +286,7 @@ if (SVS_EXPERIMENTAL_ENABLE_CONCURRENT_TSAN) set(CONCURRENT_TSAN_SOURCES ${TEST_DIR}/svs/concurrent/graph.cpp ${TEST_DIR}/svs/concurrent/concurrency.cpp + ${TEST_DIR}/svs/concurrent/translation.cpp ) add_executable(concurrent_tsan ${CONCURRENT_TSAN_SOURCES}) diff --git a/tests/svs/concurrent/dynamic_index.cpp b/tests/svs/concurrent/dynamic_index.cpp index 214dec205..357397d7a 100644 --- a/tests/svs/concurrent/dynamic_index.cpp +++ b/tests/svs/concurrent/dynamic_index.cpp @@ -596,11 +596,16 @@ CATCH_TEST_CASE( const size_t segmented_capacity = svs::lib::SegmentedVector(data_size).capacity(); const size_t expected_status_bytes = segmented_capacity * sizeof(cc::SlotMetadata); - const size_t expected_metadata_bytes = expected_status_bytes + - sizeof(typename Index::internal_id_type) + - 2 * indices.size() * - (sizeof(typename Index::external_id_type) + - sizeof(typename Index::internal_id_type)); + // The translator holds one id pair per translation plus an internal-to-external table, + // another `SegmentedVector` with one external id per slot. + using ExternalId = typename Index::external_id_type; + using InternalId = typename Index::internal_id_type; + const size_t expected_translator_bytes = + indices.size() * (sizeof(ExternalId) + sizeof(InternalId)) + + svs::lib::SegmentedVector(indices.size()).capacity() * + sizeof(ExternalId); + const size_t expected_metadata_bytes = + expected_status_bytes + sizeof(InternalId) + expected_translator_bytes; // The reverse-edge index holds one in-neighbor list plus one lock per slot, so its // directory overhead is deterministic. The payload is not: the index only records diff --git a/tests/svs/concurrent/translation.cpp b/tests/svs/concurrent/translation.cpp index 9bcd596fc..e74ccc32b 100644 --- a/tests/svs/concurrent/translation.cpp +++ b/tests/svs/concurrent/translation.cpp @@ -14,310 +14,352 @@ * limitations under the License. */ +// Multi-threaded tests of ``svs::ConcurrentIDTranslator``: reads issued while one writer +// mutates the translator. Its single-threaded behaviour is covered, together with the +// plain variant, in ``tests/svs/core/translation.cpp``. +// +// A reader can only check what is true at every instant, so each test fixes the set of +// external IDs an internal ID may ever map to and requires every read to land in that set. +// The data-race half of the contract is only visible to ThreadSanitizer; this file is part +// of the ``concurrent_tsan`` target for that reason. +// +// Assertions inside the reader loops accumulate into counters and are checked once at the +// end: Catch2's assertion bookkeeping is neither free nor safe to call from several +// threads at once. + // header under test. #include "svs/core/translation.h" -// misc utilities -#include "svs/lib/narrow.h" - -// Test utils -#include "tests/utils/generators.h" - // Catch2 #include "catch2/catch_test_macros.hpp" // stl -#include - -// These tests exercise the shared translator used by the concurrent index, -// including its stale-ID replacement operation. -using IDTranslator = svs::IDTranslator; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include namespace { -template -void check_contents( - const Begin& begin, const End& end, const External& external, const Internal& internal -) { - int64_t dist = std::distance(begin, end); - CATCH_REQUIRE(dist == svs::lib::narrow(external.size())); - CATCH_REQUIRE(dist == svs::lib::narrow(internal.size())); - - size_t count = 0; - for (auto i = begin; i != end; ++i, ++count) { - CATCH_REQUIRE(i->first == external[count]); - CATCH_REQUIRE(i->second == internal[count]); - } -} -template -void check_contents( - const IDTranslator& translator, const External& external, const Internal& internal -) { - check_contents(translator.begin(), translator.end(), external, internal); -} - -template -void check_translation( - const IDTranslator& translator, const External& external, const Internal& internal -) { - CATCH_REQUIRE(translator.size() == external.size()); - CATCH_REQUIRE(translator.size() == internal.size()); - - for (size_t i = 0, imax = translator.size(); i < imax; ++i) { - CATCH_REQUIRE(translator.get_internal(external[i]) == internal[i]); - CATCH_REQUIRE(translator.get_external(internal[i]) == external[i]); +using Translator = svs::ConcurrentIDTranslator; +using external_id_type = Translator::external_id_type; +using internal_id_type = Translator::internal_id_type; + +constexpr size_t kReaders = 4; + +// The two external IDs the tests ever give the translation that starts in slot `owner`. +constexpr external_id_type primary(size_t owner) { return 2 * owner; } +constexpr external_id_type renamed(size_t owner) { return 2 * owner + 1; } + +// Defaults handed to the `_or` lookups. Neither is an ID the tests store, and +// `kNoExternal` differs from the translator's own reserved ID, so a lookup that leaked the +// reserved ID instead of the default would be caught. +constexpr external_id_type kNoExternal = Translator::invalid_external_id - 1; +constexpr internal_id_type kNoInternal = std::numeric_limits::max(); + +// Run `writer` once on its own thread while `kReaders` threads call `reader` in a loop. +// Every reader makes at least one pass, including one after the writer has finished. +template +void run_against_readers(Writer&& writer, Reader&& reader) { + std::atomic start{false}; + std::atomic writer_done{false}; + + std::vector readers; + for (size_t r = 0; r < kReaders; ++r) { + readers.emplace_back([&]() { + while (!start.load(std::memory_order_acquire)) {} + bool last_pass = false; + while (!last_pass) { + last_pass = writer_done.load(std::memory_order_acquire); + reader(); + } + }); + } + std::thread writer_thread([&]() { + while (!start.load(std::memory_order_acquire)) {} + writer(); + writer_done.store(true, std::memory_order_release); + }); + + start.store(true, std::memory_order_release); + writer_thread.join(); + for (auto& t : readers) { + t.join(); } -} - -void check( - const IDTranslator& translator, - std::vector& external_ids, - std::vector& internal_ids -) { - check_translation(translator, external_ids, internal_ids); - check_contents(translator, external_ids, internal_ids); } } // namespace -CATCH_TEST_CASE("Concurrent Translation Table", "[concurrent][translation]") { - CATCH_SECTION("Identity Constructor") { - auto translator = IDTranslator(IDTranslator::Identity(10)); - CATCH_REQUIRE(translator.size() == 10); - for (size_t i = 0; i < 10; ++i) { - CATCH_REQUIRE(translator.has_external(i)); - CATCH_REQUIRE(translator.has_internal(i)); - CATCH_REQUIRE(translator.get_external(i) == i); - CATCH_REQUIRE(translator.get_internal(i) == i); +// The writer appends translations in batches and publishes a counter only after a batch is +// inserted. Readers hold no lock: a published internal ID must read back exactly, and an +// unpublished one is either still unmapped or already holds its final value. This is the +// case that relocating storage would break, since appending grows the table under the +// readers. +CATCH_TEST_CASE( + "ConcurrentIDTranslator lock-free reads during growth", "[concurrent][translation]" +) { + constexpr size_t kFinal = 100'000; + constexpr size_t kBatch = 137; + + auto translator = Translator(); + std::atomic published{0}; + std::atomic failures{0}; + + auto writer = [&]() { + auto external_ids = std::vector(); + auto internal_ids = std::vector(); + for (size_t cur = 0; cur < kFinal;) { + const size_t next = std::min(cur + kBatch, kFinal); + external_ids.clear(); + internal_ids.clear(); + for (size_t i = cur; i < next; ++i) { + external_ids.push_back(primary(i)); + internal_ids.push_back(static_cast(i)); + } + translator.insert(external_ids, internal_ids); + published.store(next, std::memory_order_release); + cur = next; } - } - - CATCH_SECTION("Basic Tests") { - auto translator = IDTranslator(); - CATCH_REQUIRE(translator.size() == 0); - - auto external_ids = std::vector{0, 2, 4, 6, 8}; - auto internal_ids = std::vector{0, 10, 20, 30, 40}; - - CATCH_REQUIRE(external_ids.size() == internal_ids.size()); - translator.insert(external_ids, internal_ids); - - check(translator, external_ids, internal_ids); - - /// - /// Adding more IDs - /// - CATCH_SECTION("Adding more entries") { - auto extra_external_ids = std::vector{10, 12, 14}; - auto extra_internal_ids = std::vector{50, 60, 70}; - translator.insert(extra_external_ids, extra_internal_ids); - external_ids.insert( - external_ids.end(), extra_external_ids.begin(), extra_external_ids.end() - ); - internal_ids.insert( - internal_ids.end(), extra_internal_ids.begin(), extra_internal_ids.end() - ); - - check(translator, external_ids, internal_ids); + }; + + auto reader = [&]() { + const size_t n = published.load(std::memory_order_acquire); + size_t bad = 0; + const size_t step = n / 256 + 1; + for (size_t i = 0; i < n; i += step) { + const auto internal = static_cast(i); + bad += !translator.has_internal(internal); + bad += translator.get_external_or(internal, kNoExternal) != primary(i); } - - /// - /// Error Handling - /// - CATCH_SECTION("Mismatched number of entries") { - // Mismatched number of internal and external IDs. - auto external_mismatch_ids = std::vector{10, 12, 14}; - auto internal_mismatch_ids = std::vector{50, 60}; - CATCH_REQUIRE_THROWS_AS( - translator.insert(external_mismatch_ids, internal_mismatch_ids), - svs::ANNException - ); - - // State of the translator should be unchanged. - check(translator, external_ids, internal_ids); + // The batch being inserted right now, and the slots beyond the table. + for (size_t i = n; i < n + 2 * kBatch; ++i) { + const auto e = + translator.get_external_or(static_cast(i), kNoExternal); + bad += e != kNoExternal && e != primary(i); } - - CATCH_SECTION("Repeat External IDs") { - auto external_mismatch_ids = std::vector{10, 12, 8}; - auto internal_mismatch_ids = std::vector{50, 60, 70}; - - CATCH_REQUIRE_THROWS_AS( - translator.insert(external_mismatch_ids, internal_mismatch_ids), - svs::ANNException - ); - - // State of the translator should be unchanged. - check(translator, external_ids, internal_ids); - } - - CATCH_SECTION("Non-unique External IDs") { - auto external_mismatch_ids = std::vector{10, 12, 10}; - auto internal_mismatch_ids = std::vector{50, 60, 70}; - - CATCH_REQUIRE_THROWS_AS( - translator.insert(external_mismatch_ids, internal_mismatch_ids), - svs::ANNException - ); - - // State of the translator should be unchanged. - check(translator, external_ids, internal_ids); - } - - CATCH_SECTION("replace_stale_and_insert is transactional on a live duplicate") { - // Batch: a fresh external id followed by a live (non-stale) duplicate. - // The whole batch must be validated before any mutation, so the throw - // leaves the translator byte-for-byte unchanged — in particular the - // fresh id `100` must NOT have been committed. - auto add_external = std::vector{100, 8}; // 8 already exists - auto add_internal = std::vector{50, 60}; - auto never_stale = [](uint32_t) { return false; }; - - CATCH_REQUIRE_THROWS_AS( - translator.replace_stale_and_insert( - add_external, add_internal, never_stale - ), - svs::ANNException - ); - - CATCH_REQUIRE_FALSE(translator.has_external(100)); // not committed - CATCH_REQUIRE_FALSE(translator.has_internal(50)); - check(translator, external_ids, internal_ids); // unchanged + failures.fetch_add(bad, std::memory_order_relaxed); + }; + + run_against_readers(writer, reader); + + CATCH_REQUIRE(failures.load() == 0); + CATCH_REQUIRE(translator.size() == kFinal); + for (size_t i = 0; i < kFinal; ++i) { + const auto internal = static_cast(i); + if (translator.get_external(internal) != primary(i) || + translator.get_internal(primary(i)) != internal) { + CATCH_FAIL("wrong translation for internal ID " << i); } + } + CATCH_REQUIRE_FALSE(translator.has_internal(static_cast(kFinal))); +} - CATCH_SECTION("replace_stale_and_insert replaces a stale mapping") { - // Mark internal 20 (external 4) stale; re-add external 4 at a new - // internal id plus a genuinely fresh id. Both should commit. - auto add_external = std::vector{4, 100}; - auto add_internal = std::vector{50, 60}; - auto stale_if_20 = [](uint32_t i) { return i == 20; }; - - CATCH_REQUIRE_NOTHROW( - translator.replace_stale_and_insert(add_external, add_internal, stale_if_20) - ); - - CATCH_REQUIRE(translator.get_internal(4) == 50); - CATCH_REQUIRE(translator.get_internal(100) == 60); - CATCH_REQUIRE(translator.get_external(50) == 4); - CATCH_REQUIRE(translator.get_external(60) == 100); - // Old internal 20 no longer maps back to any external. - CATCH_REQUIRE_FALSE(translator.has_internal(20)); +// The writer renames, deletes, re-inserts and moves translations over a fixed set of +// slots. Readers hold no lock. Slot `s` only ever holds the translation that started in +// slot `s % kSlots`, under one of its two external IDs, so every read must return one of +// those two IDs or report the slot unmapped. +CATCH_TEST_CASE( + "ConcurrentIDTranslator lock-free reads during mutation", "[concurrent][translation]" +) { + constexpr size_t kSlots = 512; + constexpr size_t kRounds = 200; + + auto translator = Translator(); + auto all_external = std::vector(); + auto all_internal = std::vector(); + auto even_external = std::vector(); + auto even_internal = std::vector(); + for (size_t i = 0; i < kSlots; ++i) { + all_external.push_back(primary(i)); + all_internal.push_back(static_cast(i)); + if (i % 2 == 0) { + even_external.push_back(primary(i)); + even_internal.push_back(static_cast(i)); } - - CATCH_SECTION("Repeat Internal IDs") { - auto external_mismatch_ids = std::vector{10, 12, 14}; - auto internal_mismatch_ids = std::vector{50, 10, 70}; - - CATCH_REQUIRE_THROWS_AS( - translator.insert(external_mismatch_ids, internal_mismatch_ids), - svs::ANNException - ); - - // State of the translator should be unchanged. - check(translator, external_ids, internal_ids); + } + translator.insert(all_external, all_internal); + + std::atomic failures{0}; + + auto writer = [&]() { + for (size_t round = 0; round < kRounds; ++round) { + for (size_t i = 0; i < kSlots; ++i) { + translator.remap_external_id(primary(i), renamed(i)); + } + // Even slots: delete under the new name, come back under the old one. + translator.delete_internal(even_internal); + translator.insert(even_external, even_internal); + // Odd slots: move beyond the end of the original range and back, then take + // the old name again. + for (size_t i = 1; i < kSlots; i += 2) { + const auto from = static_cast(i); + const auto to = static_cast(i + kSlots); + translator.remap_internal_id(from, to); + translator.remap_internal_id(to, from); + translator.remap_external_id(renamed(i), primary(i)); + } } - - CATCH_SECTION("Repeat Internal IDs") { - auto external_mismatch_ids = std::vector{10, 12, 14}; - auto internal_mismatch_ids = std::vector{50, 60, 60}; - - CATCH_REQUIRE_THROWS_AS( - translator.insert(external_mismatch_ids, internal_mismatch_ids), - svs::ANNException - ); - - // State of the translator should be unchanged. - check(translator, external_ids, internal_ids); + }; + + auto reader = [&]() { + size_t bad = 0; + for (size_t slot = 0; slot < 2 * kSlots; ++slot) { + const size_t owner = slot % kSlots; + const auto internal = static_cast(slot); + auto legal = [&](external_id_type e) { + return e == primary(owner) || e == renamed(owner); + }; + + const auto e = translator.get_external_or(internal, kNoExternal); + bad += e != kNoExternal && !legal(e); + + // The throwing lookup, on a sample: an exception per slot would dominate the + // loop. + if (slot % 16 == 0) { + try { + bad += !legal(translator.get_external(internal)); + } catch (const std::out_of_range&) { + // Unmapped at the instant of the read. + } + } + // No assertion possible on the result, but the call must be race-free. + static_cast(translator.has_internal(internal)); } - - /// - /// Deletion - /// - - CATCH_SECTION("Delete External") { - auto external_id_delete = std::vector{2, 6}; - translator.delete_external(external_id_delete); - - external_ids = {0, 4, 8}; - internal_ids = {0, 20, 40}; - check(translator, external_ids, internal_ids); + failures.fetch_add(bad, std::memory_order_relaxed); + }; + + run_against_readers(writer, reader); + + CATCH_REQUIRE(failures.load() == 0); + // Every round ends where it started. + CATCH_REQUIRE(translator.size() == kSlots); + for (size_t i = 0; i < kSlots; ++i) { + const auto internal = static_cast(i); + if (translator.get_external(internal) != primary(i) || + translator.get_internal(primary(i)) != internal || + translator.has_internal(static_cast(i + kSlots))) { + CATCH_FAIL("wrong translation for internal ID " << i); } + } +} - CATCH_SECTION("Delete External Error") { - // The external id `10` doesn't exist. - // We should get an error without modifying the underlying container. - auto external_id_delete = std::vector{2, 10}; - CATCH_REQUIRE_THROWS_AS( - translator.delete_external(external_id_delete), svs::ANNException - ); - check(translator, external_ids, internal_ids); +// The external-to-internal direction is a hash map and needs a lock. This mirrors how the +// concurrent index uses the translator: writers exclusive, readers shared. Under the +// shared lock a reader sees a state between two writer steps, in which the two directions +// agree with each other. +CATCH_TEST_CASE( + "ConcurrentIDTranslator both directions under a shared lock", + "[concurrent][translation]" +) { + constexpr size_t kSlots = 256; + constexpr size_t kRounds = 300; + + auto translator = Translator(); + auto all_external = std::vector(); + auto all_internal = std::vector(); + auto even_external = std::vector(); + auto even_internal = std::vector(); + for (size_t i = 0; i < kSlots; ++i) { + all_external.push_back(primary(i)); + all_internal.push_back(static_cast(i)); + if (i % 2 == 0) { + even_external.push_back(primary(i)); + even_internal.push_back(static_cast(i)); } - - CATCH_SECTION("Delete Internal") { - auto internal_id_delete = std::vector{0, 20, 40}; - translator.delete_internal(internal_id_delete); - - external_ids = {2, 6}; - internal_ids = {10, 30}; - check(translator, external_ids, internal_ids); + } + translator.insert(all_external, all_internal); + + std::shared_mutex mutex; + std::atomic failures{0}; + // Bumped after every writer step; see the end of `reader`. + std::atomic writer_steps{0}; + std::atomic writer_finished{false}; + + // Run one writer step under the exclusive lock. + auto exclusive_step = [&](auto&& step) { + { + std::unique_lock lock{mutex}; + step(); } - - CATCH_SECTION("Delete Internal Error") { - auto internal_id_delete = std::vector{0, 20, 2}; - CATCH_REQUIRE_THROWS_AS( - translator.delete_internal(internal_id_delete), svs::ANNException - ); - check(translator, external_ids, internal_ids); + writer_steps.fetch_add(1, std::memory_order_release); + }; + + auto writer = [&]() { + for (size_t round = 0; round < kRounds; ++round) { + exclusive_step([&]() { translator.delete_external(even_external); }); + // Odd slots move into the upper half of the slot range. + exclusive_step([&]() { + for (size_t i = 1; i < kSlots; i += 2) { + translator.remap_internal_id( + static_cast(i), + static_cast(i + kSlots) + ); + } + }); + exclusive_step([&]() { translator.insert(even_external, even_internal); }); + exclusive_step([&]() { + for (size_t i = 1; i < kSlots; i += 2) { + translator.remap_internal_id( + static_cast(i + kSlots), + static_cast(i) + ); + } + }); } - - /// - /// Renaming (relabeling) - /// - - CATCH_SECTION("Rename External") { - translator.remap_external_id(2, 100); - - CATCH_REQUIRE(!translator.has_external(2)); - CATCH_REQUIRE(translator.has_external(100)); - CATCH_REQUIRE(translator.get_internal(100) == 10); - CATCH_REQUIRE(translator.get_external(10) == 100); - CATCH_REQUIRE(translator.size() == external_ids.size()); - - // Everything else is unaffected. - CATCH_REQUIRE(translator.get_internal(0) == 0); - CATCH_REQUIRE(translator.get_internal(4) == 20); - CATCH_REQUIRE(translator.get_internal(6) == 30); - CATCH_REQUIRE(translator.get_internal(8) == 40); + writer_finished.store(true, std::memory_order_release); + }; + + auto reader = [&]() { + const size_t step_seen = writer_steps.load(std::memory_order_acquire); + size_t bad = 0; + std::shared_lock lock{mutex}; + size_t mapped = 0; + for (size_t owner = 0; owner < kSlots; ++owner) { + const auto e = primary(owner); + const auto internal = translator.get_internal_or(e, kNoInternal); + bad += translator.has_external(e) != (internal != kNoInternal); + if (internal == kNoInternal) { + continue; + } + ++mapped; + bad += internal % kSlots != owner; + bad += translator.get_external_or(internal, kNoExternal) != e; } - - CATCH_SECTION("Rename External Error - Source Does Not Exist") { - // External id `10` doesn't exist yet. - CATCH_REQUIRE_THROWS_AS( - translator.remap_external_id(10, 100), svs::ANNException - ); - // State of the translator should be unchanged. - check(translator, external_ids, internal_ids); + bad += translator.size() != mapped; + // Slots without an owner mapped to them read as unmapped. + size_t occupied = 0; + for (size_t slot = 0; slot < 2 * kSlots; ++slot) { + occupied += translator.has_internal(static_cast(slot)); } - - CATCH_SECTION("Rename External Error - Destination Already Exists") { - // External id `4` already exists. - CATCH_REQUIRE_THROWS_AS(translator.remap_external_id(2, 4), svs::ANNException); - // State of the translator should be unchanged. - check(translator, external_ids, internal_ids); + bad += occupied != mapped; + failures.fetch_add(bad, std::memory_order_relaxed); + + // One pass per writer step, waiting for the next step without the lock. Readers + // that re-lock back to back never let the lock go free, and a reader-preferring + // `std::shared_mutex` (glibc) then starves the writer forever. + lock.unlock(); + while (writer_steps.load(std::memory_order_acquire) == step_seen && + !writer_finished.load(std::memory_order_acquire)) { + std::this_thread::yield(); } - - /// - /// Saving and loading - /// - - CATCH_SECTION("Saving and Reloading") { - svs_test::prepare_temp_directory(); - auto tempdir = svs_test::temp_directory(); - - svs::lib::save_to_disk(translator, tempdir); - auto reloaded = svs::lib::load_from_disk(tempdir); - - check(translator, external_ids, internal_ids); - check(reloaded, external_ids, internal_ids); + }; + + run_against_readers(writer, reader); + + CATCH_REQUIRE(failures.load() == 0); + CATCH_REQUIRE(writer_steps.load() == 4 * kRounds); + CATCH_REQUIRE(translator.size() == kSlots); + for (size_t i = 0; i < kSlots; ++i) { + const auto internal = static_cast(i); + if (translator.get_external(internal) != primary(i) || + translator.get_internal(primary(i)) != internal) { + CATCH_FAIL("wrong translation for internal ID " << i); } } } diff --git a/tests/svs/core/translation.cpp b/tests/svs/core/translation.cpp index feefdec02..0e01829eb 100644 --- a/tests/svs/core/translation.cpp +++ b/tests/svs/core/translation.cpp @@ -24,10 +24,16 @@ #include "tests/utils/generators.h" // Catch2 +#include "catch2/catch_template_test_macros.hpp" #include "catch2/catch_test_macros.hpp" // stl +#include #include +#include +#include +#include +#include namespace { template @@ -45,28 +51,31 @@ void check_contents( } } -template +template void check_contents( - const svs::IDTranslator& translator, const External& external, const Internal& internal + const Translator& translator, const External& external, const Internal& internal ) { check_contents(translator.begin(), translator.end(), external, internal); } -template +template void check_translation( - const svs::IDTranslator& translator, const External& external, const Internal& internal + const Translator& translator, const External& external, const Internal& internal ) { CATCH_REQUIRE(translator.size() == external.size()); CATCH_REQUIRE(translator.size() == internal.size()); for (size_t i = 0, imax = translator.size(); i < imax; ++i) { + CATCH_REQUIRE(translator.has_external(external[i])); + CATCH_REQUIRE(translator.has_internal(internal[i])); CATCH_REQUIRE(translator.get_internal(external[i]) == internal[i]); CATCH_REQUIRE(translator.get_external(internal[i]) == external[i]); } } +template void check( - const svs::IDTranslator& translator, + const Translator& translator, std::vector& external_ids, std::vector& internal_ids ) { @@ -74,11 +83,37 @@ void check( check_contents(translator, external_ids, internal_ids); } +// Both directions of `lhs` are present in `rhs`, and nothing else is. +template void check_same(const Lhs& lhs, const Rhs& rhs) { + CATCH_REQUIRE(lhs.size() == rhs.size()); + for (auto pair : lhs) { + CATCH_REQUIRE(rhs.get_internal(pair.first) == pair.second); + CATCH_REQUIRE(rhs.get_external(pair.second) == pair.first); + } +} + +template +using other_variant = std::conditional_t< + std::is_same_v, + svs::ConcurrentIDTranslator, + svs::IDTranslator>; + } // namespace -CATCH_TEST_CASE("Translation Table", "[core][translation]") { +// Single-threaded behaviour is the same for both variants; the lock-free reads of the +// concurrent one are covered in `tests/svs/concurrent/translation.cpp`. +CATCH_TEMPLATE_TEST_CASE( + "Translation Table", + "[core][translation]", + svs::IDTranslator, + svs::ConcurrentIDTranslator +) { + using Translator = TestType; + using external_id_type = typename Translator::external_id_type; + using internal_id_type = typename Translator::internal_id_type; + CATCH_SECTION("Identity Constructor") { - auto translator = svs::IDTranslator(svs::IDTranslator::Identity(10)); + auto translator = Translator(typename Translator::Identity(10)); CATCH_REQUIRE(translator.size() == 10); for (size_t i = 0; i < 10; ++i) { CATCH_REQUIRE(translator.has_external(i)); @@ -89,7 +124,7 @@ CATCH_TEST_CASE("Translation Table", "[core][translation]") { } CATCH_SECTION("Basic Tests") { - auto translator = svs::IDTranslator(); + auto translator = Translator(); CATCH_REQUIRE(translator.size() == 0); auto external_ids = std::vector{0, 2, 4, 6, 8}; @@ -261,6 +296,206 @@ CATCH_TEST_CASE("Translation Table", "[core][translation]") { check(translator, external_ids, internal_ids); } + /// + /// Replacing stale mappings + /// + + CATCH_SECTION("replace_stale_and_insert is transactional on a live duplicate") { + // Batch: a fresh external id followed by a live (non-stale) duplicate. + // The whole batch must be validated before any mutation, so the throw + // leaves the translator unchanged -- in particular the fresh id `100` must + // NOT have been committed. + auto add_external = std::vector{100, 8}; // 8 already exists + auto add_internal = std::vector{50, 60}; + auto never_stale = [](uint32_t) { return false; }; + + CATCH_REQUIRE_THROWS_AS( + translator.replace_stale_and_insert( + add_external, add_internal, never_stale + ), + svs::ANNException + ); + + CATCH_REQUIRE_FALSE(translator.has_external(100)); // not committed + CATCH_REQUIRE_FALSE(translator.has_internal(50)); + check(translator, external_ids, internal_ids); // unchanged + } + + CATCH_SECTION("replace_stale_and_insert replaces a stale mapping") { + // Mark internal 20 (external 4) stale; re-add external 4 at a new + // internal id plus a genuinely fresh id. Both should commit. + auto add_external = std::vector{4, 100}; + auto add_internal = std::vector{50, 60}; + auto stale_if_20 = [](uint32_t i) { return i == 20; }; + + CATCH_REQUIRE_NOTHROW( + translator.replace_stale_and_insert(add_external, add_internal, stale_if_20) + ); + + CATCH_REQUIRE(translator.size() == external_ids.size() + 1); + CATCH_REQUIRE(translator.get_internal(4) == 50); + CATCH_REQUIRE(translator.get_internal(100) == 60); + CATCH_REQUIRE(translator.get_external(50) == 4); + CATCH_REQUIRE(translator.get_external(60) == 100); + // Old internal 20 no longer maps back to any external. + CATCH_REQUIRE_FALSE(translator.has_internal(20)); + } + + /// + /// Unmapped IDs + /// + + CATCH_SECTION("Unmapped Internal IDs") { + // `5` is a hole inside the internal-to-external table, `1000` lies beyond its + // end, and `10` becomes a hole once its translation is deleted. + translator.delete_internal(std::vector{10}); + for (uint32_t unmapped : {5u, 1000u, 10u}) { + CATCH_REQUIRE_FALSE(translator.has_internal(unmapped)); + CATCH_REQUIRE_THROWS_AS( + translator.get_external(unmapped), std::out_of_range + ); + // Regression: a hole inside the table used to yield + // `invalid_external_id` instead of the caller's default. + CATCH_REQUIRE(translator.get_external_or(unmapped, 77) == 77); + } + CATCH_REQUIRE(translator.get_external_or(20, 77) == 4); + } + + CATCH_SECTION("Unmapped External IDs") { + translator.delete_external(std::vector{2}); + for (uint64_t unmapped : {3u, 2u}) { + CATCH_REQUIRE_FALSE(translator.has_external(unmapped)); + CATCH_REQUIRE_THROWS_AS( + translator.get_internal(unmapped), std::out_of_range + ); + CATCH_REQUIRE(translator.get_internal_or(unmapped, 77) == 77); + } + CATCH_REQUIRE(translator.get_internal_or(4, 77) == 20); + } + + CATCH_SECTION("Reserved External ID") { + // The reserved ID marks an unmapped slot, so storing it would leave the two + // directions inconsistent. Every way in rejects it without side effects. + const external_id_type reserved = Translator::invalid_external_id; + auto add_external = std::vector{10, reserved}; + auto add_internal = std::vector{50, 60}; + auto never_stale = [](uint32_t) { return false; }; + + CATCH_REQUIRE_THROWS_AS( + translator.insert(add_external, add_internal), svs::ANNException + ); + CATCH_REQUIRE_THROWS_AS( + translator.replace_stale_and_insert( + add_external, add_internal, never_stale + ), + svs::ANNException + ); + CATCH_REQUIRE_THROWS_AS( + translator.insert_translation(reserved, 60), svs::ANNException + ); + CATCH_REQUIRE_THROWS_AS( + translator.remap_external_id(2, reserved), svs::ANNException + ); + + CATCH_REQUIRE_FALSE(translator.has_external(reserved)); + CATCH_REQUIRE_FALSE(translator.has_external(10)); + CATCH_REQUIRE_FALSE(translator.has_internal(50)); + CATCH_REQUIRE_FALSE(translator.has_internal(60)); + check(translator, external_ids, internal_ids); + } + + /// + /// Moving and reusing internal IDs + /// + + CATCH_SECTION("Remap Internal") { + // Into a hole inside the table, then beyond its end. + translator.remap_internal_id(10, 5); + translator.remap_internal_id(40, 1000); + + CATCH_REQUIRE_FALSE(translator.has_internal(10)); + CATCH_REQUIRE_FALSE(translator.has_internal(40)); + internal_ids = {0, 5, 20, 30, 1000}; + check(translator, external_ids, internal_ids); + } + + CATCH_SECTION("Reusing a deleted internal ID") { + translator.delete_external(std::vector{4}); + CATCH_REQUIRE_FALSE(translator.has_internal(20)); + translator.insert(std::vector{100}, std::vector{20}); + + CATCH_REQUIRE(translator.size() == external_ids.size()); + CATCH_REQUIRE_FALSE(translator.has_external(4)); + CATCH_REQUIRE(translator.get_internal(100) == 20); + CATCH_REQUIRE(translator.get_external(20) == 100); + } + + /// + /// Memory accounting + /// + + CATCH_SECTION("Memory Usage") { + const size_t pair_bytes = sizeof(external_id_type) + sizeof(internal_id_type); + CATCH_REQUIRE( + Translator::estimate_memory_usage(10) == + 10 * pair_bytes + 10 * sizeof(external_id_type) + ); + + // The internal-to-external table spans slots [0, 40] however few of them are + // mapped, and deleting translations does not release it. + const size_t num_slots = 41; + auto min_usage = [&](size_t num_translations) { + return num_translations * pair_bytes + num_slots * sizeof(external_id_type); + }; + CATCH_REQUIRE(translator.get_memory_usage() >= min_usage(5)); + if constexpr (std::is_same_v) { + // The segmented table rounds its capacity up to its bucket layout. + const size_t table_slots = + svs::lib::SegmentedVector(num_slots).capacity(); + CATCH_REQUIRE( + translator.get_memory_usage() == + 5 * pair_bytes + table_slots * sizeof(external_id_type) + ); + } + + translator.delete_internal(std::vector{0, 20, 40}); + CATCH_REQUIRE(translator.get_memory_usage() >= min_usage(2)); + + // The estimate is a lower bound for a dense translator. + auto dense = Translator(typename Translator::Identity(100)); + CATCH_REQUIRE( + dense.get_memory_usage() >= Translator::estimate_memory_usage(100) + ); + } + + /// + /// Converting between the variants + /// + + CATCH_SECTION("Converting between variants") { + using Other = other_variant; + // Leave a hole so the conversion has to reproduce an unmapped slot. + translator.delete_external(std::vector{4}); + external_ids = {0, 2, 6, 8}; + internal_ids = {0, 10, 30, 40}; + + auto converted = Other(translator); + check(converted, external_ids, internal_ids); + CATCH_REQUIRE_FALSE(converted.has_internal(20)); + CATCH_REQUIRE(converted.get_external_or(20, 77) == 77); + + // The converted translator owns its tables. + converted.insert(std::vector{4}, std::vector{20}); + CATCH_REQUIRE_FALSE(translator.has_external(4)); + CATCH_REQUIRE_FALSE(translator.has_internal(20)); + check(translator, external_ids, internal_ids); + + auto round_trip = Translator(std::move(converted)); + external_ids.push_back(4); + internal_ids.push_back(20); + check_translation(round_trip, external_ids, internal_ids); + } + /// /// Saving and loading /// @@ -270,10 +505,36 @@ CATCH_TEST_CASE("Translation Table", "[core][translation]") { auto tempdir = svs_test::temp_directory(); svs::lib::save_to_disk(translator, tempdir); - auto reloaded = svs::lib::load_from_disk(tempdir); + auto reloaded = svs::lib::load_from_disk(tempdir); check(translator, external_ids, internal_ids); check(reloaded, external_ids, internal_ids); } + + CATCH_SECTION("Saving and Reloading after mutation") { + // Holes at internal 20 and 40, a renamed external ID and a moved internal ID. + translator.delete_external(std::vector{4}); + translator.remap_external_id(2, 100); + translator.remap_internal_id(40, 7); + + svs_test::prepare_temp_directory(); + auto tempdir = svs_test::temp_directory(); + svs::lib::save_to_disk(translator, tempdir); + + // Both variants share one on-disk format: the concurrent index saves the + // concurrent variant and the shared loader reads the plain one. + auto check_reloaded = [&](const auto& reloaded) { + CATCH_REQUIRE(reloaded.size() == 4); + check_same(translator, reloaded); + CATCH_REQUIRE_FALSE(reloaded.has_external(4)); + CATCH_REQUIRE_FALSE(reloaded.has_external(2)); + CATCH_REQUIRE_FALSE(reloaded.has_internal(20)); + CATCH_REQUIRE_FALSE(reloaded.has_internal(40)); + CATCH_REQUIRE(reloaded.get_internal(100) == 10); + CATCH_REQUIRE(reloaded.get_external(7) == 8); + }; + check_reloaded(svs::lib::load_from_disk(tempdir)); + check_reloaded(svs::lib::load_from_disk>(tempdir)); + } } } diff --git a/tests/svs/index/vamana/dynamic_index.cpp b/tests/svs/index/vamana/dynamic_index.cpp index 94daddcf1..a58b98c5b 100644 --- a/tests/svs/index/vamana/dynamic_index.cpp +++ b/tests/svs/index/vamana/dynamic_index.cpp @@ -445,12 +445,16 @@ CATCH_TEST_CASE("MutableVamana Index Memory Usage", "[graph_index][dynamic_index const size_t expected_graph_bytes = index.view_graph().get_data().capacity() * index.view_graph().get_data().element_size(); using Index = decltype(index); + using ExternalId = typename Index::external_id_type; + using InternalId = typename Index::internal_id_type; + const size_t translator_bytes = index.view_translator().get_memory_usage(); + CATCH_REQUIRE( + translator_bytes >= indices.size() * (sizeof(ExternalId) + sizeof(InternalId)) + + indices.size() * sizeof(ExternalId) + ); const size_t expected_metadata_bytes = - data_size * sizeof(svs::index::vamana::SlotMetadata) + - sizeof(typename Index::internal_id_type) + - 2 * indices.size() * - (sizeof(typename Index::external_id_type) + - sizeof(typename Index::internal_id_type)); + data_size * sizeof(svs::index::vamana::SlotMetadata) + sizeof(InternalId) + + translator_bytes; const size_t expected_total_bytes = expected_data_bytes + expected_graph_bytes + expected_metadata_bytes;