From 9642f9f528d124c05bf10c670f4e9fc2742bd3cc Mon Sep 17 00:00:00 2001 From: 0z5a Date: Sun, 15 Nov 2026 14:11:57 +0100 Subject: [PATCH] fix: ebpps_sketch::merge() keeps the larger maximum weight internal_merge() computed new_wt_max and used it for every rho step but never stored it, so after merging a sketch that held the heaviest item the target kept its old wt_max. Later updates then used a stale maximum, which breaks proportional sampling, and serialize() wrote the stale value. Store new_wt_max with the final cumulative weight and n, and add a test that compares C against a single sketch for all four merge paths. --- sampling/include/ebpps_sketch_impl.hpp | 1 + sampling/test/ebpps_sketch_test.cpp | 38 ++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/sampling/include/ebpps_sketch_impl.hpp b/sampling/include/ebpps_sketch_impl.hpp index 36a7b926d..9a7b23e3f 100644 --- a/sampling/include/ebpps_sketch_impl.hpp +++ b/sampling/include/ebpps_sketch_impl.hpp @@ -269,6 +269,7 @@ void ebpps_sketch::internal_merge(O&& sk) { // avoid numeric issues by setting cumulative weight to the // pre-computed value cumulative_wt_ = final_cum_wt; + wt_max_ = new_wt_max; n_ = new_n; } diff --git a/sampling/test/ebpps_sketch_test.cpp b/sampling/test/ebpps_sketch_test.cpp index 25c1a237d..5ee728135 100644 --- a/sampling/test/ebpps_sketch_test.cpp +++ b/sampling/test/ebpps_sketch_test.cpp @@ -263,4 +263,42 @@ TEST_CASE("ebpps sketch: merge small into large", "[ebpps_sketch]") { REQUIRE(sk1.get_cumulative_weight() == Approx(1.7 * k).margin(EPS)); } +TEST_CASE("ebpps sketch: merge keeps the max weight", "[ebpps_sketch]") { + const uint32_t k = 10; + const uint64_t n = 1000; + const double heavy_wt = 500.0; + + // reference: a single sketch fed every item, where the heavy item limits rho to 1 / heavy_wt + ebpps_sketch ref = create_unweighted_sketch(k, n); + ref.update(-1, heavy_wt); + ref.update(static_cast(n), 1.0); + REQUIRE(ref.get_c() == Approx((n + 1 + heavy_wt) / heavy_wt).margin(EPS)); + + ebpps_sketch heavy(k); + heavy.update(-1, heavy_wt); + + // heavy item in the sketch being merged in, lvalue and rvalue + ebpps_sketch sk1 = create_unweighted_sketch(k, n); + sk1.merge(heavy); + sk1.update(static_cast(n), 1.0); + REQUIRE(sk1.get_c() == Approx(ref.get_c()).margin(EPS)); + + ebpps_sketch sk2 = create_unweighted_sketch(k, n); + sk2.merge(ebpps_sketch(heavy)); + sk2.update(static_cast(n), 1.0); + REQUIRE(sk2.get_c() == Approx(ref.get_c()).margin(EPS)); + + // heavy item in the target sketch, which has the smaller cumulative weight, lvalue and rvalue + ebpps_sketch light = create_unweighted_sketch(k, n); + ebpps_sketch sk3(heavy); + sk3.merge(light); + sk3.update(static_cast(n), 1.0); + REQUIRE(sk3.get_c() == Approx(ref.get_c()).margin(EPS)); + + ebpps_sketch sk4(heavy); + sk4.merge(std::move(light)); + sk4.update(static_cast(n), 1.0); + REQUIRE(sk4.get_c() == Approx(ref.get_c()).margin(EPS)); +} + } \ No newline at end of file