Skip to content

fix: keep the frequent items sketch valid when an allocation fails - #603

Draft
stojkomilos wants to merge 5 commits into
apache:masterfrom
stojkomilos:stojkomilos/fi-map-allocation-failure
Draft

stojkomilos wants to merge 5 commits into
apache:masterfrom
stojkomilos:stojkomilos/fi-map-allocation-failure

Conversation

@stojkomilos

@stojkomilos stojkomilos commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

NOT READY FOR REVIEW YET

reverse_purge_hash_map, the map inside frequent_items_sketch, can leak memory or leave the sketch broken when an allocation fails. Only a failing allocator triggers this. The serialized format does not change.

Changes

  • Constructor: allocates the keys, values and states arrays in one try, and frees the ones already allocated if one fails. Before, those arrays leaked, because the destructor does not run when a constructor throws.
  • Copy constructor: delegates the allocations to the main constructor, then copies the keys one at a time and marks each slot active only after its key is copied. Before, a failed allocation or key copy leaked the arrays and the keys already copied.
  • adjust_or_insert(): if constructing the new key throws, it empties the key's slot again. Before, the slot stayed active with no key in it, so a later lookup, serialize() or the destructor read an unconstructed key.
  • resize_or_purge_if_needed(): now gets the slot of the new key, and removes that key again if resize() throws. Before, the map kept one item over its capacity, so every later new item threw num_active ... > capacity ..., and a retry of the failed item counted it twice.
  • resize(): builds the larger map as a separate object, then swaps in its arrays. It does not move-assign the map, so update() and merge() work with an allocator or equality functor that is not assignable. Before, if the second or third allocation threw, keys_ pointed to the new uninitialized array while states_ still described the old table.
  • frequent_items_sketch copy assignment: written by hand to assign the map first, then the weights, so a failed map copy leaves the target unchanged. Before, the weights were assigned first, so a failed assignment left the target with the source's weights and its own items. The copy and move operations stay defaulted, and the member layout is unchanged.
  • frequent_items_sketch::update(): adds the weight to total_weight after the map accepts the item, so a failed update leaves the sketch unchanged. update(T&&) may move from the item even when it throws.
  • New test frequent_items_sketch_allocation_failure_test.cpp: fails each allocation in turn. Its string items allocate from the sketch's allocator, so item copies fail too.
    • Constructors: nothing leaks, and the source of a copy is unchanged.
    • Copy: a key whose copy throws is not destroyed. A key with no move constructor is copied during a resize, and a failed copy leaves the sketch unchanged.
    • Update (with no resize, with a resize, and with a purge, as an lvalue and as an rvalue): the serialized bytes are unchanged after a failure, and a retried update gives the same bytes as one that never failed.
    • Copy assignment: a failed assignment leaves the target unchanged.
    • Both merges: the sketch still works after a failure.
    • A zero-weight update, and an update of a key already in the sketch, allocate nothing, so they succeed when every allocation fails.
    • update() and merge() work with a non-assignable allocator and equality functor. reset() and assignment still need assignable ones, as on master.
    • On master, the three original test cases fail.

Not changed

  • purge(): it does not allocate for keys whose move constructor does not allocate. A key with no move constructor is copied in hash_delete(), and a failed copy there corrupts the map, as on master.
  • merge(): a failed merge leaves a usable sketch with part of the other sketch merged in. Its error bound does not yet include the other sketch's offset, so the bound can be too low.
  • Key moves, hashes and comparisons are assumed not to throw. If one throws during a resize or a purge, moved keys can be lost (resize(), hash_delete()). Only allocation failures are handled.

Checks

Comparison and timing

GCC 10.5, -O2, best of 5, two runs each:

master this PR
20M int64 updates, lg_max_map_size 14 0.766 s, 0.765 s 0.752 s, 0.748 s
2M string updates, lg_max_map_size 14 0.249 s, 0.243 s 0.242 s, 0.244 s

Both builds print hash 1e7f327e985c81af.

#include <chrono>
#include <cstdio>
#include <random>
#include <string>
#include "frequent_items_sketch.hpp"

using namespace datasketches;

static uint64_t fnv(const uint8_t* p, size_t n, uint64_t h = 1469598103934665603ULL) {
  for (size_t i = 0; i < n; ++i) { h ^= p[i]; h *= 1099511628211ULL; }
  return h;
}

template<typename T, typename Make>
uint64_t run(uint8_t lg_max, int n, uint64_t seed, Make make) {
  std::mt19937_64 rng(seed);
  std::geometric_distribution<int> skew(0.001);
  frequent_items_sketch<T> a(lg_max), b(lg_max);
  for (int i = 0; i < n; ++i) {
    a.update(make(skew(rng)), 1 + rng() % 5);
    b.update(make(static_cast<int>(rng() % 50000)));
  }
  frequent_items_sketch<T> c(a);
  c.merge(b);
  frequent_items_sketch<T> d(lg_max);
  d = c;
  d.merge(std::move(b));
  uint64_t h = 0;
  for (auto* s: {&a, &c, &d}) {
    const auto bytes = s->serialize();
    h = fnv(bytes.data(), bytes.size(), h ^ 0x9e3779b97f4a7c15ULL);
  }
  return h;
}

int main() {
  uint64_t h = 0;
  for (uint8_t lg_max: {3, 4, 6, 8, 10, 12, 14}) {
    for (uint64_t seed: {1, 2, 3}) {
      h ^= run<int64_t>(lg_max, 200000, seed, [](int x) { return static_cast<int64_t>(x); }) + seed;
      h ^= run<std::string>(lg_max, 50000, seed, [](int x) { return std::string(20, 'k') + std::to_string(x); }) * 31;
    }
  }
  std::printf("hash %016llx\n", static_cast<unsigned long long>(h));
  double best_i = 1e9, best_s = 1e9;
  for (int rep = 0; rep < 5; ++rep) {
    auto t0 = std::chrono::steady_clock::now();
    frequent_items_sketch<int64_t> s(14);
    std::mt19937_64 rng(42);
    for (int i = 0; i < 20000000; ++i) s.update(static_cast<int64_t>(rng() % 100000));
    auto t1 = std::chrono::steady_clock::now();
    frequent_items_sketch<std::string> t(14);
    for (int i = 0; i < 2000000; ++i) t.update(std::string(20, 'k') + std::to_string(rng() % 100000));
    auto t2 = std::chrono::steady_clock::now();
    best_i = std::min(best_i, std::chrono::duration<double>(t1 - t0).count());
    best_s = std::min(best_s, std::chrono::duration<double>(t2 - t1).count());
    if (s.get_num_active_items() == 0 || t.get_num_active_items() == 0) return 1;
  }
  std::printf("best of 5: int64 %.3f s, string %.3f s\n", best_i, best_s);
}

This pull request and its description were written by Isaac.

stojkomilos and others added 5 commits December 1, 2026 08:51
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
if (weight == 0) { return; }
total_weight += weight;
offset += map.adjust_or_insert(std::move(item), weight);
total_weight += weight;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The weight is now added to total_weight only after the map has accepted the item. A failed update then leaves the whole sketch unchanged, not only the map.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant