From f2fb1a8c8fb4e1e2505cd09bb9a68708e9fc8816 Mon Sep 17 00:00:00 2001 From: Tom Tan Date: Fri, 31 Jul 2026 12:52:01 -0700 Subject: [PATCH 1/5] [SDK] Downscale base2 exponential histogram buckets in place Scale reduction on the base2 exponential histogram allocated a replacement AdaptingCircularBufferCounter on every downscale, copied the surviving buckets into it and threw the old one away. On the record path a single out-of-window value can trigger several reductions in a row, so the allocation sat directly in the hot path. The code carried a TODO(euroelessar) to do this in place. AdaptingCircularBufferCounter::Downscale() now folds the buckets inside the existing backing array. The populated range can wrap around that array, so the fold runs in two passes over the physical slots: the buckets at or above the base index are walked ascending (folding never moves one of them to a higher slot) and the buckets below it are walked descending (folding never moves one of them to a lower slot). In both directions the destination slot has already been consumed, or is the source slot itself, so no live count is ever overwritten. The fold itself is the fused AdaptingIntegerArray::Fold(from, to) primitive rather than Get + Increment + zero. Each of those is a nostd::visit, and the dispatch, not the allocation, turned out to dominate: dropping from three visits per bucket to one is where most of the win comes from. Fold widens the array and retries exactly like Increment does, leaving the source cell untouched until the retry so a merged count that overflows the current cell width cannot be lost. DownscaleBuckets() becomes a one-line delegation and the TODO is gone. The integer-width optimisation is preserved for free now that the array is reused. sdk/test/metrics/circular_buffer_counter_benchmark.cc, MSVC Release, wall time per fold of a full wrapped buffer: window | before | after | delta -------+---------+---------+-------- 20 | 780 ns | 441 ns | -43.5% 160 | 5218 ns | 3495 ns | -33.0% 640 |20153 ns |13940 ns | -30.8% Tests: the old allocate-and-copy fold is kept in circular_buffer_counter_test.cc as a reference oracle and compared against the in-place version over 2000 randomized buffers covering every wrap state, buffer size and cell width, plus hand-checked cases for the wrapped, across-zero, full-buffer, widening and collapse-to-one-bucket paths. Both loop directions were mutation tested: reversing either one fails the suite. aggregation_test.cc adds record-path cases that re-derive the expected bucket placement with a fresh Base2ExponentialHistogramIndexer at the final scale, as an independent check that repeated in-place downscales agree with a single indexing pass. Fixes #3366 --- CHANGELOG.md | 3 + .../sdk/metrics/data/circular_buffer.h | 33 ++ ...base2_exponential_histogram_aggregation.cc | 24 +- sdk/src/metrics/data/circular_buffer.cc | 104 +++++- sdk/test/metrics/aggregation_test.cc | 114 ++++++ .../circular_buffer_counter_benchmark.cc | 33 ++ .../metrics/circular_buffer_counter_test.cc | 344 ++++++++++++++++++ 7 files changed, 631 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c5a4bd62ed..e90f6511a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,9 @@ Increment the: ## [Unreleased] +* [SDK] Downscale base2 exponential histogram buckets in place + [#3366](https://github.com/open-telemetry/opentelemetry-cpp/issues/3366) + * [BENCHMARK] Add multi-threaded base2 exponential histogram benchmarks [#4319](https://github.com/open-telemetry/opentelemetry-cpp/pull/4319) diff --git a/sdk/include/opentelemetry/sdk/metrics/data/circular_buffer.h b/sdk/include/opentelemetry/sdk/metrics/data/circular_buffer.h index 38cea2839a..c39e93caee 100644 --- a/sdk/include/opentelemetry/sdk/metrics/data/circular_buffer.h +++ b/sdk/include/opentelemetry/sdk/metrics/data/circular_buffer.h @@ -66,6 +66,19 @@ class AdaptingIntegerArray */ void Clear(); + /** + * Adds the value at index `from` to the value at index `to` and resets the + * value at index `from` to zero. + * + * Equivalent to Increment(to, Get(from)) followed by zeroing `from`, but it + * dispatches on the cell width once instead of three times. Does nothing when + * the two indices are equal or when the source value is zero. + * + * @param from The index of the value to move. + * @param to The index of the value to move it into. + */ + void Fold(size_t from, size_t to); + private: void EnlargeToFit(uint64_t value); @@ -143,8 +156,28 @@ class AdaptingCircularBufferCounter */ uint64_t Get(int32_t index) const; + /** + * Folds every populated bucket into the bucket at `index >> by`, in place. + * + * This is the counter side of an exponential histogram scale reduction. The + * backing array is reused, so no allocation happens unless a merged bucket + * count no longer fits the current cell width. + * + * Does nothing when the counter is empty or when `by` is zero. Values greater + * than 31 are treated as 31 because every int32_t index has already collapsed + * to either -1 or 0 at that point. + * + * @param by The number of scales to reduce by. + */ + void Downscale(uint32_t by); + private: size_t ToBufferIndex(int32_t index) const; + size_t ToBufferIndex(int32_t index, int32_t base_index) const; + + // Moves the count at `index` into the bucket it folds into, expressed against + // the post-downscale base index. Only valid as a step of Downscale(). + void FoldBucket(int32_t index, int32_t new_base_index, uint32_t shift); static constexpr int32_t kNullIndex = (std::numeric_limits::min)(); diff --git a/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc b/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc index 4803a4674f..f5477fdcb7 100644 --- a/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc +++ b/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc @@ -89,27 +89,9 @@ void DiffBuckets(const AdaptingCircularBufferCounter &left, void DownscaleBuckets(std::unique_ptr &buckets, uint32_t by) noexcept { - if (buckets->Empty()) - { - return; - } - - // We want to preserve other optimisations here as well, e.g. integer size. - // Instead of creating a new counter, we copy the existing one (for bucket size - // optimisations), and clear the values before writing the new ones. - // TODO(euroelessar): Do downscaling in-place. - auto new_buckets = std::make_unique(buckets->MaxSize()); - new_buckets->Clear(); - - for (auto i = buckets->StartIndex(); i <= buckets->EndIndex(); ++i) - { - const uint64_t count = buckets->Get(i); - if (count > 0) - { - new_buckets->Increment(i >> by, count); - } - } - buckets = std::move(new_buckets); + // Downscaling is done in place, which preserves the existing bucket size + // optimisation (integer width) and avoids allocating a replacement buffer. + buckets->Downscale(by); } } // namespace diff --git a/sdk/src/metrics/data/circular_buffer.cc b/sdk/src/metrics/data/circular_buffer.cc index 7d33610587..d7ef8e96c9 100644 --- a/sdk/src/metrics/data/circular_buffer.cc +++ b/sdk/src/metrics/data/circular_buffer.cc @@ -68,6 +68,32 @@ struct AdaptingIntegerArrayClear } }; +struct AdaptingIntegerArrayFold +{ + size_t from; + size_t to; + + template + uint64_t operator()(std::vector &backing) + { + const uint64_t count = backing[from]; + if (count == 0) + { + return 0; + } + + const uint64_t result = backing[to] + count; + if OPENTELEMETRY_LIKELY_CONDITION (result <= uint64_t(std::numeric_limits::max())) + { + backing[to] = static_cast(result); + backing[from] = static_cast(0); + return 0; + } + // Leaves the source untouched so the retry after widening sees it again. + return result; + } +}; + struct AdaptingIntegerArrayCopy { template @@ -112,6 +138,26 @@ void AdaptingIntegerArray::Clear() nostd::visit(AdaptingIntegerArrayClear{}, backing_); } +void AdaptingIntegerArray::Fold(size_t from, size_t to) +{ + if (from == to) + { + return; + } + + /* May or may not fit */ + const uint64_t result = nostd::visit(AdaptingIntegerArrayFold{from, to}, backing_); + if OPENTELEMETRY_LIKELY_CONDITION (result == 0) + { + return; + } + EnlargeToFit(result); + /* Must fit, buffer was enlarged for the value to store */ + OPENTELEMETRY_MAYBE_UNUSED const uint64_t result2 = + nostd::visit(AdaptingIntegerArrayFold{from, to}, backing_); + assert(result2 == 0); +} + void AdaptingIntegerArray::EnlargeToFit(uint64_t value) { const size_t backing_size = Size(); @@ -182,15 +228,67 @@ uint64_t AdaptingCircularBufferCounter::Get(int32_t index) const return backing_.Get(ToBufferIndex(index)); } +void AdaptingCircularBufferCounter::Downscale(uint32_t by) +{ + if (by == 0 || Empty()) + { + return; + } + + // Right shifting a negative index floors towards minus infinity on every + // supported compiler, which is exactly the mapping the caller applies to the + // indices it computes for the reduced scale. + constexpr uint32_t kMaxShift = static_cast(std::numeric_limits::digits); + const uint32_t shift = by > kMaxShift ? kMaxShift : by; + const int32_t new_base_index = base_index_ >> shift; + + // Buckets [base_index_, end_index_] sit at the front of the backing array in + // ascending slot order. Folding never moves one of them to a higher slot, so + // walking up means every destination slot has already been consumed. + for (int64_t index = base_index_; index <= end_index_; ++index) + { + FoldBucket(static_cast(index), new_base_index, shift); + } + + // Buckets [start_index_, base_index_) sit at the tail of the backing array, + // again in ascending slot order. Folding never moves one of them to a lower + // slot, so this half is walked down instead. Any of them that folds into the + // new base index lands in the front half, which is already fully consumed. + for (int64_t index = static_cast(base_index_) - 1; index >= start_index_; --index) + { + FoldBucket(static_cast(index), new_base_index, shift); + } + + start_index_ = start_index_ >> shift; + end_index_ = end_index_ >> shift; + base_index_ = new_base_index; +} + +void AdaptingCircularBufferCounter::FoldBucket(int32_t index, + int32_t new_base_index, + uint32_t shift) +{ + // The destination is expressed against the post-downscale base index, which + // cannot be installed yet because the remaining slots still hold buckets of + // the current scale. Downscale() guarantees that destination slot has already + // been read, or is the source slot itself. + backing_.Fold(ToBufferIndex(index), ToBufferIndex(index >> shift, new_base_index)); +} + size_t AdaptingCircularBufferCounter::ToBufferIndex(int32_t index) const +{ + return ToBufferIndex(index, base_index_); +} + +size_t AdaptingCircularBufferCounter::ToBufferIndex(int32_t index, int32_t base_index) const { // Figure out the index relative to the start of the circular buffer. - if (index < base_index_) + if (index < base_index) { // If index is before the base one, wrap around. - return static_cast(index + backing_.Size() - base_index_); + return static_cast(index + backing_.Size() - base_index); } - return static_cast(index - base_index_); + return static_cast(index - base_index); } } // namespace metrics diff --git a/sdk/test/metrics/aggregation_test.cc b/sdk/test/metrics/aggregation_test.cc index 8cd8a1a4ec..086b78bca8 100644 --- a/sdk/test/metrics/aggregation_test.cc +++ b/sdk/test/metrics/aggregation_test.cc @@ -15,6 +15,7 @@ #include "opentelemetry/sdk/metrics/aggregation/aggregation.h" #include "opentelemetry/sdk/metrics/aggregation/aggregation_config.h" #include "opentelemetry/sdk/metrics/aggregation/base2_exponential_histogram_aggregation.h" +#include "opentelemetry/sdk/metrics/aggregation/base2_exponential_histogram_indexer.h" #include "opentelemetry/sdk/metrics/aggregation/default_aggregation.h" #include "opentelemetry/sdk/metrics/aggregation/histogram_aggregation.h" #include "opentelemetry/sdk/metrics/aggregation/lastvalue_aggregation.h" @@ -99,6 +100,37 @@ constexpr double kSampleBStart = 0.1; constexpr double kSampleBFactor = 1.5; constexpr int kSampleBCount = 30; +// Independent oracle for bucket placement: recompute where each recorded value belongs directly at +// the scale the aggregation settled on. A sequence of in-place downscales has to agree with a +// single indexing pass at the final scale. +void ExpectBucketsMatchIndexer(const std::vector &recorded, + const AdaptingCircularBufferCounter &buckets, + int32_t scale, + double sign, + nostd::string_view label = "") +{ + SCOPED_TRACE(label); + if (buckets.Empty()) + { + return; + } + + const Base2ExponentialHistogramIndexer indexer(scale); + for (int32_t bucket = buckets.StartIndex(); bucket <= buckets.EndIndex(); ++bucket) + { + uint64_t expected = 0; + for (double value : recorded) + { + const double magnitude = value * sign; + if (magnitude > 0 && indexer.ComputeIndex(magnitude) == bucket) + { + ++expected; + } + } + EXPECT_EQ(buckets.Get(bucket), expected) << "bucket " << bucket; + } +} + } // namespace TEST(Aggregation, LongSumAggregation) @@ -1003,3 +1035,85 @@ TEST(Aggregation, Base2ExponentialHistogramAggregationDefaultConfigDiff) ExpectCountInvariant(pb.count_, diffed, "DefaultConfigDiff"); EXPECT_EQ(SumAllBuckets(diffed), SumAllBuckets(merged) - SumAllBuckets(pa)); } + +TEST(Aggregation, Base2ExponentialHistogramAggregationRecordPathDownscaleWrapsBuckets) +{ + // Scale 0 keeps the index arithmetic readable: 2^N lands in bucket N-1. + const auto config = MakeAggregationConfig(0, 4); + Base2ExponentialHistogramAggregation aggr(&config); + + // The first recording fixes the base index of the bucket array, so recording + // below it and then above it leaves the populated range wrapped around that + // array when the scale reduction folds it in place. + aggr.Aggregate(4.0, {}); // bucket 1, becomes the base index + aggr.Aggregate(8.0, {}); // bucket 2 + aggr.Aggregate(1.0, {}); // bucket -1, wraps to the tail of the array + aggr.Aggregate(16.0, {}); // bucket 3 no longer fits and forces a downscale + + const auto point = MakePointData(aggr); + ExpectCountInvariant(4u, point, "RecordPathDownscaleWrapsBuckets"); + EXPECT_EQ(point.scale_, -1); + ASSERT_FALSE(point.positive_buckets_->Empty()); + EXPECT_TRUE(point.negative_buckets_->Empty()); + EXPECT_EQ(point.positive_buckets_->StartIndex(), -1); + EXPECT_EQ(point.positive_buckets_->EndIndex(), 1); + EXPECT_EQ(point.positive_buckets_->Get(-1), 1u); // 1.0 + EXPECT_EQ(point.positive_buckets_->Get(0), 1u); // 4.0 + EXPECT_EQ(point.positive_buckets_->Get(1), 2u); // 8.0 and 16.0 +} + +TEST(Aggregation, Base2ExponentialHistogramAggregationRecordPathDownscaleWrapsNegativeBuckets) +{ + const auto config = MakeAggregationConfig(0, 4); + Base2ExponentialHistogramAggregation aggr(&config); + + // Mirror of the positive case. The empty positive buckets are downscaled too, + // which must stay a no-op. + aggr.Aggregate(-4.0, {}); + aggr.Aggregate(-8.0, {}); + aggr.Aggregate(-1.0, {}); + aggr.Aggregate(-16.0, {}); + + const auto point = MakePointData(aggr); + ExpectCountInvariant(4u, point, "RecordPathDownscaleWrapsNegativeBuckets"); + EXPECT_EQ(point.scale_, -1); + ASSERT_FALSE(point.negative_buckets_->Empty()); + EXPECT_TRUE(point.positive_buckets_->Empty()); + EXPECT_EQ(point.negative_buckets_->StartIndex(), -1); + EXPECT_EQ(point.negative_buckets_->EndIndex(), 1); + EXPECT_EQ(point.negative_buckets_->Get(-1), 1u); + EXPECT_EQ(point.negative_buckets_->Get(0), 1u); + EXPECT_EQ(point.negative_buckets_->Get(1), 2u); +} + +TEST(Aggregation, Base2ExponentialHistogramAggregationRecordPathRepeatedDownscale) +{ + const auto config = MakeAggregationConfig(4, 8); + Base2ExponentialHistogramAggregation aggr(&config); + + // Interleaving both signs over several orders of magnitude drives many scale + // reductions on both bucket arrays. + std::vector recorded; + double value = 1.0; + for (int i = 0; i < 40; ++i) + { + aggr.Aggregate(value, {}); + aggr.Aggregate(-value, {}); + recorded.push_back(value); + recorded.push_back(-value); + value *= 1.6; + } + + const auto point = MakePointData(aggr); + ExpectCountInvariant(recorded.size(), point, "RecordPathRepeatedDownscale"); + ASSERT_LT(point.scale_, 4); + ASSERT_FALSE(point.positive_buckets_->Empty()); + ASSERT_FALSE(point.negative_buckets_->Empty()); + EXPECT_LE(point.positive_buckets_->EndIndex() - point.positive_buckets_->StartIndex() + 1, + static_cast(config.max_size_)); + EXPECT_LE(point.negative_buckets_->EndIndex() - point.negative_buckets_->StartIndex() + 1, + static_cast(config.max_size_)); + + ExpectBucketsMatchIndexer(recorded, *point.positive_buckets_, point.scale_, 1.0, "positive"); + ExpectBucketsMatchIndexer(recorded, *point.negative_buckets_, point.scale_, -1.0, "negative"); +} diff --git a/sdk/test/metrics/circular_buffer_counter_benchmark.cc b/sdk/test/metrics/circular_buffer_counter_benchmark.cc index 37f2ebbcef..114a025c5d 100644 --- a/sdk/test/metrics/circular_buffer_counter_benchmark.cc +++ b/sdk/test/metrics/circular_buffer_counter_benchmark.cc @@ -109,5 +109,38 @@ BENCHMARK(BM_AdaptingCircularBufferCounterGetWrapped) ->Arg(kDefaultWindow) ->Arg(kLargeWindow); +// Folds a full, wrapped buffer in half. This is the operation the base2 +// exponential histogram runs whenever a recording falls outside the current +// window, and it is the one that used to allocate a replacement buffer per +// call. +// +// Downscaling is destructive, so an iteration cannot start from the previous +// result. The buffer is restored by copy-assigning a pristine one, which for +// equally sized buffers of the same cell width is a copy of the counts with no +// allocation, rather than by replaying the recordings. +void BM_AdaptingCircularBufferCounterDownscale(benchmark::State &state) +{ + const int32_t window = static_cast(state.range(0)); + AdaptingCircularBufferCounter filled(static_cast(window)); + filled.Increment(0, 1); + for (int32_t index = -1; index > -window; --index) + { + filled.Increment(index, 1); + } + + AdaptingCircularBufferCounter counter(static_cast(window)); + for (auto _ : state) + { + counter = filled; + counter.Downscale(1); + benchmark::DoNotOptimize(counter); + } + state.SetItemsProcessed(state.iterations() * window); +} +BENCHMARK(BM_AdaptingCircularBufferCounterDownscale) + ->Arg(kSmallWindow) + ->Arg(kDefaultWindow) + ->Arg(kLargeWindow); + } // namespace BENCHMARK_MAIN(); diff --git a/sdk/test/metrics/circular_buffer_counter_test.cc b/sdk/test/metrics/circular_buffer_counter_test.cc index b79289563d..260522f5a0 100644 --- a/sdk/test/metrics/circular_buffer_counter_test.cc +++ b/sdk/test/metrics/circular_buffer_counter_test.cc @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 #include +#include #include #include #include @@ -13,6 +14,62 @@ using namespace opentelemetry::sdk::metrics; namespace { +// The allocate-and-copy fold that AdaptingCircularBufferCounter::Downscale() +// replaced. Kept here as an oracle: it is obviously correct because it never +// writes into the buffer it reads from. +AdaptingCircularBufferCounter ReferenceDownscale(const AdaptingCircularBufferCounter &counter, + uint32_t by) +{ + AdaptingCircularBufferCounter folded{counter.MaxSize()}; + if (counter.Empty()) + { + return folded; + } + + for (int32_t index = counter.StartIndex(); index <= counter.EndIndex(); ++index) + { + const uint64_t count = counter.Get(index); + if (count > 0) + { + EXPECT_TRUE(folded.Increment(index >> by, count)); + } + } + return folded; +} + +void ExpectSameBuckets(const AdaptingCircularBufferCounter &expected, + const AdaptingCircularBufferCounter &actual) +{ + ASSERT_EQ(expected.Empty(), actual.Empty()); + EXPECT_EQ(expected.MaxSize(), actual.MaxSize()); + if (expected.Empty()) + { + return; + } + + ASSERT_EQ(expected.StartIndex(), actual.StartIndex()); + ASSERT_EQ(expected.EndIndex(), actual.EndIndex()); + for (int32_t index = expected.StartIndex(); index <= expected.EndIndex(); ++index) + { + EXPECT_EQ(expected.Get(index), actual.Get(index)) << "bucket " << index; + } +} + +uint64_t TotalCount(const AdaptingCircularBufferCounter &counter) +{ + if (counter.Empty()) + { + return 0; + } + + uint64_t total = 0; + for (int32_t index = counter.StartIndex(); index <= counter.EndIndex(); ++index) + { + total += counter.Get(index); + } + return total; +} + class AdaptingIntegerArrayTest : public testing::TestWithParam {}; @@ -69,6 +126,50 @@ TEST_P(AdaptingIntegerArrayTest, Clear) EXPECT_EQ(counter.Get(0), 1); } +TEST_P(AdaptingIntegerArrayTest, Fold) +{ + AdaptingIntegerArray counter(10); + counter.Increment(3, GetParam()); + counter.Increment(4, GetParam()); + counter.Increment(5, 1); + + counter.Fold(3, 4); + EXPECT_EQ(counter.Get(3), 0); + EXPECT_EQ(counter.Get(4), 2 * GetParam()); + // Unrelated cells and the array size are left alone. + EXPECT_EQ(counter.Get(5), 1); + EXPECT_EQ(counter.Size(), 10); + + // Folding an empty cell, and folding a cell into itself, are both no-ops. + counter.Fold(3, 5); + counter.Fold(4, 4); + EXPECT_EQ(counter.Get(4), 2 * GetParam()); + EXPECT_EQ(counter.Get(5), 1); + + // The widened cells stay usable. + counter.Increment(3, GetParam()); + EXPECT_EQ(counter.Get(3), GetParam()); +} + +TEST(AdaptingIntegerArrayWidthTest, FoldWidensCellsWhenTheMergedValueDoesNotFit) +{ + // One case per cell width boundary: the merged value overflows the current + // width, so Fold has to enlarge the array and retry. + const uint64_t sources[] = {200, 40000, 3000000000ull}; + for (uint64_t source : sources) + { + AdaptingIntegerArray counter(4); + counter.Increment(1, source); + counter.Increment(2, source); + + counter.Fold(1, 2); + + EXPECT_EQ(counter.Get(1), 0); + EXPECT_EQ(counter.Get(2), 2 * source); + EXPECT_EQ(counter.Size(), 4); + } +} + TEST(AdaptingCircularBufferCounterTest, ReturnsZeroOutsidePopulatedRange) { AdaptingCircularBufferCounter counter{10}; @@ -153,4 +254,247 @@ TEST(AdaptingCircularBufferCounterTest, Clear) EXPECT_TRUE(counter.Empty()); } +TEST(AdaptingCircularBufferCounterTest, DownscaleIsANoOpWhenEmptyOrByZero) +{ + AdaptingCircularBufferCounter empty{10}; + empty.Downscale(3); + EXPECT_TRUE(empty.Empty()); + + AdaptingCircularBufferCounter counter{10}; + EXPECT_TRUE(counter.Increment(3, 5)); + EXPECT_TRUE(counter.Increment(9, 7)); + counter.Downscale(0); + EXPECT_EQ(counter.StartIndex(), 3); + EXPECT_EQ(counter.EndIndex(), 9); + EXPECT_EQ(counter.Get(3), 5); + EXPECT_EQ(counter.Get(9), 7); +} + +TEST(AdaptingCircularBufferCounterTest, DownscaleWithoutWraparound) +{ + AdaptingCircularBufferCounter counter{10}; + EXPECT_TRUE(counter.Increment(4, 1)); + EXPECT_TRUE(counter.Increment(5, 2)); + EXPECT_TRUE(counter.Increment(6, 3)); + EXPECT_TRUE(counter.Increment(7, 4)); + + counter.Downscale(1); + + EXPECT_EQ(counter.StartIndex(), 2); + EXPECT_EQ(counter.EndIndex(), 3); + EXPECT_EQ(counter.Get(2), 3); + EXPECT_EQ(counter.Get(3), 7); + EXPECT_EQ(counter.MaxSize(), 10); + EXPECT_EQ(TotalCount(counter), 10); +} + +TEST(AdaptingCircularBufferCounterTest, DownscaleWithWraparound) +{ + AdaptingCircularBufferCounter counter{8}; + // The first recording fixes the base index, so 2..4 land at the tail of the + // backing array while 5..6 stay at its front. + EXPECT_TRUE(counter.Increment(5, 1)); + EXPECT_TRUE(counter.Increment(6, 2)); + EXPECT_TRUE(counter.Increment(2, 4)); + EXPECT_TRUE(counter.Increment(3, 8)); + EXPECT_TRUE(counter.Increment(4, 16)); + + counter.Downscale(1); + + EXPECT_EQ(counter.StartIndex(), 1); + EXPECT_EQ(counter.EndIndex(), 3); + EXPECT_EQ(counter.Get(1), 12); // 2 and 3 + EXPECT_EQ(counter.Get(2), 17); // 4 and 5 + EXPECT_EQ(counter.Get(3), 2); // 6 + EXPECT_EQ(TotalCount(counter), 31); +} + +TEST(AdaptingCircularBufferCounterTest, DownscaleAcrossZero) +{ + AdaptingCircularBufferCounter counter{10}; + EXPECT_TRUE(counter.Increment(1, 1)); + EXPECT_TRUE(counter.Increment(-1, 2)); + EXPECT_TRUE(counter.Increment(-2, 4)); + EXPECT_TRUE(counter.Increment(0, 8)); + EXPECT_TRUE(counter.Increment(2, 16)); + + counter.Downscale(1); + + // Right shifting a negative index rounds towards minus infinity, so -2 and -1 + // both fold into -1. + EXPECT_EQ(counter.StartIndex(), -1); + EXPECT_EQ(counter.EndIndex(), 1); + EXPECT_EQ(counter.Get(-1), 6); + EXPECT_EQ(counter.Get(0), 9); + EXPECT_EQ(counter.Get(1), 16); + EXPECT_EQ(TotalCount(counter), 31); +} + +TEST(AdaptingCircularBufferCounterTest, DownscaleAtMinimumIndex) +{ + constexpr int32_t kMinIndex = (std::numeric_limits::min)(); + AdaptingCircularBufferCounter counter{2}; + EXPECT_TRUE(counter.Increment(kMinIndex + 1, 1)); + EXPECT_TRUE(counter.Increment(kMinIndex, 1)); + + counter.Downscale(1); + + EXPECT_EQ(counter.StartIndex(), kMinIndex >> 1); + EXPECT_EQ(counter.EndIndex(), kMinIndex >> 1); + EXPECT_EQ(counter.Get(kMinIndex >> 1), 2); +} + +TEST(AdaptingCircularBufferCounterTest, DownscaleAtMaximumIndex) +{ + constexpr int32_t kMaxIndex = (std::numeric_limits::max)(); + AdaptingCircularBufferCounter counter{2}; + EXPECT_TRUE(counter.Increment(kMaxIndex - 1, 1)); + EXPECT_TRUE(counter.Increment(kMaxIndex, 1)); + + counter.Downscale(1); + + EXPECT_EQ(counter.StartIndex(), kMaxIndex >> 1); + EXPECT_EQ(counter.EndIndex(), kMaxIndex >> 1); + EXPECT_EQ(counter.Get(kMaxIndex >> 1), 2); +} + +TEST(AdaptingCircularBufferCounterTest, DownscaleFullBuffer) +{ + constexpr int32_t kSize = 16; + AdaptingCircularBufferCounter counter{kSize}; + // Seed in the middle so the populated range spans the whole backing array and + // wraps around it. + EXPECT_TRUE(counter.Increment(8, 9)); + for (int32_t index = 0; index < kSize; ++index) + { + if (index != 8) + { + EXPECT_TRUE(counter.Increment(index, static_cast(index) + 1)); + } + } + ASSERT_EQ(counter.StartIndex(), 0); + ASSERT_EQ(counter.EndIndex(), kSize - 1); + + const AdaptingCircularBufferCounter expected = ReferenceDownscale(counter, 2); + counter.Downscale(2); + + ExpectSameBuckets(expected, counter); + EXPECT_EQ(counter.StartIndex(), 0); + EXPECT_EQ(counter.EndIndex(), 3); + EXPECT_EQ(counter.Get(0), 10); + EXPECT_EQ(counter.Get(1), 26); + EXPECT_EQ(counter.Get(2), 42); + EXPECT_EQ(counter.Get(3), 58); + EXPECT_EQ(TotalCount(counter), 136); +} + +TEST(AdaptingCircularBufferCounterTest, DownscaleWidensCellsWhenBucketsMerge) +{ + const uint64_t deltas[] = {200, std::numeric_limits::max() + 1ull, + std::numeric_limits::max() + 1ull, + std::numeric_limits::max() + 1ull}; + for (uint64_t delta : deltas) + { + AdaptingCircularBufferCounter counter{4}; + EXPECT_TRUE(counter.Increment(0, delta)); + EXPECT_TRUE(counter.Increment(1, delta)); + + counter.Downscale(1); + + EXPECT_EQ(counter.StartIndex(), 0); + EXPECT_EQ(counter.EndIndex(), 0); + EXPECT_EQ(counter.Get(0), 2 * delta); + EXPECT_EQ(counter.MaxSize(), 4); + } +} + +TEST(AdaptingCircularBufferCounterTest, DownscaleCollapsesToASingleBucket) +{ + AdaptingCircularBufferCounter counter{10}; + EXPECT_TRUE(counter.Increment(4, 1)); + EXPECT_TRUE(counter.Increment(-4, 2)); + EXPECT_TRUE(counter.Increment(0, 3)); + + counter.Downscale(31); + + EXPECT_EQ(counter.StartIndex(), -1); + EXPECT_EQ(counter.EndIndex(), 0); + EXPECT_EQ(counter.Get(-1), 2); + EXPECT_EQ(counter.Get(0), 4); + + // The counter stays usable afterwards. + EXPECT_TRUE(counter.Increment(0, 5)); + EXPECT_EQ(counter.Get(0), 9); + EXPECT_EQ(TotalCount(counter), 11); +} + +TEST(AdaptingCircularBufferCounterTest, DownscaleSaturatesShiftAtIndexWidth) +{ + AdaptingCircularBufferCounter counter{2}; + EXPECT_TRUE(counter.Increment(0, 1)); + EXPECT_TRUE(counter.Increment(1, 1)); + + counter.Downscale(32); + + EXPECT_EQ(counter.StartIndex(), 0); + EXPECT_EQ(counter.EndIndex(), 0); + EXPECT_EQ(counter.Get(0), 2); +} + +TEST(AdaptingCircularBufferCounterTest, DownscaleSaturatesArbitrarilyLargeShift) +{ + AdaptingCircularBufferCounter counter{4}; + EXPECT_TRUE(counter.Increment(1, 1)); + EXPECT_TRUE(counter.Increment(-1, 2)); + EXPECT_TRUE(counter.Increment(0, 4)); + + counter.Downscale((std::numeric_limits::max)()); + + EXPECT_EQ(counter.StartIndex(), -1); + EXPECT_EQ(counter.EndIndex(), 0); + EXPECT_EQ(counter.Get(-1), 2); + EXPECT_EQ(counter.Get(0), 5); +} + +TEST(AdaptingCircularBufferCounterTest, DownscaleMatchesReferenceImplementation) +{ + // A plain linear congruential generator keeps the case set reproducible + // without pulling in . + uint32_t state = 0x9e3779b9u; + auto next = [&state](uint32_t bound) { + state = (state * 1664525u) + 1013904223u; + return (state >> 8) % bound; + }; + + const uint64_t magnitudes[] = {1, 250, 65000, 4000000000ull}; + + for (uint32_t trial = 0; trial < 2000; ++trial) + { + const size_t max_size = 2 + next(30); + const int32_t base = static_cast(next(41)) - 20; + + AdaptingCircularBufferCounter counter{max_size}; + // The first recording fixes the base index and therefore how the populated + // range wraps around the backing array. + EXPECT_TRUE(counter.Increment(base, magnitudes[next(4)] + next(97))); + for (size_t i = 0; i < 4 * max_size; ++i) + { + const int32_t index = base + static_cast(next(2 * static_cast(max_size))) - + static_cast(max_size); + // Out-of-range recordings are rejected, which is part of what is exercised. + counter.Increment(index, magnitudes[next(4)] + next(97)); + } + + const uint32_t by = 1 + next(4); + const AdaptingCircularBufferCounter expected = ReferenceDownscale(counter, by); + const uint64_t total = TotalCount(counter); + + counter.Downscale(by); + + ExpectSameBuckets(expected, counter); + EXPECT_EQ(TotalCount(counter), total) + << "trial " << trial << " max_size " << max_size << " by " << by; + } +} + } // namespace From e552fe26bd51871dd8cc2aba2fbeda66f05d78cb Mon Sep 17 00:00:00 2001 From: Tom Tan Date: Fri, 31 Jul 2026 14:42:55 -0700 Subject: [PATCH 2/5] Update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e90f6511a1..ba8124dfa4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,7 @@ Increment the: ## [Unreleased] * [SDK] Downscale base2 exponential histogram buckets in place - [#3366](https://github.com/open-telemetry/opentelemetry-cpp/issues/3366) + [#4324](https://github.com/open-telemetry/opentelemetry-cpp/pull/4324) * [BENCHMARK] Add multi-threaded base2 exponential histogram benchmarks [#4319](https://github.com/open-telemetry/opentelemetry-cpp/pull/4319) From a8f6b8a67390e5803e9b60ffff63d176e5834965 Mon Sep 17 00:00:00 2001 From: Tom Tan Date: Fri, 31 Jul 2026 17:41:45 -0700 Subject: [PATCH 3/5] Avoid overflow in circular buffer range checks --- sdk/src/metrics/data/circular_buffer.cc | 6 ++++-- sdk/test/metrics/circular_buffer_counter_test.cc | 10 ++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/sdk/src/metrics/data/circular_buffer.cc b/sdk/src/metrics/data/circular_buffer.cc index d7ef8e96c9..2b8e2ccf89 100644 --- a/sdk/src/metrics/data/circular_buffer.cc +++ b/sdk/src/metrics/data/circular_buffer.cc @@ -200,7 +200,8 @@ bool AdaptingCircularBufferCounter::Increment(int32_t index, uint64_t delta) if (index > end_index_) { // Move end, check max size. - if (index + 1 > static_cast(backing_.Size()) + start_index_) + if (static_cast(index) - start_index_ + 1 > + static_cast(backing_.Size())) { return false; } @@ -209,7 +210,8 @@ bool AdaptingCircularBufferCounter::Increment(int32_t index, uint64_t delta) else if (index < start_index_) { // Move end, check max size. - if (end_index_ + 1 > static_cast(backing_.Size()) + index) + if (static_cast(end_index_) - index + 1 > + static_cast(backing_.Size())) { return false; } diff --git a/sdk/test/metrics/circular_buffer_counter_test.cc b/sdk/test/metrics/circular_buffer_counter_test.cc index 260522f5a0..077e0171c0 100644 --- a/sdk/test/metrics/circular_buffer_counter_test.cc +++ b/sdk/test/metrics/circular_buffer_counter_test.cc @@ -356,6 +356,16 @@ TEST(AdaptingCircularBufferCounterTest, DownscaleAtMaximumIndex) EXPECT_EQ(counter.StartIndex(), kMaxIndex >> 1); EXPECT_EQ(counter.EndIndex(), kMaxIndex >> 1); EXPECT_EQ(counter.Get(kMaxIndex >> 1), 2); + + AdaptingCircularBufferCounter reverse_order{2}; + EXPECT_TRUE(reverse_order.Increment(kMaxIndex, 1)); + EXPECT_TRUE(reverse_order.Increment(kMaxIndex - 1, 1)); + + reverse_order.Downscale(1); + + EXPECT_EQ(reverse_order.StartIndex(), kMaxIndex >> 1); + EXPECT_EQ(reverse_order.EndIndex(), kMaxIndex >> 1); + EXPECT_EQ(reverse_order.Get(kMaxIndex >> 1), 2); } TEST(AdaptingCircularBufferCounterTest, DownscaleFullBuffer) From 245e491bff1a9ddaf5073eefd1f0620deaca7292 Mon Sep 17 00:00:00 2001 From: Tom Tan Date: Fri, 31 Jul 2026 18:27:22 -0700 Subject: [PATCH 4/5] Fix format --- sdk/src/metrics/data/circular_buffer.cc | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/sdk/src/metrics/data/circular_buffer.cc b/sdk/src/metrics/data/circular_buffer.cc index 2b8e2ccf89..d32752f257 100644 --- a/sdk/src/metrics/data/circular_buffer.cc +++ b/sdk/src/metrics/data/circular_buffer.cc @@ -200,8 +200,7 @@ bool AdaptingCircularBufferCounter::Increment(int32_t index, uint64_t delta) if (index > end_index_) { // Move end, check max size. - if (static_cast(index) - start_index_ + 1 > - static_cast(backing_.Size())) + if (static_cast(index) - start_index_ + 1 > static_cast(backing_.Size())) { return false; } @@ -210,8 +209,7 @@ bool AdaptingCircularBufferCounter::Increment(int32_t index, uint64_t delta) else if (index < start_index_) { // Move end, check max size. - if (static_cast(end_index_) - index + 1 > - static_cast(backing_.Size())) + if (static_cast(end_index_) - index + 1 > static_cast(backing_.Size())) { return false; } From 0c051054fb92a78b5c7c55b77c4339724cb9f33d Mon Sep 17 00:00:00 2001 From: Tom Tan Date: Mon, 3 Aug 2026 10:19:14 -0700 Subject: [PATCH 5/5] Address feedback --- sdk/test/metrics/circular_buffer_counter_test.cc | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sdk/test/metrics/circular_buffer_counter_test.cc b/sdk/test/metrics/circular_buffer_counter_test.cc index 077e0171c0..16fa3a73d0 100644 --- a/sdk/test/metrics/circular_buffer_counter_test.cc +++ b/sdk/test/metrics/circular_buffer_counter_test.cc @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 #include -#include +#include #include #include #include @@ -480,14 +480,14 @@ TEST(AdaptingCircularBufferCounterTest, DownscaleMatchesReferenceImplementation) for (uint32_t trial = 0; trial < 2000; ++trial) { - const size_t max_size = 2 + next(30); - const int32_t base = static_cast(next(41)) - 20; + const std::size_t max_size = 2 + next(30); + const int32_t base = static_cast(next(41)) - 20; AdaptingCircularBufferCounter counter{max_size}; // The first recording fixes the base index and therefore how the populated // range wraps around the backing array. EXPECT_TRUE(counter.Increment(base, magnitudes[next(4)] + next(97))); - for (size_t i = 0; i < 4 * max_size; ++i) + for (std::size_t i = 0; i < 4 * max_size; ++i) { const int32_t index = base + static_cast(next(2 * static_cast(max_size))) - static_cast(max_size);