From 173dce8acb76fc190ccf71d7d4ab5dfb339866c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milo=C5=A1=20Stojko?= Date: Tue, 1 Dec 2026 08:51:38 +0000 Subject: [PATCH 1/5] fix: keep the frequent items sketch valid when an allocation fails reverse_purge_hash_map leaked its arrays when the constructor or the copy constructor failed to allocate. If constructing a new key threw, its slot stayed active with no key in it. If resize() failed to allocate, keys_ pointed to the new uninitialized array while the states described the old table. The constructors now free what they allocated, adjust_or_insert() takes the new key out again if constructing it or growing the map fails, and resize() builds the larger map separately before it changes this one. update() adds the weight after the map accepted the item, so a failed update leaves the sketch unchanged. Adds a test that fails each allocation of the constructors, updates, assignment and merges in turn. Co-authored-by: Isaac --- fi/include/frequent_items_sketch_impl.hpp | 4 +- fi/include/reverse_purge_hash_map.hpp | 2 +- fi/include/reverse_purge_hash_map_impl.hpp | 98 +++---- fi/test/CMakeLists.txt | 1 + ...t_items_sketch_allocation_failure_test.cpp | 265 ++++++++++++++++++ 5 files changed, 318 insertions(+), 52 deletions(-) create mode 100644 fi/test/frequent_items_sketch_allocation_failure_test.cpp diff --git a/fi/include/frequent_items_sketch_impl.hpp b/fi/include/frequent_items_sketch_impl.hpp index ae77ae77c..467db3d37 100644 --- a/fi/include/frequent_items_sketch_impl.hpp +++ b/fi/include/frequent_items_sketch_impl.hpp @@ -53,16 +53,16 @@ template void frequent_items_sketch::update(const T& item, W weight) { check_weight(weight); if (weight == 0) { return; } - total_weight += weight; offset += map.adjust_or_insert(item, weight); + total_weight += weight; } template void frequent_items_sketch::update(T&& item, W weight) { check_weight(weight); if (weight == 0) { return; } - total_weight += weight; offset += map.adjust_or_insert(std::move(item), weight); + total_weight += weight; } template diff --git a/fi/include/reverse_purge_hash_map.hpp b/fi/include/reverse_purge_hash_map.hpp index 4a6f2759d..a13e9dcd0 100644 --- a/fi/include/reverse_purge_hash_map.hpp +++ b/fi/include/reverse_purge_hash_map.hpp @@ -86,7 +86,7 @@ class reverse_purge_hash_map { void subtract_and_keep_positive_only(V amount); void hash_delete(uint32_t probe); uint32_t internal_adjust_or_insert(const K& key, V value); - V resize_or_purge_if_needed(); + V resize_or_purge_if_needed(uint32_t new_index); void resize(uint8_t lg_new_size); V purge(); }; diff --git a/fi/include/reverse_purge_hash_map_impl.hpp b/fi/include/reverse_purge_hash_map_impl.hpp index 73fb803e1..07e08b077 100644 --- a/fi/include/reverse_purge_hash_map_impl.hpp +++ b/fi/include/reverse_purge_hash_map_impl.hpp @@ -41,44 +41,41 @@ allocator_(allocator), lg_cur_size_(lg_cur_size), lg_max_size_(lg_max_size), num_active_(0), -keys_(allocator_.allocate(1ULL << lg_cur_size)), +keys_(nullptr), values_(nullptr), states_(nullptr) { + const size_t size = 1ULL << lg_cur_size; AllocV av(allocator_); - values_ = av.allocate(1ULL << lg_cur_size); AllocU16 au16(allocator_); - states_ = au16.allocate(1ULL << lg_cur_size); - std::fill(states_, states_ + (1ULL << lg_cur_size), static_cast(0)); + // the destructor does not run if a constructor throws + try { + keys_ = allocator_.allocate(size); + values_ = av.allocate(size); + states_ = au16.allocate(size); + } catch (...) { + if (values_ != nullptr) { av.deallocate(values_, size); } + if (keys_ != nullptr) { allocator_.deallocate(keys_, size); } + throw; + } + std::fill(states_, states_ + size, static_cast(0)); } template reverse_purge_hash_map::reverse_purge_hash_map(const reverse_purge_hash_map& other): -equal_(other.equal_), -allocator_(other.allocator_), -lg_cur_size_(other.lg_cur_size_), -lg_max_size_(other.lg_max_size_), -num_active_(other.num_active_), -keys_(allocator_.allocate(1ULL << lg_cur_size_)), -values_(nullptr), -states_(nullptr) +reverse_purge_hash_map(other.lg_cur_size_, other.lg_max_size_, other.equal_, other.allocator_) { - AllocV av(allocator_); - values_ = av.allocate(1ULL << lg_cur_size_); - AllocU16 au16(allocator_); - states_ = au16.allocate(1ULL << lg_cur_size_); + // if a key copy throws, the destructor destroys the keys of slots with states_ > 0, + // so set the state only after the key is copied const uint32_t size = 1 << lg_cur_size_; - if (num_active_ > 0) { - auto num = num_active_; - for (uint32_t i = 0; i < size; i++) { - if (other.states_[i] > 0) { - new (&keys_[i]) K(other.keys_[i]); - values_[i] = other.values_[i]; - if (--num == 0) { break; } - } + for (uint32_t i = 0; i < size && num_active_ < other.num_active_; i++) { + if (other.states_[i] > 0) { + new (&keys_[i]) K(other.keys_[i]); + values_[i] = other.values_[i]; + states_[i] = other.states_[i]; + num_active_++; } } - std::copy(other.states_, other.states_ + size, states_); } template @@ -155,8 +152,15 @@ V reverse_purge_hash_map::adjust_or_insert(FwdK&& key, V value) { const uint32_t num_active_before = num_active_; const uint32_t index = internal_adjust_or_insert(key, value); if (num_active_ > num_active_before) { - new (&keys_[index]) K(std::forward(key)); - return resize_or_purge_if_needed(); + try { + new (&keys_[index]) K(std::forward(key)); + } catch (...) { + // the slot was empty, so emptying it again leaves the map unchanged + states_[index] = 0; + num_active_--; + throw; + } + return resize_or_purge_if_needed(index); } return 0; } @@ -307,10 +311,18 @@ uint32_t reverse_purge_hash_map::internal_adjust_or_insert(const } template -V reverse_purge_hash_map::resize_or_purge_if_needed() { +V reverse_purge_hash_map::resize_or_purge_if_needed(uint32_t new_index) { if (num_active_ > get_capacity()) { if (lg_cur_size_ < lg_max_size_) { // can grow - resize(lg_cur_size_ + 1); + try { + resize(lg_cur_size_ + 1); + } catch (...) { + // resize() builds the larger map separately, so take the new key out of this one + keys_[new_index].~K(); + states_[new_index] = 0; + num_active_--; + throw; + } } else { // at target size, must purge const V offset = purge(); if (num_active_ > get_capacity()) { @@ -324,28 +336,16 @@ V reverse_purge_hash_map::resize_or_purge_if_needed() { template void reverse_purge_hash_map::resize(uint8_t lg_new_size) { - const uint32_t old_size = 1 << lg_cur_size_; - K* old_keys = keys_; - V* old_values = values_; - uint16_t* old_states = states_; - const uint32_t new_size = 1 << lg_new_size; - keys_ = allocator_.allocate(new_size); - AllocV av(allocator_); - values_ = av.allocate(new_size); - AllocU16 au16(allocator_); - states_ = au16.allocate(new_size); - std::fill(states_, states_ + new_size, static_cast(0)); - num_active_ = 0; - lg_cur_size_ = lg_new_size; - for (uint32_t i = 0; i < old_size; i++) { - if (old_states[i] > 0) { - adjust_or_insert(std::move(old_keys[i]), old_values[i]); - old_keys[i].~K(); + // if an allocation fails, this map is unchanged + reverse_purge_hash_map resized(lg_new_size, lg_max_size_, equal_, allocator_); + const uint32_t size = 1 << lg_cur_size_; + for (uint32_t i = 0; i < size; i++) { + if (states_[i] > 0) { + resized.adjust_or_insert(std::move(keys_[i]), values_[i]); } } - allocator_.deallocate(old_keys, old_size); - av.deallocate(old_values, old_size); - au16.deallocate(old_states, old_size); + // the old arrays and the moved-from keys go to resized, which frees them + *this = std::move(resized); } template diff --git a/fi/test/CMakeLists.txt b/fi/test/CMakeLists.txt index 0279b03ff..f6d5eff97 100644 --- a/fi/test/CMakeLists.txt +++ b/fi/test/CMakeLists.txt @@ -40,6 +40,7 @@ target_sources(fi_test reverse_purge_hash_map_test.cpp frequent_items_sketch_test.cpp frequent_items_sketch_custom_type_test.cpp + frequent_items_sketch_allocation_failure_test.cpp ) if (SERDE_COMPAT) diff --git a/fi/test/frequent_items_sketch_allocation_failure_test.cpp b/fi/test/frequent_items_sketch_allocation_failure_test.cpp new file mode 100644 index 000000000..26ca1361b --- /dev/null +++ b/fi/test/frequent_items_sketch_allocation_failure_test.cpp @@ -0,0 +1,265 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#include +#include +#include +#include +#include +#include + +#include "frequent_items_sketch.hpp" +#include "test_allocator.hpp" + +namespace datasketches { + +namespace { + +// After arm(n), allocation number n (counting from 0) throws std::bad_alloc. +struct allocation_control { + long count = 0; + long fail_at = -1; + void arm(long at) { count = 0; fail_at = at; } + void disarm() { fail_at = -1; } +}; + +template +struct failing_allocator: test_allocator { + allocation_control* control; + template struct rebind { using other = failing_allocator; }; + explicit failing_allocator(allocation_control& c): test_allocator(0), control(&c) {} + template + failing_allocator(const failing_allocator& other): test_allocator(0), control(other.control) {} + T* allocate(std::size_t n, const T* hint = nullptr) { + if (control->fail_at >= 0 && control->count++ == control->fail_at) throw std::bad_alloc(); + return test_allocator::allocate(n, hint); + } +}; + +template +bool operator==(const failing_allocator& a, const failing_allocator& b) { return a.control == b.control; } +template +bool operator!=(const failing_allocator& a, const failing_allocator& b) { return !(a == b); } + +// the items allocate through the same allocation_control, so copying an item into the sketch can fail too +using item_type = std::basic_string, failing_allocator>; + +struct item_hash { + size_t operator()(const item_type& item) const { + return std::hash()(std::string(item.data(), item.size())); + } +}; + +// serialize only: enough to compare sketches by their bytes +struct item_serde { + size_t size_of_item(const item_type& item) const { return sizeof(uint32_t) + item.size(); } + size_t serialize(void* ptr, size_t capacity, const item_type* items, unsigned num) const { + char* p = static_cast(ptr); + for (unsigned i = 0; i < num; ++i) { + if (size_of_item(items[i]) > capacity - (p - static_cast(ptr))) throw std::out_of_range("capacity"); + const uint32_t size = static_cast(items[i].size()); + std::memcpy(p, &size, sizeof(size)); + std::memcpy(p + sizeof(size), items[i].data(), size); + p += sizeof(size) + size; + } + return p - static_cast(ptr); + } +}; + +using sketch_type = frequent_items_sketch, + failing_allocator>; + +item_type make_item(int i, allocation_control& control) { + // longer than the small string buffer, so that copying the item allocates + const std::string s = std::string(32, 'x') + std::to_string(i); + return item_type(s.data(), s.size(), failing_allocator(control)); +} + +sketch_type make_sketch(uint8_t lg_max, uint8_t lg_start, int first, int count, allocation_control& control) { + sketch_type sketch(lg_max, lg_start, std::equal_to(), failing_allocator(control)); + for (int i = first; i < first + count; ++i) sketch.update(make_item(i, control), i % 3 + 1); + return sketch; +} + +std::vector bytes(const sketch_type& sketch) { + const auto bytes = sketch.serialize(0, item_serde()); + return std::vector(bytes.begin(), bytes.end()); +} + +// disarms the control, then checks that the sketch still updates, queries and serializes +void check_usable(sketch_type& sketch, allocation_control& control) { + control.disarm(); + const uint64_t total_weight = sketch.get_total_weight(); + const item_type item = make_item(-1, control); + sketch.update(item, 5); + REQUIRE(sketch.get_total_weight() == total_weight + 5); + REQUIRE(sketch.get_estimate(item) >= 5); + REQUIRE(sketch.get_frequent_items(NO_FALSE_POSITIVES).size() <= sketch.get_num_active_items()); + REQUIRE(bytes(sketch).size() > 0); +} + +// Fails each allocation of an update in turn, until the update completes. +// Checks that a failed update leaves the sketch unchanged, and that the update can then be retried. +// Returns the number of allocations of a successful update. +template +long check_update_failures(uint8_t lg_max, uint8_t lg_start, int count) { + allocation_control control; + sketch_type expected = make_sketch(lg_max, lg_start, 0, count, control); + expected.update(make_item(count, control), 7); + for (long fail_at = 0; ; ++fail_at) { + sketch_type sketch = make_sketch(lg_max, lg_start, 0, count, control); + const auto bytes_before = bytes(sketch); + item_type item = make_item(count, control); + control.arm(fail_at); + try { + if (move_item) sketch.update(std::move(item), 7); else sketch.update(item, 7); + control.disarm(); + REQUIRE(bytes(sketch) == bytes(expected)); + return fail_at; + } catch (const std::bad_alloc&) { + control.disarm(); + REQUIRE(bytes(sketch) == bytes_before); + sketch.update(make_item(count, control), 7); + REQUIRE(bytes(sketch) == bytes(expected)); + } + } +} + +} // namespace + +TEST_CASE("frequent items: allocation failure in a constructor", "[frequent_items_sketch]") { + test_allocator_total_bytes = 0; + test_allocator_net_allocations = 0; + allocation_control control; + long failures_tested = 0; + for (long fail_at = 0; ; ++fail_at) { + control.arm(fail_at); + try { + sketch_type sketch(6, 3, std::equal_to(), failing_allocator(control)); + control.disarm(); + break; + } catch (const std::bad_alloc&) { + REQUIRE(test_allocator_net_allocations == 0); + ++failures_tested; + } + } + // the 3 arrays of the map + REQUIRE(failures_tested == 3); + + { + control.disarm(); + const sketch_type source = make_sketch(6, 3, 0, 20, control); + const auto source_bytes = bytes(source); + const long long net_allocations = test_allocator_net_allocations; + failures_tested = 0; + for (long fail_at = 0; ; ++fail_at) { + control.arm(fail_at); + try { + sketch_type copy(source); + control.disarm(); + REQUIRE(bytes(copy) == source_bytes); + break; + } catch (const std::bad_alloc&) { + control.disarm(); + REQUIRE(test_allocator_net_allocations == net_allocations); + REQUIRE(bytes(source) == source_bytes); + ++failures_tested; + } + } + // the 3 arrays of the map and the 20 items + REQUIRE(failures_tested == 23); + + for (long fail_at = 0; ; ++fail_at) { + sketch_type target = make_sketch(6, 3, 100, 5, control); + control.arm(fail_at); + try { + target = source; + control.disarm(); + REQUIRE(bytes(target) == source_bytes); + break; + } catch (const std::bad_alloc&) { + check_usable(target, control); + } + } + } + REQUIRE(test_allocator_total_bytes == 0); + REQUIRE(test_allocator_net_allocations == 0); +} + +TEST_CASE("frequent items: a failed update leaves the sketch unchanged", "[frequent_items_sketch]") { + test_allocator_total_bytes = 0; + test_allocator_net_allocations = 0; + // a new item without a resize, a new item that grows the map from 8 to 16 slots, + // and a new item that makes the map purge at its maximum size + for (uint8_t lg_max: {6, 3}) { + for (int count: {2, 6}) { + CAPTURE(lg_max, count); + REQUIRE(check_update_failures(lg_max, 3, count) > 0); + REQUIRE(check_update_failures(lg_max, 3, count) >= 0); + } + } + // lvalue: the item copy and the 3 arrays of the larger map. rvalue: the 3 arrays + REQUIRE(check_update_failures(6, 3, 6) == 4); + REQUIRE(check_update_failures(6, 3, 6) == 3); + REQUIRE(test_allocator_total_bytes == 0); + REQUIRE(test_allocator_net_allocations == 0); +} + +TEST_CASE("frequent items: a failed merge leaves the sketch usable", "[frequent_items_sketch]") { + test_allocator_total_bytes = 0; + test_allocator_net_allocations = 0; + allocation_control control; + // into a map that grows, and into a map that purges at its maximum size + for (uint8_t lg_max: {6, 4}) { + CAPTURE(lg_max); + const sketch_type source = make_sketch(lg_max, 3, 5, 30, control); + const auto source_bytes = bytes(source); + long failures_tested = 0; + for (long fail_at = 0; ; ++fail_at) { + sketch_type target = make_sketch(lg_max, 3, 0, 10, control); + control.arm(fail_at); + try { + target.merge(source); + control.disarm(); + break; + } catch (const std::bad_alloc&) { + check_usable(target, control); + REQUIRE(bytes(source) == source_bytes); + ++failures_tested; + } + } + REQUIRE(failures_tested > 0); + for (long fail_at = 0; ; ++fail_at) { + sketch_type target = make_sketch(lg_max, 3, 0, 10, control); + sketch_type moved_source(source); + control.arm(fail_at); + try { + target.merge(std::move(moved_source)); + control.disarm(); + break; + } catch (const std::bad_alloc&) { + check_usable(target, control); + } + } + } + REQUIRE(test_allocator_total_bytes == 0); + REQUIRE(test_allocator_net_allocations == 0); +} + +} /* namespace datasketches */ From 383bfd2bb4942233f0629629f065419b3f4f649b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milo=C5=A1=20Stojko?= Date: Tue, 1 Dec 2026 10:00:10 +0000 Subject: [PATCH 2/5] fix: swap buffers in resize instead of move-assigning the map The move assignment also swapped equal_ and allocator_, so update() needed them to be assignable. Swap only the buffers. Document that a failed update(T&&) consumes the item. Add tests for a key whose copy throws, for a non-assignable allocator and functor, and for updates that need no allocation. Co-authored-by: Isaac --- fi/include/frequent_items_sketch.hpp | 1 + fi/include/reverse_purge_hash_map_impl.hpp | 8 +- ...t_items_sketch_allocation_failure_test.cpp | 126 ++++++++++++++++++ 3 files changed, 133 insertions(+), 2 deletions(-) diff --git a/fi/include/frequent_items_sketch.hpp b/fi/include/frequent_items_sketch.hpp index 2dd337e5e..3d9b25c3d 100644 --- a/fi/include/frequent_items_sketch.hpp +++ b/fi/include/frequent_items_sketch.hpp @@ -91,6 +91,7 @@ class frequent_items_sketch { * Update this sketch with an item and a positive weight (frequency count). * If cross-language portability is required, callers should ensure that * the input string uses a compatible encoding (valid UTF-8). + * The item is moved from even if the call throws. * @param item for which the weight should be increased (rvalue) * @param weight the amount by which the weight of the item should be increased * A count of zero is a no-op, and a negative count will throw an exception. diff --git a/fi/include/reverse_purge_hash_map_impl.hpp b/fi/include/reverse_purge_hash_map_impl.hpp index 07e08b077..da5a54956 100644 --- a/fi/include/reverse_purge_hash_map_impl.hpp +++ b/fi/include/reverse_purge_hash_map_impl.hpp @@ -344,8 +344,12 @@ void reverse_purge_hash_map::resize(uint8_t lg_new_size) { resized.adjust_or_insert(std::move(keys_[i]), values_[i]); } } - // the old arrays and the moved-from keys go to resized, which frees them - *this = std::move(resized); + // equal_ and allocator_ may not be assignable, so swap only the buffers + std::swap(lg_cur_size_, resized.lg_cur_size_); + std::swap(num_active_, resized.num_active_); + std::swap(keys_, resized.keys_); + std::swap(values_, resized.values_); + std::swap(states_, resized.states_); } template diff --git a/fi/test/frequent_items_sketch_allocation_failure_test.cpp b/fi/test/frequent_items_sketch_allocation_failure_test.cpp index 26ca1361b..64d86ebcc 100644 --- a/fi/test/frequent_items_sketch_allocation_failure_test.cpp +++ b/fi/test/frequent_items_sketch_allocation_failure_test.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -134,6 +135,7 @@ long check_update_failures(uint8_t lg_max, uint8_t lg_start, int count) { return fail_at; } catch (const std::bad_alloc&) { control.disarm(); + if (move_item) REQUIRE(item.empty()); // a failed rvalue update consumes the item REQUIRE(bytes(sketch) == bytes_before); sketch.update(make_item(count, control), 7); REQUIRE(bytes(sketch) == bytes(expected)); @@ -141,6 +143,36 @@ long check_update_failures(uint8_t lg_max, uint8_t lg_start, int count) { } } +// a key that counts destructions of keys whose copy never finished +struct guarded_key { + static constexpr uint64_t MAGIC = 0x5afe5afe5afe5afeULL; + static long bad_destructions; + item_type value; + uint64_t magic; + guarded_key(const item_type& v): value(v), magic(MAGIC) {} + guarded_key(item_type&& v): value(std::move(v)), magic(MAGIC) {} + guarded_key(const guarded_key& o): value(o.value), magic(MAGIC) {} + guarded_key(guarded_key&& o) noexcept: value(std::move(o.value)), magic(MAGIC) {} + ~guarded_key() { if (magic != MAGIC) ++bad_destructions; magic = 0; } + guarded_key& operator=(const guarded_key&) = delete; +}; +long guarded_key::bad_destructions = 0; + +struct guarded_hash { + size_t operator()(const guarded_key& k) const { return item_hash()(k.value); } +}; +struct guarded_equal { + bool operator()(const guarded_key& a, const guarded_key& b) const { return a.value == b.value; } +}; +using guarded_sketch = frequent_items_sketch>; + +guarded_sketch make_guarded_sketch(uint8_t lg_max, int count, allocation_control& control) { + guarded_sketch sketch(lg_max, 3, guarded_equal(), failing_allocator(control)); + for (int i = 0; i < count; ++i) sketch.update(guarded_key(make_item(i, control)), i % 3 + 1); + return sketch; +} + } // namespace TEST_CASE("frequent items: allocation failure in a constructor", "[frequent_items_sketch]") { @@ -262,4 +294,98 @@ TEST_CASE("frequent items: a failed merge leaves the sketch usable", "[frequent_ REQUIRE(test_allocator_net_allocations == 0); } +TEST_CASE("frequent items: a key whose copy throws is not destroyed", "[frequent_items_sketch]") { + test_allocator_total_bytes = 0; + test_allocator_net_allocations = 0; + guarded_key::bad_destructions = 0; + allocation_control control; + { + const guarded_sketch source = make_guarded_sketch(6, 20, control); + for (long fail_at = 0; ; ++fail_at) { + control.arm(fail_at); + try { + guarded_sketch copy(source); + control.disarm(); + break; + } catch (const std::bad_alloc&) { + control.disarm(); + } + } + } + REQUIRE(guarded_key::bad_destructions == 0); + for (uint8_t lg_max: {6, 3}) { + for (long fail_at = 0; ; ++fail_at) { + guarded_sketch sketch = make_guarded_sketch(lg_max, 6, control); + control.arm(fail_at); + try { + sketch.update(guarded_key(make_item(100, control)), 7); + control.disarm(); + break; + } catch (const std::bad_alloc&) { + control.disarm(); + } + } + } + REQUIRE(guarded_key::bad_destructions == 0); + REQUIRE(test_allocator_total_bytes == 0); + REQUIRE(test_allocator_net_allocations == 0); +} + +TEST_CASE("frequent items: an update that needs no allocation succeeds when every allocation fails", + "[frequent_items_sketch]") { + test_allocator_total_bytes = 0; + test_allocator_net_allocations = 0; + allocation_control control; + { + // 3 is already in the sketch + sketch_type expected = make_sketch(6, 3, 0, 5, control); + sketch_type sketch = make_sketch(6, 3, 0, 5, control); + const item_type fresh = make_item(50, control); + const item_type key = make_item(3, control); + expected.update(key, 4); + control.arm(0); + sketch.update(fresh, 0); // zero weight returns before the map and copies nothing + sketch.update(key, 4); // the key is found, so the map copies nothing + control.disarm(); + REQUIRE(bytes(sketch) == bytes(expected)); + } + REQUIRE(test_allocator_total_bytes == 0); + REQUIRE(test_allocator_net_allocations == 0); +} + +namespace { + +// const members make copy and move assignment unusable, like std::pmr::polymorphic_allocator +template +struct non_assignable_allocator { + using value_type = T; + const int tag = 0; + non_assignable_allocator() = default; + template non_assignable_allocator(const non_assignable_allocator&) {} + T* allocate(std::size_t n) { return std::allocator().allocate(n); } + void deallocate(T* p, std::size_t n) { std::allocator().deallocate(p, n); } +}; +template +bool operator==(const non_assignable_allocator&, const non_assignable_allocator&) { return true; } +template +bool operator!=(const non_assignable_allocator&, const non_assignable_allocator&) { return false; } + +struct non_assignable_equal { + const int tag = 0; + bool operator()(int a, int b) const { return a == b; } +}; + +} // namespace + +TEST_CASE("frequent items: a non-assignable allocator and equality functor", "[frequent_items_sketch]") { + using sketch = frequent_items_sketch, non_assignable_equal, + non_assignable_allocator>; + // the map grows from 8 to 256 slots, so resize() runs + sketch s(10, 3, non_assignable_equal(), non_assignable_allocator()); + for (int i = 0; i < 100; ++i) s.update(i); + REQUIRE(s.get_num_active_items() == 100); + REQUIRE(s.get_total_weight() == 100); + REQUIRE(s.get_estimate(42) == 1); +} + } /* namespace datasketches */ From 6e69b05d7f54f76e97c75cf43dfb590da58a1e39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milo=C5=A1=20Stojko?= Date: Tue, 1 Dec 2026 10:31:20 +0000 Subject: [PATCH 3/5] fix: keep the target unchanged when a copy assignment fails Declare the map first, so the implicit copy assignment fails before the weights change. Clarify the copy constructor comment, and remove a swap that does nothing. Test that a failed copy assignment leaves the target unchanged, and that a key copy failure in update() does not destroy the key. Co-authored-by: Isaac --- fi/include/frequent_items_sketch.hpp | 4 ++-- fi/include/frequent_items_sketch_impl.hpp | 6 +++--- fi/include/reverse_purge_hash_map_impl.hpp | 6 ++---- .../frequent_items_sketch_allocation_failure_test.cpp | 11 ++++++++--- 4 files changed, 15 insertions(+), 12 deletions(-) diff --git a/fi/include/frequent_items_sketch.hpp b/fi/include/frequent_items_sketch.hpp index 3d9b25c3d..2fcaaf118 100644 --- a/fi/include/frequent_items_sketch.hpp +++ b/fi/include/frequent_items_sketch.hpp @@ -91,7 +91,7 @@ class frequent_items_sketch { * Update this sketch with an item and a positive weight (frequency count). * If cross-language portability is required, callers should ensure that * the input string uses a compatible encoding (valid UTF-8). - * The item is moved from even if the call throws. + * The item may be moved from, even if the call throws. * @param item for which the weight should be increased (rvalue) * @param weight the amount by which the weight of the item should be increased * A count of zero is a no-op, and a negative count will throw an exception. @@ -326,9 +326,9 @@ class frequent_items_sketch { // in C++ and Java to indicate an empty sketch, therefore both are set for compatibility with // the historical binary format, and either one is accepted on read. No other flag bits are defined. enum flags { IS_EMPTY_1 = 0, IS_EMPTY_2 = 2 }; + reverse_purge_hash_map map; W total_weight; W offset; - reverse_purge_hash_map map; static void check_preamble_longs(uint8_t preamble_longs, uint8_t flags_byte); static void check_total_weight(W total_weight); static void check_serial_version(uint8_t serial_version); diff --git a/fi/include/frequent_items_sketch_impl.hpp b/fi/include/frequent_items_sketch_impl.hpp index 467db3d37..50846cff2 100644 --- a/fi/include/frequent_items_sketch_impl.hpp +++ b/fi/include/frequent_items_sketch_impl.hpp @@ -37,14 +37,14 @@ const uint8_t frequent_items_sketch::LG_MIN_MAP_SIZE; template frequent_items_sketch::frequent_items_sketch(uint8_t lg_max_map_size, uint8_t lg_start_map_size, const E& equal, const A& allocator): -total_weight(0), -offset(0), map( std::max(lg_start_map_size, frequent_items_sketch::LG_MIN_MAP_SIZE), std::max(lg_max_map_size, frequent_items_sketch::LG_MIN_MAP_SIZE), equal, allocator -) +), +total_weight(0), +offset(0) { if (lg_start_map_size > lg_max_map_size) { throw std::invalid_argument("starting size must not be greater than maximum size"); } } diff --git a/fi/include/reverse_purge_hash_map_impl.hpp b/fi/include/reverse_purge_hash_map_impl.hpp index da5a54956..258660f26 100644 --- a/fi/include/reverse_purge_hash_map_impl.hpp +++ b/fi/include/reverse_purge_hash_map_impl.hpp @@ -65,8 +65,7 @@ template reverse_purge_hash_map::reverse_purge_hash_map(const reverse_purge_hash_map& other): reverse_purge_hash_map(other.lg_cur_size_, other.lg_max_size_, other.equal_, other.allocator_) { - // if a key copy throws, the destructor destroys the keys of slots with states_ > 0, - // so set the state only after the key is copied + // the destructor stops after num_active_ keys, so count a key only once it is built const uint32_t size = 1 << lg_cur_size_; for (uint32_t i = 0; i < size && num_active_ < other.num_active_; i++) { if (other.states_[i] > 0) { @@ -336,7 +335,7 @@ V reverse_purge_hash_map::resize_or_purge_if_needed(uint32_t new_ template void reverse_purge_hash_map::resize(uint8_t lg_new_size) { - // if an allocation fails, this map is unchanged + // an allocation failure leaves this map unchanged; key moves, hashes and comparisons must not throw reverse_purge_hash_map resized(lg_new_size, lg_max_size_, equal_, allocator_); const uint32_t size = 1 << lg_cur_size_; for (uint32_t i = 0; i < size; i++) { @@ -346,7 +345,6 @@ void reverse_purge_hash_map::resize(uint8_t lg_new_size) { } // equal_ and allocator_ may not be assignable, so swap only the buffers std::swap(lg_cur_size_, resized.lg_cur_size_); - std::swap(num_active_, resized.num_active_); std::swap(keys_, resized.keys_); std::swap(values_, resized.values_); std::swap(states_, resized.states_); diff --git a/fi/test/frequent_items_sketch_allocation_failure_test.cpp b/fi/test/frequent_items_sketch_allocation_failure_test.cpp index 64d86ebcc..db7553a40 100644 --- a/fi/test/frequent_items_sketch_allocation_failure_test.cpp +++ b/fi/test/frequent_items_sketch_allocation_failure_test.cpp @@ -175,7 +175,7 @@ guarded_sketch make_guarded_sketch(uint8_t lg_max, int count, allocation_control } // namespace -TEST_CASE("frequent items: allocation failure in a constructor", "[frequent_items_sketch]") { +TEST_CASE("frequent items: allocation failure in a constructor, copy or assignment", "[frequent_items_sketch]") { test_allocator_total_bytes = 0; test_allocator_net_allocations = 0; allocation_control control; @@ -219,6 +219,7 @@ TEST_CASE("frequent items: allocation failure in a constructor", "[frequent_item for (long fail_at = 0; ; ++fail_at) { sketch_type target = make_sketch(6, 3, 100, 5, control); + const auto target_bytes = bytes(target); control.arm(fail_at); try { target = source; @@ -226,6 +227,8 @@ TEST_CASE("frequent items: allocation failure in a constructor", "[frequent_item REQUIRE(bytes(target) == source_bytes); break; } catch (const std::bad_alloc&) { + control.disarm(); + REQUIRE(bytes(target) == target_bytes); check_usable(target, control); } } @@ -243,7 +246,7 @@ TEST_CASE("frequent items: a failed update leaves the sketch unchanged", "[frequ for (int count: {2, 6}) { CAPTURE(lg_max, count); REQUIRE(check_update_failures(lg_max, 3, count) > 0); - REQUIRE(check_update_failures(lg_max, 3, count) >= 0); + check_update_failures(lg_max, 3, count); // the helper checks each failure } } // lvalue: the item copy and the 3 arrays of the larger map. rvalue: the 3 arrays @@ -316,9 +319,11 @@ TEST_CASE("frequent items: a key whose copy throws is not destroyed", "[frequent for (uint8_t lg_max: {6, 3}) { for (long fail_at = 0; ; ++fail_at) { guarded_sketch sketch = make_guarded_sketch(lg_max, 6, control); + // an lvalue, so that the map copies the key and the copy can fail + const guarded_key key(make_item(100, control)); control.arm(fail_at); try { - sketch.update(guarded_key(make_item(100, control)), 7); + sketch.update(key, 7); control.disarm(); break; } catch (const std::bad_alloc&) { From 04cb1065313c7d35451f19cd5d696d9b0dc32cd6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milo=C5=A1=20Stojko?= Date: Tue, 1 Dec 2026 10:49:04 +0000 Subject: [PATCH 4/5] fix: write copy assignment by hand so the map is assigned first Restore the member order. Assign the map before the weights, so a failed copy leaves the target unchanged. Default the copy and move operations, which a user-declared copy assignment would otherwise suppress. Co-authored-by: Isaac --- fi/include/frequent_items_sketch.hpp | 6 +++++- fi/include/frequent_items_sketch_impl.hpp | 15 ++++++++++++--- ...quent_items_sketch_allocation_failure_test.cpp | 1 + 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/fi/include/frequent_items_sketch.hpp b/fi/include/frequent_items_sketch.hpp index 2fcaaf118..1f561630d 100644 --- a/fi/include/frequent_items_sketch.hpp +++ b/fi/include/frequent_items_sketch.hpp @@ -76,6 +76,10 @@ class frequent_items_sketch { */ explicit frequent_items_sketch(uint8_t lg_max_map_size, uint8_t lg_start_map_size = LG_MIN_MAP_SIZE, const E& equal = E(), const A& allocator = A()); + frequent_items_sketch(const frequent_items_sketch& other) = default; + frequent_items_sketch(frequent_items_sketch&& other) = default; + frequent_items_sketch& operator=(const frequent_items_sketch& other); + frequent_items_sketch& operator=(frequent_items_sketch&& other) = default; /** * Update this sketch with an item and a positive weight (frequency count). @@ -326,9 +330,9 @@ class frequent_items_sketch { // in C++ and Java to indicate an empty sketch, therefore both are set for compatibility with // the historical binary format, and either one is accepted on read. No other flag bits are defined. enum flags { IS_EMPTY_1 = 0, IS_EMPTY_2 = 2 }; - reverse_purge_hash_map map; W total_weight; W offset; + reverse_purge_hash_map map; static void check_preamble_longs(uint8_t preamble_longs, uint8_t flags_byte); static void check_total_weight(W total_weight); static void check_serial_version(uint8_t serial_version); diff --git a/fi/include/frequent_items_sketch_impl.hpp b/fi/include/frequent_items_sketch_impl.hpp index 50846cff2..45e58204c 100644 --- a/fi/include/frequent_items_sketch_impl.hpp +++ b/fi/include/frequent_items_sketch_impl.hpp @@ -37,18 +37,27 @@ const uint8_t frequent_items_sketch::LG_MIN_MAP_SIZE; template frequent_items_sketch::frequent_items_sketch(uint8_t lg_max_map_size, uint8_t lg_start_map_size, const E& equal, const A& allocator): +total_weight(0), +offset(0), map( std::max(lg_start_map_size, frequent_items_sketch::LG_MIN_MAP_SIZE), std::max(lg_max_map_size, frequent_items_sketch::LG_MIN_MAP_SIZE), equal, allocator -), -total_weight(0), -offset(0) +) { if (lg_start_map_size > lg_max_map_size) { throw std::invalid_argument("starting size must not be greater than maximum size"); } } +template +frequent_items_sketch& frequent_items_sketch::operator=(const frequent_items_sketch& other) { + // map first: its copy can throw, and the weights must not change then + map = other.map; + total_weight = other.total_weight; + offset = other.offset; + return *this; +} + template void frequent_items_sketch::update(const T& item, W weight) { check_weight(weight); diff --git a/fi/test/frequent_items_sketch_allocation_failure_test.cpp b/fi/test/frequent_items_sketch_allocation_failure_test.cpp index db7553a40..5bcda096e 100644 --- a/fi/test/frequent_items_sketch_allocation_failure_test.cpp +++ b/fi/test/frequent_items_sketch_allocation_failure_test.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include From 67b98656d86cf8aea6ac04cf87d5bf775839d24f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milo=C5=A1=20Stojko?= Date: Tue, 1 Dec 2026 11:16:27 +0000 Subject: [PATCH 5/5] fix: document copy and move operations, tighten allocation tests Add Doxygen comments to the four new operations. In the tests, count the failures of the assignment and rvalue merge loops, drop the check on a moved-from string, and test a key with no move constructor during a resize. Co-authored-by: Isaac --- fi/include/frequent_items_sketch.hpp | 21 +++++++++++ ...t_items_sketch_allocation_failure_test.cpp | 36 +++++++++++-------- 2 files changed, 42 insertions(+), 15 deletions(-) diff --git a/fi/include/frequent_items_sketch.hpp b/fi/include/frequent_items_sketch.hpp index 1f561630d..b43fa3d22 100644 --- a/fi/include/frequent_items_sketch.hpp +++ b/fi/include/frequent_items_sketch.hpp @@ -76,9 +76,30 @@ class frequent_items_sketch { */ explicit frequent_items_sketch(uint8_t lg_max_map_size, uint8_t lg_start_map_size = LG_MIN_MAP_SIZE, const E& equal = E(), const A& allocator = A()); + /** + * Copy constructor + * @param other sketch to be copied + */ frequent_items_sketch(const frequent_items_sketch& other) = default; + + /** + * Move constructor + * @param other sketch to be moved + */ frequent_items_sketch(frequent_items_sketch&& other) = default; + + /** + * Copy assignment + * @param other sketch to be copied + * @return reference to this sketch + */ frequent_items_sketch& operator=(const frequent_items_sketch& other); + + /** + * Move assignment + * @param other sketch to be moved + * @return reference to this sketch + */ frequent_items_sketch& operator=(frequent_items_sketch&& other) = default; /** diff --git a/fi/test/frequent_items_sketch_allocation_failure_test.cpp b/fi/test/frequent_items_sketch_allocation_failure_test.cpp index 5bcda096e..12ffcce4d 100644 --- a/fi/test/frequent_items_sketch_allocation_failure_test.cpp +++ b/fi/test/frequent_items_sketch_allocation_failure_test.cpp @@ -136,7 +136,6 @@ long check_update_failures(uint8_t lg_max, uint8_t lg_start, int count) { return fail_at; } catch (const std::bad_alloc&) { control.disarm(); - if (move_item) REQUIRE(item.empty()); // a failed rvalue update consumes the item REQUIRE(bytes(sketch) == bytes_before); sketch.update(make_item(count, control), 7); REQUIRE(bytes(sketch) == bytes(expected)); @@ -153,7 +152,6 @@ struct guarded_key { guarded_key(const item_type& v): value(v), magic(MAGIC) {} guarded_key(item_type&& v): value(std::move(v)), magic(MAGIC) {} guarded_key(const guarded_key& o): value(o.value), magic(MAGIC) {} - guarded_key(guarded_key&& o) noexcept: value(std::move(o.value)), magic(MAGIC) {} ~guarded_key() { if (magic != MAGIC) ++bad_destructions; magic = 0; } guarded_key& operator=(const guarded_key&) = delete; }; @@ -218,6 +216,7 @@ TEST_CASE("frequent items: allocation failure in a constructor, copy or assignme // the 3 arrays of the map and the 20 items REQUIRE(failures_tested == 23); + failures_tested = 0; for (long fail_at = 0; ; ++fail_at) { sketch_type target = make_sketch(6, 3, 100, 5, control); const auto target_bytes = bytes(target); @@ -231,8 +230,10 @@ TEST_CASE("frequent items: allocation failure in a constructor, copy or assignme control.disarm(); REQUIRE(bytes(target) == target_bytes); check_usable(target, control); + ++failures_tested; } } + REQUIRE(failures_tested == 23); } REQUIRE(test_allocator_total_bytes == 0); REQUIRE(test_allocator_net_allocations == 0); @@ -281,6 +282,7 @@ TEST_CASE("frequent items: a failed merge leaves the sketch usable", "[frequent_ } } REQUIRE(failures_tested > 0); + failures_tested = 0; for (long fail_at = 0; ; ++fail_at) { sketch_type target = make_sketch(lg_max, 3, 0, 10, control); sketch_type moved_source(source); @@ -291,8 +293,11 @@ TEST_CASE("frequent items: a failed merge leaves the sketch usable", "[frequent_ break; } catch (const std::bad_alloc&) { check_usable(target, control); + ++failures_tested; } } + // a grow allocates, a purge moves keys without allocating + if (lg_max == 6) REQUIRE(failures_tested > 0); else REQUIRE(failures_tested == 0); } REQUIRE(test_allocator_total_bytes == 0); REQUIRE(test_allocator_net_allocations == 0); @@ -317,19 +322,20 @@ TEST_CASE("frequent items: a key whose copy throws is not destroyed", "[frequent } } REQUIRE(guarded_key::bad_destructions == 0); - for (uint8_t lg_max: {6, 3}) { - for (long fail_at = 0; ; ++fail_at) { - guarded_sketch sketch = make_guarded_sketch(lg_max, 6, control); - // an lvalue, so that the map copies the key and the copy can fail - const guarded_key key(make_item(100, control)); - control.arm(fail_at); - try { - sketch.update(key, 7); - control.disarm(); - break; - } catch (const std::bad_alloc&) { - control.disarm(); - } + // lg_max 6 only: with no move constructor, the resize copies the keys. A purge would copy them too, + // and a failed copy there is not handled. + for (long fail_at = 0; ; ++fail_at) { + guarded_sketch sketch = make_guarded_sketch(6, 6, control); + // an lvalue, so that the map copies the key and the copy can fail + const guarded_key key(make_item(100, control)); + control.arm(fail_at); + try { + sketch.update(key, 7); + control.disarm(); + break; + } catch (const std::bad_alloc&) { + control.disarm(); + REQUIRE(sketch.get_num_active_items() == 6); } } REQUIRE(guarded_key::bad_destructions == 0);