diff --git a/fi/include/frequent_items_sketch.hpp b/fi/include/frequent_items_sketch.hpp index 2dd337e5..b43fa3d2 100644 --- a/fi/include/frequent_items_sketch.hpp +++ b/fi/include/frequent_items_sketch.hpp @@ -76,6 +76,31 @@ 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; /** * Update this sketch with an item and a positive weight (frequency count). @@ -91,6 +116,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 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. diff --git a/fi/include/frequent_items_sketch_impl.hpp b/fi/include/frequent_items_sketch_impl.hpp index ae77ae77..45e58204 100644 --- a/fi/include/frequent_items_sketch_impl.hpp +++ b/fi/include/frequent_items_sketch_impl.hpp @@ -49,20 +49,29 @@ map( 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); 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 4a6f2759..a13e9dcd 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 73fb803e..258660f2 100644 --- a/fi/include/reverse_purge_hash_map_impl.hpp +++ b/fi/include/reverse_purge_hash_map_impl.hpp @@ -41,44 +41,40 @@ 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_); + // the destructor stops after num_active_ keys, so count a key only once it is built 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 +151,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 +310,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 +335,19 @@ 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(); + // 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++) { + 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); + // equal_ and allocator_ may not be assignable, so swap only the buffers + std::swap(lg_cur_size_, resized.lg_cur_size_); + std::swap(keys_, resized.keys_); + std::swap(values_, resized.values_); + std::swap(states_, resized.states_); } template diff --git a/fi/test/CMakeLists.txt b/fi/test/CMakeLists.txt index 0279b03f..f6d5eff9 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 00000000..12ffcce4 --- /dev/null +++ b/fi/test/frequent_items_sketch_allocation_failure_test.cpp @@ -0,0 +1,403 @@ +/* + * 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 +#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)); + } + } +} + +// 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() { 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, copy or assignment", "[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); + + 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); + control.arm(fail_at); + try { + target = source; + control.disarm(); + REQUIRE(bytes(target) == source_bytes); + break; + } catch (const std::bad_alloc&) { + 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); +} + +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); + 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 + 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); + 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); + ++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); +} + +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); + // 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); + 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 */