diff --git a/fi/include/reverse_purge_hash_map_impl.hpp b/fi/include/reverse_purge_hash_map_impl.hpp index 73fb803e..5492914e 100644 --- a/fi/include/reverse_purge_hash_map_impl.hpp +++ b/fi/include/reverse_purge_hash_map_impl.hpp @@ -350,7 +350,8 @@ void reverse_purge_hash_map::resize(uint8_t lg_new_size) { template V reverse_purge_hash_map::purge() { - const uint32_t limit = std::min(MAX_SAMPLE_SIZE, num_active_); + // Sample at most the capacity, as datasketches-java does, so the median matches. + const uint32_t limit = std::min(std::min(MAX_SAMPLE_SIZE, get_capacity()), num_active_); uint32_t num_samples = 0; uint32_t i = 0; // A temporary of at most MAX_SAMPLE_SIZE values: on the stack rather than from the allocator, which need not be diff --git a/fi/test/frequent_items_sketch_test.cpp b/fi/test/frequent_items_sketch_test.cpp index b2035439..93c6adc2 100644 --- a/fi/test/frequent_items_sketch_test.cpp +++ b/fi/test/frequent_items_sketch_test.cpp @@ -179,6 +179,44 @@ TEST_CASE("frequent items: purge clearing all counters serialized form", "[frequ REQUIRE(sketch2.get_maximum_error() == 1); } +namespace { +// Same as Java's Long.hashCode for values in [0, 2^31), so slots match Java. +struct identity_hash { + size_t operator()(int64_t v) const { return static_cast(v); } +}; +} + +TEST_CASE("frequent items: purge median samples at most the capacity, as java", "[frequent_items_sketch]") { + // Java takes the median of 6 counters (the capacity). Taking 7 gives max error 30. + frequent_items_sketch sketch(3); + sketch.update(1, 10); + sketch.update(2, 1); + sketch.update(3, 20); + sketch.update(4, 30); + sketch.update(5, 40); + sketch.update(6, 50); + sketch.update(7, 60); + REQUIRE(sketch.get_maximum_error() == 40); + REQUIRE(sketch.get_num_active_items() == 2); + auto items = sketch.get_frequent_items(frequent_items_error_type::NO_FALSE_NEGATIVES, 0); + REQUIRE(items.size() == 2); + REQUIRE(items[0].get_item() == 7); + REQUIRE(items[0].get_estimate() == 60); + REQUIRE(items[1].get_item() == 6); + REQUIRE(items[1].get_estimate() == 50); +} + +TEST_CASE("frequent items: purge at 2048 slots matches java", "[frequent_items_sketch]") { + // Capacity 1536 is above 1024, so the median still samples 1024 counts. + frequent_items_sketch sketch(11); + for (int64_t i = 1; i <= 1600; ++i) sketch.update(i, i % 5 + 1); + REQUIRE(sketch.get_maximum_error() == 3); + REQUIRE(sketch.get_num_active_items() == 677); + REQUIRE(sketch.get_total_weight() == 4800); + REQUIRE(sketch.get_estimate(3) == 4); + REQUIRE(sketch.get_estimate(1600) == 4); +} + TEST_CASE("frequent items: reset", "[frequent_items_sketch]") { frequent_items_sketch sketch(8); for (uint64_t i = 0; i < 1000; ++i) sketch.update(i % 300, i % 7 + 1);