From 22503bc72bd16d1e567899ae1891107e123541c4 Mon Sep 17 00:00:00 2001 From: Christoph Viebig Date: Wed, 9 Sep 2026 12:10:11 +0000 Subject: [PATCH 1/3] Add controlled KLL randomness Allow callers to provide a random-bit generator to `kll_sketch` updates and merges while preserving the existing API behavior. The generator must meet the standard UniformRandomBitGenerator requirements, checked by the new is_uniform_random_bit_generator trait, so standard engines such as std::mt19937_64 can be passed directly. Accepting any callable that returns a value convertible to bool would accept these engines too, but would take almost every 32-bit output as 1. Each bit comes from random_bit_from(), which tells whether the output is in the upper half of the generator's range. Unlike std::bernoulli_distribution, this depends only on the generator output, so a given generator state gives the same sketch with any standard library. The default generator has the range {0, 1}, so its bits are unchanged. --- common/include/common_defs.hpp | 50 +++++++++ common/test/CMakeLists.txt | 1 + common/test/random_bit_test.cpp | 175 ++++++++++++++++++++++++++++++++ kll/include/kll_helper.hpp | 13 +-- kll/include/kll_helper_impl.hpp | 23 +++-- kll/include/kll_sketch.hpp | 55 +++++++++- kll/include/kll_sketch_impl.hpp | 58 +++++++---- kll/test/kll_sketch_test.cpp | 85 ++++++++++++++++ 8 files changed, 421 insertions(+), 39 deletions(-) create mode 100644 common/test/random_bit_test.cpp diff --git a/common/include/common_defs.hpp b/common/include/common_defs.hpp index 6a87e079a..e8ec25331 100644 --- a/common/include/common_defs.hpp +++ b/common/include/common_defs.hpp @@ -27,6 +27,8 @@ #include #include #include +#include +#include /// DataSketches namespace namespace datasketches { @@ -54,6 +56,54 @@ namespace random_utils { } } +template struct make_void { using type = void; }; + +/** + * C++11 version of the UniformRandomBitGenerator requirements of the standard library, + * which C++20 expresses as std::uniform_random_bit_generator plus G::result_type: + * G::result_type is an unsigned integer type, G::min() and G::max() are constant expressions of that type + * with G::min() < G::max(), and invoking a non-const G returns G::result_type. + * The standard engines, such as std::mt19937_64, meet these requirements. + */ +template +struct is_uniform_random_bit_generator: std::false_type {}; + +template +struct is_uniform_random_bit_generator()()), + std::integral_constant, // fails unless G::min() is a constant expression + std::integral_constant + >::type>: std::integral_constant::value + && !std::is_same::type, bool>::value + && std::is_same()()), typename G::result_type>::value + && std::is_same::value + && std::is_same::value + && (G::min() < G::max()) + > {}; + +/** + * Returns a fair random bit from a uniform random bit generator. + * The bit depends only on the generator output, unlike std::bernoulli_distribution, + * so a given generator state gives the same bits with any standard library. + * The bit tells whether the output is in the upper half of the range, since the high bits + * of some engines are better than the low bits. If the range has an odd number of values, + * the largest value is skipped, so the generator can be invoked more than once. + * With a range of {0, 1}, the bit is the output. + */ +template +bool random_bit_from(G& generator) { + static_assert(is_uniform_random_bit_generator::value, "G must be a uniform random bit generator"); + using U = typename G::result_type; + const U span = static_cast(G::max() - G::min()); // number of values - 1 + const U last = static_cast(span - 1 + span % 2); // largest accepted offset: an even number of values from 0 + for (;;) { + const U offset = static_cast(generator() - G::min()); + if (offset <= last) return offset > last / 2; + } +} + // utility function to hide unused compiler warning // usually has no additional cost template void unused(T&&...) {} diff --git a/common/test/CMakeLists.txt b/common/test/CMakeLists.txt index a4dfb623d..b34c2df3a 100644 --- a/common/test/CMakeLists.txt +++ b/common/test/CMakeLists.txt @@ -74,6 +74,7 @@ target_sources(common_test hash_test.cpp serde_test.cpp inv_pow2_test.cpp + random_bit_test.cpp ) # now the integration test part diff --git a/common/test/random_bit_test.cpp b/common/test/random_bit_test.cpp new file mode 100644 index 000000000..da01393cd --- /dev/null +++ b/common/test/random_bit_test.cpp @@ -0,0 +1,175 @@ +/* + * 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 "common_defs.hpp" + +namespace datasketches { + +// returns the given values in a loop +template +class sequence_generator { +public: + using result_type = UInt; + static constexpr result_type min() { return Min; } + static constexpr result_type max() { return Max; } + + explicit sequence_generator(std::vector values): values_(std::move(values)), calls_(0) {} + result_type operator()() { return values_[calls_++ % values_.size()]; } + size_t calls() const { return calls_; } + +private: + std::vector values_; + size_t calls_; +}; + +struct signed_result { + using result_type = int32_t; + static constexpr result_type min() { return 0; } + static constexpr result_type max() { return 1; } + result_type operator()() { return 0; } +}; + +struct bool_result { + using result_type = bool; + static constexpr result_type min() { return false; } + static constexpr result_type max() { return true; } + result_type operator()() { return false; } +}; + +struct mismatched_result { + using result_type = uint32_t; + static constexpr result_type min() { return 0; } + static constexpr result_type max() { return 1; } + uint64_t operator()() { return 0; } +}; + +struct no_result_type { + static constexpr uint32_t min() { return 0; } + static constexpr uint32_t max() { return 1; } + uint32_t operator()() { return 0; } +}; + +struct runtime_range { + using result_type = uint32_t; + static result_type min() { return 0; } + static result_type max() { return 1; } + result_type operator()() { return 0; } +}; + +struct empty_range { + using result_type = uint32_t; + static constexpr result_type min() { return 1; } + static constexpr result_type max() { return 1; } + result_type operator()() { return 1; } +}; + +using default_random_bit_generator = decltype(random_utils::random_bit); + +static_assert(is_uniform_random_bit_generator::value, ""); +static_assert(is_uniform_random_bit_generator::value, ""); +static_assert(is_uniform_random_bit_generator::value, ""); +static_assert(is_uniform_random_bit_generator::value, ""); +static_assert(is_uniform_random_bit_generator::value, ""); +static_assert(is_uniform_random_bit_generator>::value, ""); + +// integers must not be taken for generators, such as a weight passed to kll_sketch::update() +static_assert(!is_uniform_random_bit_generator::value, ""); +static_assert(!is_uniform_random_bit_generator::value, ""); +static_assert(!is_uniform_random_bit_generator::value, ""); +// the range is needed to derive a fair bit, so callables without it are rejected +static_assert(!is_uniform_random_bit_generator::value, ""); +static_assert(!is_uniform_random_bit_generator>::value, ""); +static_assert(!is_uniform_random_bit_generator::value, ""); +static_assert(!is_uniform_random_bit_generator::value, ""); +static_assert(!is_uniform_random_bit_generator::value, ""); +static_assert(!is_uniform_random_bit_generator::value, ""); +static_assert(!is_uniform_random_bit_generator::value, ""); +static_assert(!is_uniform_random_bit_generator::value, ""); +static_assert(!is_uniform_random_bit_generator::value, "a const generator cannot be invoked"); + +TEST_CASE("is uniform random bit generator: lambda", "[random_bit]") { + auto lambda = [] { return true; }; + static_assert(!is_uniform_random_bit_generator::value, ""); + unused(lambda); +} + +TEST_CASE("random bit from: range {0, 1} gives the output", "[random_bit]") { + sequence_generator generator({0, 1, 1, 0}); + REQUIRE_FALSE(random_bit_from(generator)); + REQUIRE(random_bit_from(generator)); + REQUIRE(random_bit_from(generator)); + REQUIRE_FALSE(random_bit_from(generator)); + REQUIRE(generator.calls() == 4); +} + +TEST_CASE("random bit from: default generator gives its output", "[random_bit]") { + default_random_bit_generator generator(7); + default_random_bit_generator copy(generator); + for (int i = 0; i < 1000; ++i) REQUIRE(random_bit_from(generator) == (copy() == 1)); +} + +TEST_CASE("random bit from: upper half of the range", "[random_bit]") { + sequence_generator small({5, 6, 7, 8}); + REQUIRE_FALSE(random_bit_from(small)); + REQUIRE_FALSE(random_bit_from(small)); + REQUIRE(random_bit_from(small)); + REQUIRE(random_bit_from(small)); + + const uint64_t top_bit = UINT64_C(1) << 63; + sequence_generator full({0, top_bit - 1, top_bit, UINT64_MAX}); + REQUIRE_FALSE(random_bit_from(full)); + REQUIRE_FALSE(random_bit_from(full)); + REQUIRE(random_bit_from(full)); + REQUIRE(random_bit_from(full)); + REQUIRE(full.calls() == 4); +} + +TEST_CASE("random bit from: odd number of values skips the largest", "[random_bit]") { + sequence_generator generator({12, 10, 12, 12, 11}); + REQUIRE_FALSE(random_bit_from(generator)); + REQUIRE(generator.calls() == 2); + REQUIRE(random_bit_from(generator)); + REQUIRE(generator.calls() == 5); +} + +template +static unsigned count_ones(Engine engine, unsigned num_bits) { + unsigned ones = 0; + for (unsigned i = 0; i < num_bits; ++i) ones += random_bit_from(engine) ? 1 : 0; + return ones; +} + +TEST_CASE("random bit from: standard engines are fair", "[random_bit]") { + // the standard deviation of the count is about 158, and the engines are seeded, so the result is fixed + REQUIRE(count_ones(std::mt19937(1), 100000) == Approx(50000).margin(1000)); + REQUIRE(count_ones(std::minstd_rand(1), 100000) == Approx(50000).margin(1000)); + // an odd number of values: 0 to 2^31 - 2 + REQUIRE(count_ones(std::linear_congruential_engine(1), 100000) + == Approx(50000).margin(1000)); +} + +} /* namespace datasketches */ diff --git a/kll/include/kll_helper.hpp b/kll/include/kll_helper.hpp index 3a223d9ab..4ea04da23 100644 --- a/kll/include/kll_helper.hpp +++ b/kll/include/kll_helper.hpp @@ -47,11 +47,11 @@ class kll_helper { static inline uint16_t int_cap_aux_aux(uint16_t k, uint8_t depth); static inline uint64_t sum_the_sample_weights(uint8_t num_levels, const uint32_t* levels); - template - static void randomly_halve_down(T* buf, uint32_t start, uint32_t length); + template + static void randomly_halve_down(T* buf, uint32_t start, uint32_t length, RandomBitGenerator& random_bit_generator); - template - static void randomly_halve_up(T* buf, uint32_t start, uint32_t length); + template + static void randomly_halve_up(T* buf, uint32_t start, uint32_t length, RandomBitGenerator& random_bit_generator); // this version moves objects within the same buffer // assumes that destination has initialized objects @@ -101,9 +101,10 @@ class kll_helper { static inline compress_result predict_compress(uint16_t k, uint8_t m, uint8_t num_levels_in, const uint32_t* in_levels, uint32_t* level_sizes); - template + template static compress_result general_compress(uint16_t k, uint8_t m, uint8_t num_levels_in, T* items, - uint32_t* in_levels, uint32_t* out_levels, bool is_level_zero_sorted, const C& comparator); + uint32_t* in_levels, uint32_t* out_levels, bool is_level_zero_sorted, const C& comparator, + RandomBitGenerator& random_bit_generator); template static void copy_construct(const T* src, size_t src_first, size_t src_last, T* dst, size_t dst_first); diff --git a/kll/include/kll_helper_impl.hpp b/kll/include/kll_helper_impl.hpp index 1325c345a..13699eb01 100644 --- a/kll/include/kll_helper_impl.hpp +++ b/kll/include/kll_helper_impl.hpp @@ -93,14 +93,15 @@ uint64_t kll_helper::sum_the_sample_weights(uint8_t num_levels, const uint32_t* return total; } -template -void kll_helper::randomly_halve_down(T* buf, uint32_t start, uint32_t length) { +template +void kll_helper::randomly_halve_down(T* buf, uint32_t start, uint32_t length, RandomBitGenerator& random_bit_generator) { if (!is_even(length)) { throw std::invalid_argument("length must be even"); } const uint32_t half_length = length / 2; #ifdef KLL_VALIDATION + unused(random_bit_generator); const uint32_t offset = deterministic_offset(); #else - const uint32_t offset = random_utils::random_bit(); + const uint32_t offset = random_bit_from(random_bit_generator) ? 1 : 0; #endif uint32_t j = start + offset; for (uint32_t i = start; i < (start + half_length); i++) { @@ -109,14 +110,15 @@ void kll_helper::randomly_halve_down(T* buf, uint32_t start, uint32_t length) { } } -template -void kll_helper::randomly_halve_up(T* buf, uint32_t start, uint32_t length) { +template +void kll_helper::randomly_halve_up(T* buf, uint32_t start, uint32_t length, RandomBitGenerator& random_bit_generator) { if (!is_even(length)) { throw std::invalid_argument("length must be even"); } const uint32_t half_length = length / 2; #ifdef KLL_VALIDATION + unused(random_bit_generator); const uint32_t offset = deterministic_offset(); #else - const uint32_t offset = random_utils::random_bit(); + const uint32_t offset = random_bit_from(random_bit_generator) ? 1 : 0; #endif uint32_t j = (start + length) - 1 - offset; for (uint32_t i = (start + length) - 1; i >= (start + half_length); i--) { @@ -231,9 +233,10 @@ kll_helper::compress_result kll_helper::predict_compress(uint16_t k, uint8_t m, * sorted afterwards. * Level zero is not required to be sorted before, and may not be sorted afterwards. */ -template +template kll_helper::compress_result kll_helper::general_compress(uint16_t k, uint8_t m, uint8_t num_levels_in, T* items, - uint32_t* in_levels, uint32_t* out_levels, bool is_level_zero_sorted, const C& comparator) + uint32_t* in_levels, uint32_t* out_levels, bool is_level_zero_sorted, const C& comparator, + RandomBitGenerator& random_bit_generator) { if (num_levels_in == 0) { throw std::invalid_argument("num_levels_in == 0"); } // things are too weird if zero levels are allowed const uint32_t starting_item_count = in_levels[num_levels_in] - in_levels[0]; @@ -286,9 +289,9 @@ kll_helper::compress_result kll_helper::general_compress(uint16_t k, uint8_t m, } if (pop_above == 0) { // Level above is empty, so halve up - randomly_halve_up(items, adj_beg, adj_pop); + randomly_halve_up(items, adj_beg, adj_pop, random_bit_generator); } else { // Level above is nonempty, so halve down, then merge up - randomly_halve_down(items, adj_beg, adj_pop); + randomly_halve_down(items, adj_beg, adj_pop, random_bit_generator); merge_sorted_arrays(items, adj_beg, half_adj_pop, raw_lim, pop_above, adj_beg + half_adj_pop, comparator); } diff --git a/kll/include/kll_sketch.hpp b/kll/include/kll_sketch.hpp index d5feb047d..630b1d64f 100644 --- a/kll/include/kll_sketch.hpp +++ b/kll/include/kll_sketch.hpp @@ -21,6 +21,7 @@ #define KLL_SKETCH_HPP_ #include +#include #include #include "common_defs.hpp" @@ -253,6 +254,20 @@ class kll_sketch { template void update(FwdT&& item); + /** + * Updates this sketch with the given data item using caller-owned randomness. + * The generator state is not owned or serialized by the sketch. + * The generator is invoked only when a compaction needs a random bit (see random_bit_from()). + * @param item from a stream of items + * @param random_bit_generator uniform random bit generator, such as std::mt19937_64 + * @throw std::overflow_error if n would exceed kll_constants::MAX_N, in which case the sketch is unchanged + */ + // The last template parameter restricts this overload to uniform random bit generators. Otherwise it would be + // a better match than update(item, weight) for a weight that is an lvalue of an integral type other than uint64_t. + template::value>::type> + void update(FwdT&& item, RandomBitGenerator& random_bit_generator); + /** * Updates this sketch with the given data item repeated the given number of times. * The result is equivalent to calling update(item) weight times. @@ -270,6 +285,21 @@ class kll_sketch { template void update(FwdT&& item, uint64_t weight); + /** + * Updates this sketch with the given data item repeated the given number of times + * using caller-owned randomness. + * The generator state is not owned or serialized by the sketch. + * The generator is invoked only when a compaction needs a random bit (see random_bit_from()). + * @param item from a stream of items + * @param weight number of times the item is repeated, from 1 to kll_constants::MAX_WEIGHT (2^61 - 1) + * @param random_bit_generator uniform random bit generator, such as std::mt19937_64 + * @throw std::invalid_argument if the weight is 0 or greater than kll_constants::MAX_WEIGHT + * @throw std::overflow_error if n would exceed kll_constants::MAX_N, in which case the sketch is unchanged + */ + template::value>::type> + void update(FwdT&& item, uint64_t weight, RandomBitGenerator& random_bit_generator); + /** * Merges another sketch into this one. * If sketches contain strings, callers are responsible for ensuring that @@ -285,6 +315,19 @@ class kll_sketch { template void merge(FwdSk&& other); + /** + * Merges another sketch into this one using caller-owned randomness. + * The generator state is not owned or serialized by the sketch. + * The generator is invoked only when a compaction needs a random bit (see random_bit_from()). + * If other is this sketch, this throws std::invalid_argument. + * @param other sketch to merge into this one + * @param random_bit_generator uniform random bit generator, such as std::mt19937_64 + * @throw std::overflow_error if n would exceed kll_constants::MAX_N, in which case the sketch is unchanged + */ + template::value>::type> + void merge(FwdSk&& other, RandomBitGenerator& random_bit_generator); + /** * Allocates storage for k items now, rather than on the first update or merge, * or as the buffer grows. The buffer then does not need to grow before the first compaction. @@ -641,9 +684,11 @@ class kll_sketch { template void copy_items(const O& other); // &items_[index], or nullptr without item storage, which makes every item range empty inline T* item_ptr(uint32_t index) const; - inline uint32_t internal_update(); + template + inline uint32_t internal_update(RandomBitGenerator& random_bit_generator); // inserts an item into level zero; if constructing it throws, the sketch is unchanged - template void insert_level_zero(FwdT&& item); + template + void insert_level_zero(FwdT&& item, RandomBitGenerator& random_bit_generator); // throws std::overflow_error if n_ + increase would exceed kll_constants::MAX_N inline void check_n_increase(uint64_t increase) const; // destroys the items and frees items_, for a constructor that throws @@ -651,14 +696,16 @@ class kll_sketch { // The following code is only valid in the special case of exactly reaching capacity while updating. // It cannot be used while merging, while reducing k, or anything else. - void compress_while_updating(void); + template + void compress_while_updating(RandomBitGenerator& random_bit_generator); uint8_t find_level_to_compact() const; void add_empty_top_level_to_completely_full_sketch(); void grow_items(uint32_t new_size); // only while there is one level void sort_level_zero(); - template void merge_higher_levels(O&& other, uint64_t final_n); + template + void merge_higher_levels(O&& other, uint64_t final_n, RandomBitGenerator& random_bit_generator); template void populate_work_arrays(FwdSk&& other, T* workbuf, const uint32_t* worklevels, uint8_t provisional_num_levels); diff --git a/kll/include/kll_sketch_impl.hpp b/kll/include/kll_sketch_impl.hpp index 6f08ee45f..83ec4006f 100644 --- a/kll/include/kll_sketch_impl.hpp +++ b/kll/include/kll_sketch_impl.hpp @@ -189,26 +189,32 @@ sorted_view_(nullptr) template template void kll_sketch::update(FwdT&& item) { + update(std::forward(item), random_utils::random_bit); +} + +template +template +void kll_sketch::update(FwdT&& item, RandomBitGenerator& random_bit_generator) { if (!check_update_item(item)) { return; } check_n_increase(1); allocate_items(); // first, so that a failure leaves the sketch unchanged reset_sorted_view(); // before any change, so that a failed copy can't leave a stale view update_min_max(static_cast(item)); // min and max are always copies - insert_level_zero(std::forward(item)); + insert_level_zero(std::forward(item), random_bit_generator); } template -template -void kll_sketch::insert_level_zero(FwdT&& item) { +template +void kll_sketch::insert_level_zero(FwdT&& item, RandomBitGenerator& random_bit_generator) { if (levels_[0] == 0) { // item can refer into items_, and internal_update() can destroy it T copy(std::forward(item)); - const uint32_t index = internal_update(); + const uint32_t index = internal_update(random_bit_generator); new (&items_[index]) T(std::move(copy)); } else { // construct the item before counting it, so that a failed copy leaves the sketch unchanged new (&items_[levels_[0] - 1]) T(std::forward(item)); - internal_update(); + internal_update(random_bit_generator); } } @@ -222,6 +228,12 @@ void kll_sketch::check_n_increase(uint64_t increase) const { template template void kll_sketch::update(FwdT&& item, uint64_t weight) { + update(std::forward(item), weight, random_utils::random_bit); +} + +template +template +void kll_sketch::update(FwdT&& item, uint64_t weight, RandomBitGenerator& random_bit_generator) { if (!check_update_item(item)) { return; } if (weight == 0) throw std::invalid_argument("weight must be at least 1"); if (weight > kll_constants::MAX_WEIGHT) { @@ -229,7 +241,7 @@ void kll_sketch::update(FwdT&& item, uint64_t weight) { } check_n_increase(weight); if (weight == 1) { - update(std::forward(item)); + update(std::forward(item), random_bit_generator); return; } allocate_items(); // first, so that a failure leaves the sketch unchanged @@ -237,10 +249,10 @@ void kll_sketch::update(FwdT&& item, uint64_t weight) { if (weight < levels_[0]) { // fits into level zero without compaction update_min_max(static_cast(item)); // each copy is counted only once it is constructed, so a failed copy leaves a valid sketch - for (uint64_t i = 1; i < weight; ++i) insert_level_zero(static_cast(item)); - insert_level_zero(std::forward(item)); + for (uint64_t i = 1; i < weight; ++i) insert_level_zero(static_cast(item), random_bit_generator); + insert_level_zero(std::forward(item), random_bit_generator); } else { - merge(kll_sketch(k_, static_cast(item), weight, comparator_, allocator_)); + merge(kll_sketch(k_, static_cast(item), weight, comparator_, allocator_), random_bit_generator); } } @@ -332,13 +344,14 @@ T* kll_sketch::item_ptr(uint32_t index) const { } template -uint32_t kll_sketch::internal_update() { +template +uint32_t kll_sketch::internal_update(RandomBitGenerator& random_bit_generator) { allocate_items(); if (levels_[0] == 0) { if (items_size_ < k_) { grow_items(std::min(items_size_ << static_cast(RESIZE_FACTOR), k_)); } else { - compress_while_updating(); + compress_while_updating(random_bit_generator); } } n_++; @@ -349,6 +362,12 @@ uint32_t kll_sketch::internal_update() { template template void kll_sketch::merge(FwdSk&& other) { + merge(std::forward(other), random_utils::random_bit); +} + +template +template +void kll_sketch::merge(FwdSk&& other, RandomBitGenerator& random_bit_generator) { if (this == &other) { throw std::invalid_argument("A sketch cannot merge with itself."); } if (other.is_empty()) { return; } if (m_ != other.m_) { @@ -366,9 +385,9 @@ void kll_sketch::merge(FwdSk&& other) { } const uint64_t final_n = n_ + other.n_; for (uint32_t i = other.levels_[0]; i < other.levels_[1]; i++) { - insert_level_zero(conditional_forward(other.items_[i])); + insert_level_zero(conditional_forward(other.items_[i]), random_bit_generator); } - if (other.num_levels_ >= 2) { merge_higher_levels(std::forward(other), final_n); } + if (other.num_levels_ >= 2) { merge_higher_levels(std::forward(other), final_n, random_bit_generator); } n_ = final_n; if (other.is_estimation_mode()) { min_k_ = std::min(min_k_, other.min_k_); } assert_correct_total_weight(); @@ -804,7 +823,8 @@ sorted_view_(nullptr) // The following code is only valid in the special case of exactly reaching capacity while updating. // It cannot be used while merging, while reducing k, or anything else. template -void kll_sketch::compress_while_updating(void) { +template +void kll_sketch::compress_while_updating(RandomBitGenerator& random_bit_generator) { const uint8_t level = find_level_to_compact(); // It is important to add the new top level right here. Be aware that this operation @@ -831,9 +851,9 @@ void kll_sketch::compress_while_updating(void) { std::sort(items_ + adj_beg, items_ + adj_beg + adj_pop, comparator_); } if (pop_above == 0) { - kll_helper::randomly_halve_up(items_, adj_beg, adj_pop); + kll_helper::randomly_halve_up(items_, adj_beg, adj_pop, random_bit_generator); } else { - kll_helper::randomly_halve_down(items_, adj_beg, adj_pop); + kll_helper::randomly_halve_down(items_, adj_beg, adj_pop, random_bit_generator); kll_helper::merge_sorted_arrays(items_, adj_beg, half_adj_pop, raw_lim, pop_above, adj_beg + half_adj_pop, comparator_); } levels_[level + 1] -= half_adj_pop; // adjust boundaries of the level above @@ -956,8 +976,8 @@ quantiles_sorted_view kll_sketch::get_sorted_view() const { } template -template -void kll_sketch::merge_higher_levels(O&& other, uint64_t final_n) { +template +void kll_sketch::merge_higher_levels(O&& other, uint64_t final_n, RandomBitGenerator& random_bit_generator) { const uint32_t tmp_num_items = get_num_retained() + other.get_num_retained_above_level_zero(); A alloc(allocator_); auto tmp_items_deleter = [tmp_num_items, &alloc](T* ptr) { alloc.deallocate(ptr, tmp_num_items); }; // no destructor needed @@ -990,7 +1010,7 @@ void kll_sketch::merge_higher_levels(O&& other, uint64_t final_n) { populate_work_arrays(std::forward(other), workbuf.get(), worklevels.data(), provisional_num_levels); const kll_helper::compress_result result = kll_helper::general_compress(k_, m_, provisional_num_levels, workbuf.get(), - worklevels.data(), outlevels.data(), is_level_zero_sorted_, comparator_); + worklevels.data(), outlevels.data(), is_level_zero_sorted_, comparator_, random_bit_generator); if (result.final_num_levels != predicted.final_num_levels || result.final_capacity != predicted.final_capacity || result.final_num_items != predicted.final_num_items) { throw std::logic_error("merge error: compression does not match the prediction"); diff --git a/kll/test/kll_sketch_test.cpp b/kll/test/kll_sketch_test.cpp index 196391aa2..cc810d288 100644 --- a/kll/test/kll_sketch_test.cpp +++ b/kll/test/kll_sketch_test.cpp @@ -20,10 +20,12 @@ #include #include #include +#include #include #include #include #include +#include #include #include @@ -47,6 +49,27 @@ using kll_float_sketch = kll_sketch, test_allocator, test_allocator>; +// SplitMix64, a uniform random bit generator over all 64-bit values +class deterministic_random_bit_generator { +public: + using result_type = uint64_t; + static constexpr result_type min() { return 0; } + static constexpr result_type max() { return UINT64_MAX; } + + explicit deterministic_random_bit_generator(uint64_t state): state_(state) {} + + result_type operator()() { + state_ += UINT64_C(0x9e3779b97f4a7c15); + uint64_t value = state_; + value = (value ^ (value >> 30)) * UINT64_C(0xbf58476d1ce4e5b9); + value = (value ^ (value >> 27)) * UINT64_C(0x94d049bb133111eb); + return value ^ (value >> 31); + } + +private: + uint64_t state_; +}; + TEST_CASE("kll sketch", "[kll_sketch]") { // setup @@ -340,6 +363,68 @@ TEST_CASE("kll sketch", "[kll_sketch]") { } } + SECTION("caller-owned randomness") { + auto build = [](uint64_t seed) { + kll_float_sketch sketch(200, std::less(), 0); + deterministic_random_bit_generator random_bit(seed); + for (uint32_t i = 0; i < 10000; ++i) sketch.update(static_cast(i), random_bit); + return sketch.serialize(); + }; + // weighted updates use the generator both when the copies fit into level zero and when they are merged + auto build_weighted = [](uint64_t seed) { + kll_float_sketch sketch(200, std::less(), 0); + deterministic_random_bit_generator random_bit(seed); + for (uint32_t i = 0; i < 2000; ++i) { + const uint64_t weight = (i % 3 == 0) ? 1000 : 7; + sketch.update(static_cast(i), weight, random_bit); + } + return sketch.serialize(); + }; + + REQUIRE(build(1) == build(1)); + REQUIRE(build_weighted(1) == build_weighted(1)); +#ifndef KLL_VALIDATION // validation mode replaces the generator with deterministic offsets + REQUIRE(build(1) != build(2)); + REQUIRE(build_weighted(1) != build_weighted(2)); +#endif + + // a standard engine works directly: a bit is not just whether the 32-bit output is nonzero, which is almost always + auto build_with_engine = [](uint32_t seed) { + kll_float_sketch sketch(200, std::less(), 0); + std::mt19937 engine(seed); + for (uint32_t i = 0; i < 10000; ++i) sketch.update(static_cast(i), engine); + return sketch.serialize(); + }; + REQUIRE(build_with_engine(1) == build_with_engine(1)); +#ifndef KLL_VALIDATION // validation mode replaces the generator with deterministic offsets + REQUIRE(build_with_engine(1) != build_with_engine(2)); +#endif + + // a weight that is an lvalue of an integral type other than uint64_t is a weight, not a generator + kll_float_sketch weighted(200, std::less(), 0); + uint32_t weight = 5; + weighted.update(1.0f, weight); + REQUIRE(weighted.get_n() == 5); + + kll_float_sketch left(200, std::less(), 0); + kll_float_sketch right(200, std::less(), 0); + deterministic_random_bit_generator left_random_bit(3); + deterministic_random_bit_generator right_random_bit(4); + for (uint32_t i = 0; i < 5000; ++i) left.update(static_cast(i), left_random_bit); + for (uint32_t i = 5000; i < 10000; ++i) right.update(static_cast(i), right_random_bit); + + kll_float_sketch first_merge(200, std::less(), 0); + kll_float_sketch second_merge(200, std::less(), 0); + deterministic_random_bit_generator first_merge_random_bit(5); + deterministic_random_bit_generator second_merge_random_bit(5); + first_merge.merge(left, first_merge_random_bit); + first_merge.merge(right, first_merge_random_bit); + second_merge.merge(left, second_merge_random_bit); + second_merge.merge(right, second_merge_random_bit); + REQUIRE(first_merge.serialize() == second_merge.serialize()); + REQUIRE_THROWS_WITH(first_merge.merge(first_merge, first_merge_random_bit), "A sketch cannot merge with itself."); + } + SECTION("stream serialize deserialize empty") { kll_float_sketch sketch(200, std::less(), 0); const long long empty_bytes = test_allocator_total_bytes; From 2ff376233cd523e8542bd8c666c2a0c10b2d0f20 Mon Sep 17 00:00:00 2001 From: Christoph Viebig Date: Tue, 10 Nov 2026 17:04:52 +0000 Subject: [PATCH 2/3] Run the KLL reference validation through the random bit generator API Replace the KLL_VALIDATION compile-time switch and the global kll_next_offset with a test generator that alternates 0, 1, 0, ... and is passed to update(). This removes the conditional code from kll_helper, so the validation tests build in every configuration. Because this test code is now built by default, compute the sample hash with unsigned arithmetic: the signed multiplication overflowed, which UBSan reports and CI's sanitizer jobs treat as fatal. The hash values are unchanged. Also fix the [validaiton] tag typo, so "[validation]" selects every validation test. The 114 reference cases are tagged hidden, so they do not add to default test runs or CI time. Run them with: kll_test "[validation]" --- kll/include/kll_helper.hpp | 10 ------- kll/include/kll_helper_impl.hpp | 18 ------------ kll/test/kll_sketch_test.cpp | 4 --- kll/test/kll_sketch_validation.cpp | 47 +++++++++++++++++++----------- 4 files changed, 30 insertions(+), 49 deletions(-) diff --git a/kll/include/kll_helper.hpp b/kll/include/kll_helper.hpp index 4ea04da23..66bde0d05 100644 --- a/kll/include/kll_helper.hpp +++ b/kll/include/kll_helper.hpp @@ -24,10 +24,6 @@ namespace datasketches { -#ifdef KLL_VALIDATION -extern uint32_t kll_next_offset; -#endif - // 0 <= power <= 30 static const uint64_t powers_of_three[] = {1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467, @@ -112,12 +108,6 @@ class kll_helper { template static void move_construct(T* src, size_t src_first, size_t src_last, T* dst, size_t dst_first, bool destroy); -#ifdef KLL_VALIDATION - private: - - static inline uint32_t deterministic_offset(); -#endif - }; } /* namespace datasketches */ diff --git a/kll/include/kll_helper_impl.hpp b/kll/include/kll_helper_impl.hpp index 13699eb01..12072d5d0 100644 --- a/kll/include/kll_helper_impl.hpp +++ b/kll/include/kll_helper_impl.hpp @@ -97,12 +97,7 @@ template void kll_helper::randomly_halve_down(T* buf, uint32_t start, uint32_t length, RandomBitGenerator& random_bit_generator) { if (!is_even(length)) { throw std::invalid_argument("length must be even"); } const uint32_t half_length = length / 2; -#ifdef KLL_VALIDATION - unused(random_bit_generator); - const uint32_t offset = deterministic_offset(); -#else const uint32_t offset = random_bit_from(random_bit_generator) ? 1 : 0; -#endif uint32_t j = start + offset; for (uint32_t i = start; i < (start + half_length); i++) { if (i != j) buf[i] = std::move(buf[j]); @@ -114,12 +109,7 @@ template void kll_helper::randomly_halve_up(T* buf, uint32_t start, uint32_t length, RandomBitGenerator& random_bit_generator) { if (!is_even(length)) { throw std::invalid_argument("length must be even"); } const uint32_t half_length = length / 2; -#ifdef KLL_VALIDATION - unused(random_bit_generator); - const uint32_t offset = deterministic_offset(); -#else const uint32_t offset = random_bit_from(random_bit_generator) ? 1 : 0; -#endif uint32_t j = (start + length) - 1 - offset; for (uint32_t i = (start + length) - 1; i >= (start + half_length); i--) { if (i != j) buf[i] = std::move(buf[j]); @@ -343,14 +333,6 @@ void kll_helper::move_construct(T* src, size_t src_first, size_t src_last, T* ds } } -#ifdef KLL_VALIDATION -uint32_t kll_helper::deterministic_offset() { - const uint32_t result(kll_next_offset); - kll_next_offset = 1 - kll_next_offset; - return result; -} -#endif - } /* namespace datasketches */ #endif // KLL_HELPER_IMPL_HPP_ diff --git a/kll/test/kll_sketch_test.cpp b/kll/test/kll_sketch_test.cpp index cc810d288..0a1835830 100644 --- a/kll/test/kll_sketch_test.cpp +++ b/kll/test/kll_sketch_test.cpp @@ -383,10 +383,8 @@ TEST_CASE("kll sketch", "[kll_sketch]") { REQUIRE(build(1) == build(1)); REQUIRE(build_weighted(1) == build_weighted(1)); -#ifndef KLL_VALIDATION // validation mode replaces the generator with deterministic offsets REQUIRE(build(1) != build(2)); REQUIRE(build_weighted(1) != build_weighted(2)); -#endif // a standard engine works directly: a bit is not just whether the 32-bit output is nonzero, which is almost always auto build_with_engine = [](uint32_t seed) { @@ -396,9 +394,7 @@ TEST_CASE("kll sketch", "[kll_sketch]") { return sketch.serialize(); }; REQUIRE(build_with_engine(1) == build_with_engine(1)); -#ifndef KLL_VALIDATION // validation mode replaces the generator with deterministic offsets REQUIRE(build_with_engine(1) != build_with_engine(2)); -#endif // a weight that is an lvalue of an integral type other than uint64_t is a weight, not a generator kll_float_sketch weighted(200, std::less(), 0); diff --git a/kll/test/kll_sketch_validation.cpp b/kll/test/kll_sketch_validation.cpp index 2dbf60df6..8b7e52d61 100644 --- a/kll/test/kll_sketch_validation.cpp +++ b/kll/test/kll_sketch_validation.cpp @@ -22,15 +22,27 @@ #include #include -#ifdef KLL_VALIDATION - // This is to make sure the implementation matches exactly the reference implementation in OCaml. -// Conditional compilation is used because the implementation needs -// to switch from random choice to deterministic +// The expected results were produced with compaction offsets alternating 0, 1, 0, ... +// starting from 0 for each sketch, so the sketch is updated with a generator that reproduces that sequence. namespace datasketches { -uint32_t kll_next_offset; // to make kll_sketch deterministic +class alternating_bit_generator { +public: + using result_type = uint32_t; + static constexpr result_type min() { return 0; } + static constexpr result_type max() { return 1; } + + result_type operator()() { + const result_type result = next_; + next_ ^= 1; + return result; + } + +private: + result_type next_ = 0; +}; constexpr unsigned num_tests = 114; @@ -166,22 +178,25 @@ static std::vector make_input_array(unsigned n, unsigned stride) { template std::pair hash_samples_and_count_levels(It from, It to) { - int64_t multiplier = 738219921; // an arbitrary odd 30-bit number - int64_t mask60 = (1ULL << 60) - 1ULL; - int64_t accum = 0; + // unsigned arithmetic wraps around instead of overflowing; the result is the same bit pattern + const uint64_t multiplier = 738219921; // an arbitrary odd 30-bit number + const uint64_t mask60 = (1ULL << 60) - 1ULL; + uint64_t accum = 0; uint8_t num_levels = 1; for (auto it = from; it != to; ++it) { - accum += static_cast((*it).first); + accum += static_cast(static_cast((*it).first)); accum *= multiplier; accum &= mask60; accum ^= accum >> 30; const uint8_t level = count_trailing_zeros_in_u64((*it).second); if (num_levels <= level) num_levels = level + 1; } - return std::pair(accum, num_levels); + return std::pair(static_cast(accum), num_levels); // accum < 2^60 } -TEST_CASE("kll validation", "[kll_sketch][validation]") { +// Hidden by default because the 114 cases add up to about 91 million updates. +// Run with: kll_test "[validation]" +TEST_CASE("kll validation", "[kll_sketch][.validation]") { for (unsigned i = 0; i < num_tests; i++) { if (correct_results[7 * i] != i) throw std::logic_error("test number mismatch"); unsigned k = correct_results[7 * i + 1]; @@ -189,9 +204,9 @@ TEST_CASE("kll validation", "[kll_sketch][validation]") { unsigned stride = correct_results[7 * i + 3]; auto input_array = make_input_array(n, stride); kll_sketch sketch(k); - kll_next_offset = 0; + alternating_bit_generator random_bit; for (unsigned j = 0; j < n; j++) { - sketch.update(input_array[j]); + sketch.update(input_array[j], random_bit); } unsigned num_samples = sketch.get_num_retained(); auto p = hash_samples_and_count_levels(sketch.begin(), sketch.end()); @@ -208,7 +223,7 @@ TEST_CASE("kll validation", "[kll_sketch][validation]") { } } -TEST_CASE("kll validation: test hash and num levels", "[kll_sketch][validaiton]") { +TEST_CASE("kll validation: test hash and num levels", "[kll_sketch][validation]") { std::pair array[] = { std::make_pair(907500, 1), std::make_pair(944104, 1), @@ -223,7 +238,7 @@ TEST_CASE("kll validation: test hash and num levels", "[kll_sketch][validaiton]" REQUIRE(hash_and_num_levels.second == 3); } -TEST_CASE("kll validation: make input array", "[kll_sketch][validaiton]") { +TEST_CASE("kll validation: make input array", "[kll_sketch][validation]") { int expected_array[6] = { 3654721, 7309442, 2575555, 6230276, 1496389, 5151110 }; auto array(make_input_array(6, 3654721)); REQUIRE(array[0] == expected_array[0]); @@ -235,5 +250,3 @@ TEST_CASE("kll validation: make input array", "[kll_sketch][validaiton]") { } } /* namespace datasketches */ - -#endif From e11b275b969e44545c81348c8a6b7d6f275f04e5 Mon Sep 17 00:00:00 2001 From: Christoph Viebig Date: Tue, 10 Nov 2026 17:08:19 +0000 Subject: [PATCH 3/3] Run the short KLL reference validation cases by default Run the 67 reference cases with n <= 100000 (about 1% of the updates) in default test runs and keep the 47 long-stream cases hidden. kll_test "[validation]" still runs every case once. Report case details through Catch2 INFO instead of printing a line per case. --- kll/test/kll_sketch_validation.cpp | 32 ++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/kll/test/kll_sketch_validation.cpp b/kll/test/kll_sketch_validation.cpp index 8b7e52d61..cef206a24 100644 --- a/kll/test/kll_sketch_validation.cpp +++ b/kll/test/kll_sketch_validation.cpp @@ -18,6 +18,7 @@ */ #include +#include #include #include @@ -194,14 +195,14 @@ std::pair hash_samples_and_count_levels(It from, It to) { return std::pair(static_cast(accum), num_levels); // accum < 2^60 } -// Hidden by default because the 114 cases add up to about 91 million updates. -// Run with: kll_test "[validation]" -TEST_CASE("kll validation", "[kll_sketch][.validation]") { +// Checks the reference cases whose stream length n is in [min_n, max_n]. +static void check_reference_cases(unsigned min_n, unsigned max_n) { for (unsigned i = 0; i < num_tests; i++) { if (correct_results[7 * i] != i) throw std::logic_error("test number mismatch"); unsigned k = correct_results[7 * i + 1]; unsigned n = correct_results[7 * i + 2]; unsigned stride = correct_results[7 * i + 3]; + if (n < min_n || n > max_n) continue; auto input_array = make_input_array(n, stride); kll_sketch sketch(k); alternating_bit_generator random_bit; @@ -210,19 +211,28 @@ TEST_CASE("kll validation", "[kll_sketch][.validation]") { } unsigned num_samples = sketch.get_num_retained(); auto p = hash_samples_and_count_levels(sketch.begin(), sketch.end()); - std::cout << i; + INFO("reference case " << i << ", n = " << n); REQUIRE(correct_results[7 * i + 4] == p.second); REQUIRE(correct_results[7 * i + 5] == num_samples); - if (correct_results[7 * i + 6] == p.first) { - std::cout << " pass" << std::endl; - } else { - std::cout << " " << (correct_results[7 * i + 6]) << " != " << p.first << "\n"; - std::cout << sketch.to_string(); - FAIL(); - } + INFO(sketch.to_string()); + REQUIRE(correct_results[7 * i + 6] == p.first); } } +// Streams up to this length run by default: 67 of the 114 cases, about 1% of the updates. +constexpr unsigned max_default_n = 100000; + +TEST_CASE("kll validation: short streams", "[kll_sketch][validation]") { + check_reference_cases(0, max_default_n); +} + +// Hidden by default because these 47 cases add up to about 90 million updates. +// Run all reference cases with: kll_test "[validation]" +// To run them by default as well, remove the '.' from the tag. +TEST_CASE("kll validation: long streams", "[kll_sketch][.validation]") { + check_reference_cases(max_default_n + 1, std::numeric_limits::max()); +} + TEST_CASE("kll validation: test hash and num levels", "[kll_sketch][validation]") { std::pair array[] = { std::make_pair(907500, 1),