From 826a90840affe9c05f7d7996e31993f1988a80f1 Mon Sep 17 00:00:00 2001 From: Tom Tan Date: Mon, 3 Aug 2026 18:54:56 -0700 Subject: [PATCH 01/11] [METRICS SDK] Enforce a runtime minimum scale for Base2ExponentialHistogramAggregation --- CHANGELOG.md | 15 ++ .../metrics/aggregation/aggregation_config.h | 10 + .../base2_exponential_histogram_aggregation.h | 7 +- ...base2_exponential_histogram_aggregation.cc | 203 +++++++++++------- .../base2_exponential_histogram_indexer.cc | 7 +- sdk/test/metrics/aggregation_test.cc | 175 +++++++++++++++ 6 files changed, 341 insertions(+), 76 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ef17a78bf..fee3a9f88c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,21 @@ Increment the: ## [Unreleased] +* [METRICS SDK] Enforce a runtime minimum scale for + `Base2ExponentialHistogramAggregation`. Automatic downscaling now stops at + `kMinRuntimeScale` (-10, the declarative-configuration minimum for + `max_scale`) instead of driving `scale_` below the range the configuration + validator accepts. Every scale mutation on the record, merge and diff paths + goes through one clamped helper, so bucket indices and `scale_` always move by + the same amount. Bucket buffers are allocated with at least three slots + (`kMinBucketsAtFloor`) because every finite double maps to an index in + `[-2, 0]` at the floor; this only widens the degenerate `max_size == 2` + configuration, whose reported `max_buckets_` stays the configured value, and + guarantees no recording is dropped once the floor is reached. The indexer now + saturates its right shift so an out-of-range scale supplied through the + point-data constructors cannot trigger undefined behaviour. + [#4325](https://github.com/open-telemetry/opentelemetry-cpp/issues/4325) + * [METRICS SDK] Fix Windows metrics tail latency on the synchronous record path: `SyncMetricStorage::attribute_hashmap_lock_` now uses `std::mutex` instead of `common::SpinLockMutex`. The spin lock's final `sleep_for(1ms)` back-off is diff --git a/sdk/include/opentelemetry/sdk/metrics/aggregation/aggregation_config.h b/sdk/include/opentelemetry/sdk/metrics/aggregation/aggregation_config.h index 8c80715846..165a1a579b 100644 --- a/sdk/include/opentelemetry/sdk/metrics/aggregation/aggregation_config.h +++ b/sdk/include/opentelemetry/sdk/metrics/aggregation/aggregation_config.h @@ -72,6 +72,16 @@ constexpr std::int32_t kMaxScaleMin = -10; constexpr std::int32_t kMaxScaleMax = 20; constexpr std::size_t kMaxSizeMin = 2; +// Lower bound for the scale chosen at runtime by automatic downscaling. The specification only +// requires a "reasonable minimum", so this SDK aligns the runtime floor with the declarative +// configuration minimum for max_scale. +constexpr std::int32_t kMinRuntimeScale = kMaxScaleMin; + +// Bucket slots needed to keep every finite double representable at kMinRuntimeScale, where all +// values map to an index in [-2, 0]. Bucket buffers are never allocated smaller than this, so a +// histogram pinned at the floor never has to drop a recording. +constexpr std::size_t kMinBucketsAtFloor = 3; + class Base2ExponentialHistogramAggregationConfig : public AggregationConfig { public: diff --git a/sdk/include/opentelemetry/sdk/metrics/aggregation/base2_exponential_histogram_aggregation.h b/sdk/include/opentelemetry/sdk/metrics/aggregation/base2_exponential_histogram_aggregation.h index 9e927b56a6..6171f35556 100644 --- a/sdk/include/opentelemetry/sdk/metrics/aggregation/base2_exponential_histogram_aggregation.h +++ b/sdk/include/opentelemetry/sdk/metrics/aggregation/base2_exponential_histogram_aggregation.h @@ -47,12 +47,17 @@ class Base2ExponentialHistogramAggregation : public Aggregation private: void AggregateIntoBuckets(std::unique_ptr &buckets, double value) noexcept; - void Downscale(uint32_t by) noexcept; + + /* Reduces the scale by up to `by`, stopping at kMinRuntimeScale. Returns the reduction that was + * actually applied, which callers must use to shift bucket indices. */ + uint32_t Downscale(uint32_t by) noexcept; mutable opentelemetry::common::SpinLockMutex lock_; Base2ExponentialHistogramPointData point_data_; Base2ExponentialHistogramIndexer indexer_; bool record_min_max_ = true; + // Keeps the scale floor warning off the record hot path after the first occurrence. + bool floor_warning_emitted_ = false; }; } // namespace metrics diff --git a/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc b/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc index f5477fdcb7..c99da533c5 100644 --- a/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc +++ b/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc @@ -35,7 +35,10 @@ namespace uint32_t GetScaleReduction(int32_t start_index, int32_t end_index, size_t max_buckets) noexcept { uint32_t scale_reduction = 0; - while (static_cast(end_index) - start_index + 1 > static_cast(max_buckets)) + // Both indices have collapsed to -1 or 0 after 31 shifts, so further iterations cannot narrow + // the span; the bound keeps a degenerate max_buckets from spinning forever. + while (scale_reduction < 31 && + static_cast(end_index) - start_index + 1 > static_cast(max_buckets)) { start_index >>= 1; end_index >>= 1; @@ -94,6 +97,74 @@ void DownscaleBuckets(std::unique_ptr &buckets, u buckets->Downscale(by); } +// Bucket buffers are never narrower than kMinBucketsAtFloor so that the whole double range stays +// representable once the scale is pinned at kMinRuntimeScale. This only widens the degenerate +// max_size_ == 2 configuration, and the extra slot is only reachable at the floor. +size_t BucketCapacity(size_t max_buckets) noexcept +{ + return (std::max)(max_buckets, kMinBucketsAtFloor); +} + +// Truncates `requested` to the reduction that can be applied without pushing `current_scale` below +// kMinRuntimeScale. Returns 0 once the floor is reached. +uint32_t ClampScaleReduction(int32_t current_scale, uint32_t requested) noexcept +{ + const int64_t headroom = static_cast(current_scale) - kMinRuntimeScale; + if (headroom <= 0) + { + return 0; + } + return static_cast((std::min)(static_cast(requested), headroom)); +} + +// Single entry point for scale reduction: clamps to the runtime floor, folds both bucket arrays by +// the clamped amount and moves scale_ by exactly that amount. Returns the reduction applied. +uint32_t ApplyDownscale(Base2ExponentialHistogramPointData &point_data, uint32_t requested) noexcept +{ + const uint32_t applied = ClampScaleReduction(point_data.scale_, requested); + if (applied == 0) + { + return 0; + } + + if (point_data.positive_buckets_) + { + DownscaleBuckets(point_data.positive_buckets_, applied); + } + if (point_data.negative_buckets_) + { + DownscaleBuckets(point_data.negative_buckets_, applied); + } + point_data.scale_ -= static_cast(applied); + return applied; +} + +// Folds `high_res` onto `target_scale`. The bucket shift has to match the scale delta exactly, so +// the runtime floor is deliberately not applied here: it bounds the reductions the SDK chooses, +// not the alignment of an operand that already sits lower. +void AlignToScale(Base2ExponentialHistogramPointData &high_res, int32_t target_scale) noexcept +{ + if (high_res.scale_ <= target_scale) + { + return; + } + + // AdaptingCircularBufferCounter::Downscale() saturates at 31, which is idempotent for int32_t + // indices, so a larger delta needs no special handling. + const int64_t delta = static_cast(high_res.scale_) - target_scale; + const uint32_t by = delta > 31 ? 31u : static_cast(delta); + + if (high_res.positive_buckets_) + { + DownscaleBuckets(high_res.positive_buckets_, by); + } + if (high_res.negative_buckets_) + { + DownscaleBuckets(high_res.negative_buckets_, by); + } + high_res.scale_ = target_scale; +} + } // namespace Base2ExponentialHistogramAggregation::Base2ExponentialHistogramAggregation( @@ -132,9 +203,9 @@ Base2ExponentialHistogramAggregation::Base2ExponentialHistogramAggregation( // Initialize buckets point_data_.positive_buckets_ = - std::make_unique(point_data_.max_buckets_); + std::make_unique(BucketCapacity(point_data_.max_buckets_)); point_data_.negative_buckets_ = - std::make_unique(point_data_.max_buckets_); + std::make_unique(BucketCapacity(point_data_.max_buckets_)); indexer_ = Base2ExponentialHistogramIndexer(point_data_.scale_); } @@ -221,45 +292,66 @@ void Base2ExponentialHistogramAggregation::AggregateIntoBuckets( { if (!buckets) { - buckets = std::make_unique(point_data_.max_buckets_); + buckets = + std::make_unique(BucketCapacity(point_data_.max_buckets_)); } if (buckets->MaxSize() == 0) { - buckets = std::make_unique(point_data_.max_buckets_); + buckets = + std::make_unique(BucketCapacity(point_data_.max_buckets_)); } const int32_t index = indexer_.ComputeIndex(value); - if (!buckets->Increment(index, 1)) + + // The backing buffer can be wider than the configured budget (see BucketCapacity), so the + // reduction is derived from max_buckets_ instead of relying on Increment() to fail. + uint32_t scale_reduction = 0; + if (!buckets->Empty()) { - const int32_t start_index = (std::min)(buckets->StartIndex(), index); - const int32_t end_index = (std::max)(buckets->EndIndex(), index); - const uint32_t scale_reduction = - GetScaleReduction(start_index, end_index, point_data_.max_buckets_); - Downscale(scale_reduction); + scale_reduction = + GetScaleReduction((std::min)(buckets->StartIndex(), index), + (std::max)(buckets->EndIndex(), index), point_data_.max_buckets_); + } - buckets->Increment(index >> scale_reduction, 1); + // Downscale() may stop short of the request at the floor, so shift the index by what was + // actually applied. + const uint32_t applied = Downscale(scale_reduction); + if (!buckets->Increment(index >> applied, 1)) + { + OTEL_INTERNAL_LOG_ERROR( + "[Base2ExponentialHistogramAggregation::AggregateIntoBuckets] bucket index " + << (index >> applied) << " out of range at scale " << point_data_.scale_ + << "; recording dropped from the buckets. SDK invariant violation"); + assert(false && "AggregateIntoBuckets: bucket index out of range"); } } -void Base2ExponentialHistogramAggregation::Downscale(uint32_t by) noexcept +uint32_t Base2ExponentialHistogramAggregation::Downscale(uint32_t by) noexcept { if (by == 0) { - return; + return 0; } - if (point_data_.positive_buckets_) + const uint32_t applied = ApplyDownscale(point_data_, by); + + if (applied < by && !floor_warning_emitted_) { - DownscaleBuckets(point_data_.positive_buckets_, by); + floor_warning_emitted_ = true; + OTEL_INTERNAL_LOG_WARN("[Base2ExponentialHistogramAggregation] scale " + << point_data_.scale_ << " reached the runtime minimum " + << kMinRuntimeScale + << "; recorded values now share buckets instead of downscaling further"); } - if (point_data_.negative_buckets_) + + if (applied == 0) { - DownscaleBuckets(point_data_.negative_buckets_, by); + return 0; } - point_data_.scale_ -= static_cast(by); indexer_ = Base2ExponentialHistogramIndexer(point_data_.scale_); + return applied; } // Merge A and B into a new circular buffer C. @@ -329,7 +421,6 @@ std::unique_ptr Base2ExponentialHistogramAggregation::Merge( result_value.count_ = low_res.count_ + high_res.count_; result_value.sum_ = low_res.sum_ + high_res.sum_; result_value.zero_count_ = low_res.zero_count_ + high_res.zero_count_; - result_value.scale_ = (std::min)(low_res.scale_, high_res.scale_); result_value.max_buckets_ = low_res.max_buckets_ >= high_res.max_buckets_ ? low_res.max_buckets_ : high_res.max_buckets_; result_value.record_min_max_ = low_res.record_min_max_ && high_res.record_min_max_; @@ -340,16 +431,7 @@ std::unique_ptr Base2ExponentialHistogramAggregation::Merge( result_value.max_ = (std::max)(low_res.max_, high_res.max_); } - { - auto scale_reduction = high_res.scale_ - low_res.scale_; - - if (scale_reduction > 0) - { - DownscaleBuckets(high_res.positive_buckets_, scale_reduction); - DownscaleBuckets(high_res.negative_buckets_, scale_reduction); - high_res.scale_ -= scale_reduction; - } - } + AlignToScale(high_res, low_res.scale_); // positive_buckets_ and negative_buckets_ share a single scale_; apply // the maximum required reduction across both bucket types. @@ -359,21 +441,18 @@ std::unique_ptr Base2ExponentialHistogramAggregation::Merge( GetScaleReductionForUnion(*low_res.negative_buckets_, *high_res.negative_buckets_, result_value.max_buckets_)); - if (scale_reduction > 0) - { - DownscaleBuckets(low_res.positive_buckets_, scale_reduction); - DownscaleBuckets(high_res.positive_buckets_, scale_reduction); - DownscaleBuckets(low_res.negative_buckets_, scale_reduction); - DownscaleBuckets(high_res.negative_buckets_, scale_reduction); - low_res.scale_ -= static_cast(scale_reduction); - high_res.scale_ -= static_cast(scale_reduction); - result_value.scale_ -= static_cast(scale_reduction); - } + // Both operands share a scale after the alignment above, so one clamped amount applies to both. + const uint32_t applied = ClampScaleReduction(low_res.scale_, scale_reduction); + ApplyDownscale(low_res, applied); + ApplyDownscale(high_res, applied); + result_value.scale_ = low_res.scale_; - result_value.positive_buckets_ = std::make_unique(MergeBuckets( - result_value.max_buckets_, *low_res.positive_buckets_, *high_res.positive_buckets_)); - result_value.negative_buckets_ = std::make_unique(MergeBuckets( - result_value.max_buckets_, *low_res.negative_buckets_, *high_res.negative_buckets_)); + result_value.positive_buckets_ = std::make_unique( + MergeBuckets(BucketCapacity(result_value.max_buckets_), *low_res.positive_buckets_, + *high_res.positive_buckets_)); + result_value.negative_buckets_ = std::make_unique( + MergeBuckets(BucketCapacity(result_value.max_buckets_), *low_res.negative_buckets_, + *high_res.negative_buckets_)); return std::unique_ptr{ new Base2ExponentialHistogramAggregation(std::move(result_value))}; @@ -389,24 +468,7 @@ std::unique_ptr Base2ExponentialHistogramAggregation::Diff( auto &low_res = left.scale_ < right.scale_ ? left : right; auto &high_res = left.scale_ < right.scale_ ? right : left; - { - const auto scale_reduction = high_res.scale_ - low_res.scale_; - - if (scale_reduction > 0) - { - if (high_res.positive_buckets_) - { - DownscaleBuckets(high_res.positive_buckets_, scale_reduction); - } - - if (high_res.negative_buckets_) - { - DownscaleBuckets(high_res.negative_buckets_, scale_reduction); - } - - high_res.scale_ -= scale_reduction; - } - } + AlignToScale(high_res, low_res.scale_); // positive_buckets_ and negative_buckets_ share a single scale_; apply // the maximum required reduction across both bucket types. @@ -416,15 +478,10 @@ std::unique_ptr Base2ExponentialHistogramAggregation::Diff( GetScaleReductionForUnion(*low_res.negative_buckets_, *high_res.negative_buckets_, low_res.max_buckets_)); - if (scale_reduction > 0) - { - DownscaleBuckets(low_res.positive_buckets_, scale_reduction); - DownscaleBuckets(high_res.positive_buckets_, scale_reduction); - DownscaleBuckets(low_res.negative_buckets_, scale_reduction); - DownscaleBuckets(high_res.negative_buckets_, scale_reduction); - low_res.scale_ -= static_cast(scale_reduction); - high_res.scale_ -= static_cast(scale_reduction); - } + // Both operands share a scale after the alignment above, so one clamped amount applies to both. + const uint32_t applied = ClampScaleReduction(low_res.scale_, scale_reduction); + ApplyDownscale(low_res, applied); + ApplyDownscale(high_res, applied); Base2ExponentialHistogramPointData result_value; result_value.scale_ = low_res.scale_; @@ -436,9 +493,9 @@ std::unique_ptr Base2ExponentialHistogramAggregation::Diff( (right.zero_count_ >= left.zero_count_) ? (right.zero_count_ - left.zero_count_) : 0; result_value.positive_buckets_ = - std::make_unique(right.max_buckets_); + std::make_unique(BucketCapacity(right.max_buckets_)); result_value.negative_buckets_ = - std::make_unique(right.max_buckets_); + std::make_unique(BucketCapacity(right.max_buckets_)); if (!left.positive_buckets_->Empty() || !right.positive_buckets_->Empty()) { diff --git a/sdk/src/metrics/aggregation/base2_exponential_histogram_indexer.cc b/sdk/src/metrics/aggregation/base2_exponential_histogram_indexer.cc index 20c4dad7c0..0df9fa4f9e 100644 --- a/sdk/src/metrics/aggregation/base2_exponential_histogram_indexer.cc +++ b/sdk/src/metrics/aggregation/base2_exponential_histogram_indexer.cc @@ -4,6 +4,7 @@ #include "opentelemetry/sdk/metrics/aggregation/base2_exponential_histogram_indexer.h" #include +#include OPENTELEMETRY_BEGIN_NAMESPACE namespace sdk @@ -62,8 +63,10 @@ int32_t Base2ExponentialHistogramIndexer::ComputeIndex(double value) const } // For scale zero, compute the exact index by extracting the exponent. // For negative scales, compute the exact index by extracting the exponent and shifting it to - // the right by -scale - return MapToIndexScaleZero(abs_value) >> -scale_; + // the right by -scale. The shift saturates at 31 because shifting an int32_t by 32 or more is + // undefined, and every index has already collapsed to -1 or 0 at that point. + const int64_t shift = -static_cast(scale_); + return MapToIndexScaleZero(abs_value) >> (shift > 31 ? 31 : static_cast(shift)); } } // namespace metrics diff --git a/sdk/test/metrics/aggregation_test.cc b/sdk/test/metrics/aggregation_test.cc index 086b78bca8..e93a3092e2 100644 --- a/sdk/test/metrics/aggregation_test.cc +++ b/sdk/test/metrics/aggregation_test.cc @@ -1117,3 +1117,178 @@ TEST(Aggregation, Base2ExponentialHistogramAggregationRecordPathRepeatedDownscal ExpectBucketsMatchIndexer(recorded, *point.positive_buckets_, point.scale_, 1.0, "positive"); ExpectBucketsMatchIndexer(recorded, *point.negative_buckets_, point.scale_, -1.0, "negative"); } + +namespace +{ +// The widest span a double can produce: the smallest subnormal and the largest finite value. +constexpr double kTiny = (std::numeric_limits::denorm_min)(); +constexpr double kHuge = (std::numeric_limits::max)(); + +// The most demanding configuration: the scale already starts at the runtime floor and only two +// buckets are budgeted, while the full double range needs three at that scale. +Base2ExponentialHistogramAggregationConfig FloorConfig() +{ + return MakeAggregationConfig(kMinRuntimeScale, kMaxSizeMin); +} + +int32_t BucketSpan(const AdaptingCircularBufferCounter &buckets) +{ + return buckets.Empty() ? 0 : buckets.EndIndex() - buckets.StartIndex() + 1; +} +} // namespace + +TEST(Aggregation, Base2ExponentialHistogramAggregationScaleFloorFullRange) +{ + const auto config = FloorConfig(); + Base2ExponentialHistogramAggregation aggr(&config); + + aggr.Aggregate(kTiny, {}); + aggr.Aggregate(kHuge, {}); + + const auto point = MakePointData(aggr); + EXPECT_EQ(point.scale_, kMinRuntimeScale); + EXPECT_EQ(point.max_buckets_, kMaxSizeMin); + ExpectCountInvariant(2u, point, "ScaleFloorFullRange"); + EXPECT_TRUE(point.negative_buckets_->Empty()); + EXPECT_EQ(BucketSpan(*point.positive_buckets_), static_cast(kMinBucketsAtFloor)); +} + +TEST(Aggregation, Base2ExponentialHistogramAggregationScaleFloorFullRangeNegative) +{ + const auto config = FloorConfig(); + Base2ExponentialHistogramAggregation aggr(&config); + + aggr.Aggregate(-kTiny, {}); + aggr.Aggregate(-kHuge, {}); + + const auto point = MakePointData(aggr); + EXPECT_EQ(point.scale_, kMinRuntimeScale); + ExpectCountInvariant(2u, point, "ScaleFloorFullRangeNegative"); + EXPECT_TRUE(point.positive_buckets_->Empty()); + EXPECT_EQ(BucketSpan(*point.negative_buckets_), static_cast(kMinBucketsAtFloor)); +} + +TEST(Aggregation, Base2ExponentialHistogramAggregationScaleFloorMixedSign) +{ + const auto config = FloorConfig(); + Base2ExponentialHistogramAggregation aggr(&config); + + // Both bucket arrays are driven to the floor while sharing a single scale_. + aggr.Aggregate(kTiny, {}); + aggr.Aggregate(-kHuge, {}); + aggr.Aggregate(kHuge, {}); + aggr.Aggregate(-kTiny, {}); + aggr.Aggregate(0.0, {}); + + const auto point = MakePointData(aggr); + EXPECT_EQ(point.scale_, kMinRuntimeScale); + ExpectCountInvariant(5u, point, "ScaleFloorMixedSign"); + EXPECT_EQ(point.zero_count_, 1u); + EXPECT_EQ(BucketSpan(*point.positive_buckets_), static_cast(kMinBucketsAtFloor)); + EXPECT_EQ(BucketSpan(*point.negative_buckets_), static_cast(kMinBucketsAtFloor)); +} + +TEST(Aggregation, Base2ExponentialHistogramAggregationScaleFloorIsIdempotent) +{ + const auto config = FloorConfig(); + Base2ExponentialHistogramAggregation aggr(&config); + + for (int i = 0; i < 10; ++i) + { + aggr.Aggregate(kTiny, {}); + aggr.Aggregate(kHuge, {}); + aggr.Aggregate(1.0, {}); + EXPECT_EQ(MakePointData(aggr).scale_, kMinRuntimeScale) << "iteration " << i; + } + + ExpectCountInvariant(30u, MakePointData(aggr), "ScaleFloorIsIdempotent"); +} + +TEST(Aggregation, Base2ExponentialHistogramAggregationMergeAtScaleFloor) +{ + const auto config = FloorConfig(); + + Base2ExponentialHistogramAggregation tiny(&config); + tiny.Aggregate(kTiny, {}); + Base2ExponentialHistogramAggregation huge(&config); + huge.Aggregate(-kHuge, {}); + huge.Aggregate(kHuge, {}); + + ASSERT_EQ(MakePointData(tiny).scale_, kMinRuntimeScale); + ASSERT_EQ(MakePointData(huge).scale_, kMinRuntimeScale); + + const auto merged = MakePointData(*tiny.Merge(huge)); + EXPECT_GE(merged.scale_, kMinRuntimeScale); + ExpectCountInvariant(3u, merged, "MergeAtScaleFloor"); +} + +TEST(Aggregation, Base2ExponentialHistogramAggregationMergeFloorWithHighScale) +{ + const auto floor_config = FloorConfig(); + Base2ExponentialHistogramAggregation at_floor(&floor_config); + at_floor.Aggregate(kTiny, {}); + at_floor.Aggregate(kHuge, {}); + + const Base2ExponentialHistogramAggregationConfig default_config; + Base2ExponentialHistogramAggregation fine_grained(&default_config); + // Both recordings land in the same bucket, so this operand keeps its configured max_scale. + fine_grained.Aggregate(1.0, {}); + fine_grained.Aggregate(1.0, {}); + + const auto floor_point = MakePointData(at_floor); + const auto fine_point = MakePointData(fine_grained); + ASSERT_EQ(floor_point.scale_, kMinRuntimeScale); + ASSERT_EQ(fine_point.scale_, default_config.max_scale_); + + // The finer-grained operand is folded onto the coarser scale by exactly the scale delta. + const auto merged = MakePointData(*at_floor.Merge(fine_grained)); + EXPECT_EQ(merged.scale_, kMinRuntimeScale); + ExpectCountInvariant(4u, merged, "MergeFloorWithHighScale"); +} + +TEST(Aggregation, Base2ExponentialHistogramAggregationDiffAtScaleFloor) +{ + const auto config = FloorConfig(); + + Base2ExponentialHistogramAggregation left(&config); + left.Aggregate(kTiny, {}); + + Base2ExponentialHistogramAggregation extra(&config); + extra.Aggregate(kHuge, {}); + + const auto right = left.Merge(extra); + ASSERT_EQ(MakePointData(*right).scale_, kMinRuntimeScale); + + const auto diffed = MakePointData(*left.Diff(*right)); + EXPECT_GE(diffed.scale_, kMinRuntimeScale); + ExpectCountInvariant(1u, diffed, "DiffAtScaleFloor"); +} + +TEST(Aggregation, Base2ExponentialHistogramAggregationDefaultConfigStaysAboveFloor) +{ + // The default budget is wide enough to hold the full double range well above the floor, so the + // floor capacity guarantee must not change the scale a normal configuration settles on. + const Base2ExponentialHistogramAggregationConfig config; + Base2ExponentialHistogramAggregation aggr(&config); + + aggr.Aggregate(kTiny, {}); + aggr.Aggregate(kHuge, {}); + + const auto point = MakePointData(aggr); + EXPECT_GT(point.scale_, kMinRuntimeScale); + EXPECT_LT(point.scale_, config.max_scale_); + EXPECT_EQ(point.max_buckets_, config.max_size_); + ExpectCountInvariant(2u, point, "DefaultConfigStaysAboveFloor"); + EXPECT_LE(BucketSpan(*point.positive_buckets_), static_cast(config.max_size_)); +} + +TEST(Aggregation, Base2ExponentialHistogramIndexerSaturatesShiftAtExtremeNegativeScale) +{ + // Scales this low are only reachable through the point data constructors, but the shift must + // stay defined: every index has collapsed to -1 or 0 by then. + const Base2ExponentialHistogramIndexer indexer(-40); + EXPECT_EQ(indexer.ComputeIndex(1.0), -1); + EXPECT_EQ(indexer.ComputeIndex(kTiny), -1); + EXPECT_EQ(indexer.ComputeIndex(4.0), 0); + EXPECT_EQ(indexer.ComputeIndex(kHuge), 0); +} From 2c25401e74d24eb2ce729a15e2eb3a725d14fabe Mon Sep 17 00:00:00 2001 From: Tom Tan Date: Mon, 3 Aug 2026 19:14:52 -0700 Subject: [PATCH 02/11] Update changelog --- CHANGELOG.md | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 96d655c5f9..053c14f673 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,19 +16,8 @@ Increment the: ## [Unreleased] * [METRICS SDK] Enforce a runtime minimum scale for - `Base2ExponentialHistogramAggregation`. Automatic downscaling now stops at - `kMinRuntimeScale` (-10, the declarative-configuration minimum for - `max_scale`) instead of driving `scale_` below the range the configuration - validator accepts. Every scale mutation on the record, merge and diff paths - goes through one clamped helper, so bucket indices and `scale_` always move by - the same amount. Bucket buffers are allocated with at least three slots - (`kMinBucketsAtFloor`) because every finite double maps to an index in - `[-2, 0]` at the floor; this only widens the degenerate `max_size == 2` - configuration, whose reported `max_buckets_` stays the configured value, and - guarantees no recording is dropped once the floor is reached. The indexer now - saturates its right shift so an out-of-range scale supplied through the - point-data constructors cannot trigger undefined behaviour. - [#4325](https://github.com/open-telemetry/opentelemetry-cpp/issues/4325) + `Base2ExponentialHistogramAggregation`. + [#4353](https://github.com/open-telemetry/opentelemetry-cpp/pull/4353) * [CODE HEALTH] Move remaining `misc-use-internal-linkage` classes/enums into anonymous namespaces: `OtlpFileSystemBackend`/`OtlpFileOstreamBackend` in From cf355bdbee8b859be3a09ea8b12db4fa22aedf67 Mon Sep 17 00:00:00 2001 From: Tom Tan Date: Mon, 3 Aug 2026 22:30:14 -0700 Subject: [PATCH 03/11] Fix IWYU --- ...base2_exponential_histogram_aggregation.cc | 36 ++++++++++++- .../base2_exponential_histogram_indexer.cc | 8 +-- sdk/test/metrics/aggregation_test.cc | 52 +++++++++++++++++++ 3 files changed, 91 insertions(+), 5 deletions(-) diff --git a/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc b/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc index c99da533c5..45aec5b503 100644 --- a/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc +++ b/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc @@ -105,6 +105,34 @@ size_t BucketCapacity(size_t max_buckets) noexcept return (std::max)(max_buckets, kMinBucketsAtFloor); } +// Point data handed to the public constructors carries buffers the caller sized, which can be +// narrower than the capacity this class guarantees; move the counts into a wide enough buffer. +void EnsureBucketCapacity(std::unique_ptr &buckets, + size_t capacity) noexcept +{ + if (!buckets || buckets->MaxSize() >= capacity) + { + return; + } + + auto widened = std::make_unique(capacity); + if (!buckets->Empty()) + { + for (int32_t index = buckets->StartIndex(); index <= buckets->EndIndex(); ++index) + { + const uint64_t count = buckets->Get(index); + if (count > 0 && !widened->Increment(index, count)) + { + OTEL_INTERNAL_LOG_ERROR( + "[Base2ExponentialHistogramAggregation::EnsureBucketCapacity] bucket index " + << index << " out of range; count " << count << " dropped. SDK invariant violation"); + assert(false && "EnsureBucketCapacity: bucket index out of range"); + } + } + } + buckets = std::move(widened); +} + // Truncates `requested` to the reduction that can be applied without pushing `current_scale` below // kMinRuntimeScale. Returns 0 once the floor is reached. uint32_t ClampScaleReduction(int32_t current_scale, uint32_t requested) noexcept @@ -235,6 +263,9 @@ Base2ExponentialHistogramAggregation::Base2ExponentialHistogramAggregation( point_data_.negative_buckets_ = std::make_unique(*point_data.negative_buckets_); } + + EnsureBucketCapacity(point_data_.positive_buckets_, BucketCapacity(point_data_.max_buckets_)); + EnsureBucketCapacity(point_data_.negative_buckets_, BucketCapacity(point_data_.max_buckets_)); } Base2ExponentialHistogramAggregation::Base2ExponentialHistogramAggregation( @@ -242,7 +273,10 @@ Base2ExponentialHistogramAggregation::Base2ExponentialHistogramAggregation( : point_data_{std::move(point_data)}, indexer_(point_data_.scale_), record_min_max_{point_data_.record_min_max_} -{} +{ + EnsureBucketCapacity(point_data_.positive_buckets_, BucketCapacity(point_data_.max_buckets_)); + EnsureBucketCapacity(point_data_.negative_buckets_, BucketCapacity(point_data_.max_buckets_)); +} void Base2ExponentialHistogramAggregation::Aggregate( int64_t value, diff --git a/sdk/src/metrics/aggregation/base2_exponential_histogram_indexer.cc b/sdk/src/metrics/aggregation/base2_exponential_histogram_indexer.cc index 0df9fa4f9e..568d5ba5ba 100644 --- a/sdk/src/metrics/aggregation/base2_exponential_histogram_indexer.cc +++ b/sdk/src/metrics/aggregation/base2_exponential_histogram_indexer.cc @@ -4,7 +4,6 @@ #include "opentelemetry/sdk/metrics/aggregation/base2_exponential_histogram_indexer.h" #include -#include OPENTELEMETRY_BEGIN_NAMESPACE namespace sdk @@ -64,9 +63,10 @@ int32_t Base2ExponentialHistogramIndexer::ComputeIndex(double value) const // For scale zero, compute the exact index by extracting the exponent. // For negative scales, compute the exact index by extracting the exponent and shifting it to // the right by -scale. The shift saturates at 31 because shifting an int32_t by 32 or more is - // undefined, and every index has already collapsed to -1 or 0 at that point. - const int64_t shift = -static_cast(scale_); - return MapToIndexScaleZero(abs_value) >> (shift > 31 ? 31 : static_cast(shift)); + // undefined, and every index has already collapsed to -1 or 0 at that point. Testing the scale + // rather than its negation also keeps INT32_MIN from overflowing. + const int32_t shift = scale_ < -31 ? 31 : -scale_; + return MapToIndexScaleZero(abs_value) >> shift; } } // namespace metrics diff --git a/sdk/test/metrics/aggregation_test.cc b/sdk/test/metrics/aggregation_test.cc index e93a3092e2..e44466bc7d 100644 --- a/sdk/test/metrics/aggregation_test.cc +++ b/sdk/test/metrics/aggregation_test.cc @@ -1135,6 +1135,36 @@ int32_t BucketSpan(const AdaptingCircularBufferCounter &buckets) { return buckets.Empty() ? 0 : buckets.EndIndex() - buckets.StartIndex() + 1; } + +// Point data as an external caller may legitimately supply it: already at the runtime floor, with +// the configured two-bucket budget and a matching two-slot buffer that holds kTiny at index -2. +Base2ExponentialHistogramPointData MakeFloorPointDataWithNarrowBuckets() +{ + Base2ExponentialHistogramPointData point; + point.max_buckets_ = kMaxSizeMin; + point.scale_ = kMinRuntimeScale; + point.count_ = 1; + point.sum_ = kTiny; + point.min_ = kTiny; + point.max_ = kTiny; + point.record_min_max_ = true; + + point.positive_buckets_ = std::make_unique(kMaxSizeMin); + point.negative_buckets_ = std::make_unique(kMaxSizeMin); + EXPECT_TRUE(point.positive_buckets_->Increment(-2, 1)); + return point; +} + +void ExpectFloorPointDataAcceptsFullRange(const Base2ExponentialHistogramPointData &point, + nostd::string_view label) +{ + SCOPED_TRACE(label); + EXPECT_EQ(point.scale_, kMinRuntimeScale); + EXPECT_EQ(point.max_buckets_, kMaxSizeMin); + ExpectCountInvariant(2u, point, label); + EXPECT_GE(point.positive_buckets_->MaxSize(), kMinBucketsAtFloor); + EXPECT_EQ(BucketSpan(*point.positive_buckets_), static_cast(kMinBucketsAtFloor)); +} } // namespace TEST(Aggregation, Base2ExponentialHistogramAggregationScaleFloorFullRange) @@ -1292,3 +1322,25 @@ TEST(Aggregation, Base2ExponentialHistogramIndexerSaturatesShiftAtExtremeNegativ EXPECT_EQ(indexer.ComputeIndex(4.0), 0); EXPECT_EQ(indexer.ComputeIndex(kHuge), 0); } + +TEST(Aggregation, Base2ExponentialHistogramAggregationCopiedPointDataKeepsFloorCapacity) +{ + // The caller's two-slot buffer cannot hold the three buckets the floor needs, so the copy has to + // be widened or the next full-range recording is dropped. + const auto point_data = MakeFloorPointDataWithNarrowBuckets(); + Base2ExponentialHistogramAggregation aggr(point_data); + + aggr.Aggregate(kHuge, {}); + + ExpectFloorPointDataAcceptsFullRange(MakePointData(aggr), "CopiedPointDataKeepsFloorCapacity"); + EXPECT_EQ(point_data.positive_buckets_->MaxSize(), kMaxSizeMin); +} + +TEST(Aggregation, Base2ExponentialHistogramAggregationMovedPointDataKeepsFloorCapacity) +{ + Base2ExponentialHistogramAggregation aggr(MakeFloorPointDataWithNarrowBuckets()); + + aggr.Aggregate(kHuge, {}); + + ExpectFloorPointDataAcceptsFullRange(MakePointData(aggr), "MovedPointDataKeepsFloorCapacity"); +} From 173b81ea3d352deea3e3b2983d3d1dcf0ab4717a Mon Sep 17 00:00:00 2001 From: Tom Tan Date: Thu, 6 Aug 2026 15:08:17 -0700 Subject: [PATCH 04/11] Fix cppcheck --- .../base2_exponential_histogram_indexer.cc | 16 +++++++++++----- sdk/test/metrics/aggregation_test.cc | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/sdk/src/metrics/aggregation/base2_exponential_histogram_indexer.cc b/sdk/src/metrics/aggregation/base2_exponential_histogram_indexer.cc index 568d5ba5ba..f21cb8031d 100644 --- a/sdk/src/metrics/aggregation/base2_exponential_histogram_indexer.cc +++ b/sdk/src/metrics/aggregation/base2_exponential_histogram_indexer.cc @@ -62,11 +62,17 @@ int32_t Base2ExponentialHistogramIndexer::ComputeIndex(double value) const } // For scale zero, compute the exact index by extracting the exponent. // For negative scales, compute the exact index by extracting the exponent and shifting it to - // the right by -scale. The shift saturates at 31 because shifting an int32_t by 32 or more is - // undefined, and every index has already collapsed to -1 or 0 at that point. Testing the scale - // rather than its negation also keeps INT32_MIN from overflowing. - const int32_t shift = scale_ < -31 ? 31 : -scale_; - return MapToIndexScaleZero(abs_value) >> shift; + // the right by -scale. + const int32_t index = MapToIndexScaleZero(abs_value); + // Every finite double has an exponent in [-1075, 1023], so shifting by 11 or more already + // collapses the index to -1 or 0. Returning that directly keeps the shift well inside the width + // of int32_t, and testing the scale rather than its negation keeps INT32_MIN from overflowing. + constexpr int32_t kCollapsedShift = 11; + if (scale_ < -kCollapsedShift) + { + return index < 0 ? -1 : 0; + } + return index >> -scale_; } } // namespace metrics diff --git a/sdk/test/metrics/aggregation_test.cc b/sdk/test/metrics/aggregation_test.cc index 37aafb27aa..8f313c713e 100644 --- a/sdk/test/metrics/aggregation_test.cc +++ b/sdk/test/metrics/aggregation_test.cc @@ -1321,6 +1321,20 @@ TEST(Aggregation, Base2ExponentialHistogramIndexerSaturatesShiftAtExtremeNegativ EXPECT_EQ(indexer.ComputeIndex(kTiny), -1); EXPECT_EQ(indexer.ComputeIndex(4.0), 0); EXPECT_EQ(indexer.ComputeIndex(kHuge), 0); + + // -11 still shifts while the lower scales return the collapsed index directly; the two paths + // have to agree, otherwise the saturation would change results instead of just defining them. + const std::vector values = {kTiny, 1e-300, 0.5, 1.0, 4.0, 1e300, kHuge}; + const Base2ExponentialHistogramIndexer shifted(-11); + for (int32_t scale : {-12, -20, -31, -40}) + { + const Base2ExponentialHistogramIndexer collapsed(scale); + for (double value : values) + { + EXPECT_EQ(collapsed.ComputeIndex(value), shifted.ComputeIndex(value)) + << "scale " << scale << ", value " << value; + } + } } TEST(Aggregation, Base2ExponentialHistogramAggregationCopiedPointDataKeepsFloorCapacity) From d2a3d9d9a3bd540a1fae3e8a1e7fa2bc33af085e Mon Sep 17 00:00:00 2001 From: Tom Tan Date: Thu, 6 Aug 2026 17:50:42 -0700 Subject: [PATCH 05/11] Address feedback --- .../metrics/aggregation/aggregation_config.h | 12 ++-- ...base2_exponential_histogram_aggregation.cc | 12 ++-- sdk/test/metrics/aggregation_test.cc | 57 ++++++++++--------- 3 files changed, 41 insertions(+), 40 deletions(-) diff --git a/sdk/include/opentelemetry/sdk/metrics/aggregation/aggregation_config.h b/sdk/include/opentelemetry/sdk/metrics/aggregation/aggregation_config.h index 165a1a579b..ef11b5f602 100644 --- a/sdk/include/opentelemetry/sdk/metrics/aggregation/aggregation_config.h +++ b/sdk/include/opentelemetry/sdk/metrics/aggregation/aggregation_config.h @@ -73,14 +73,10 @@ constexpr std::int32_t kMaxScaleMax = 20; constexpr std::size_t kMaxSizeMin = 2; // Lower bound for the scale chosen at runtime by automatic downscaling. The specification only -// requires a "reasonable minimum", so this SDK aligns the runtime floor with the declarative -// configuration minimum for max_scale. -constexpr std::int32_t kMinRuntimeScale = kMaxScaleMin; - -// Bucket slots needed to keep every finite double representable at kMinRuntimeScale, where all -// values map to an index in [-2, 0]. Bucket buffers are never allocated smaller than this, so a -// histogram pinned at the floor never has to drop a recording. -constexpr std::size_t kMinBucketsAtFloor = 3; +// requires a "reasonable minimum". At -11 every finite double maps to a bucket index in [-1, 0], +// so the whole range fits in kMaxSizeMin buckets and no configuration needs more than its +// max_size. This bounds the runtime scale only; max_scale still starts no lower than kMaxScaleMin. +constexpr std::int32_t kMinRuntimeScale = -11; class Base2ExponentialHistogramAggregationConfig : public AggregationConfig { diff --git a/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc b/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc index b8a79797b3..d9be6ce7e0 100644 --- a/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc +++ b/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc @@ -97,12 +97,12 @@ void DownscaleBuckets(std::unique_ptr &buckets, u buckets->Downscale(by); } -// Bucket buffers are never narrower than kMinBucketsAtFloor so that the whole double range stays -// representable once the scale is pinned at kMinRuntimeScale. This only widens the degenerate -// max_size_ == 2 configuration, and the extra slot is only reachable at the floor. +// Guards point data that arrives through the public constructors with a smaller budget than the +// configuration validator would ever produce. A configured max_size is at least kMaxSizeMin, so +// this never allocates more buckets than the user asked for. size_t BucketCapacity(size_t max_buckets) noexcept { - return (std::max)(max_buckets, kMinBucketsAtFloor); + return (std::max)(max_buckets, kMaxSizeMin); } // Point data handed to the public constructors carries buffers the caller sized, which can be @@ -338,8 +338,8 @@ void Base2ExponentialHistogramAggregation::AggregateIntoBuckets( const int32_t index = indexer_.ComputeIndex(value); - // The backing buffer can be wider than the configured budget (see BucketCapacity), so the - // reduction is derived from max_buckets_ instead of relying on Increment() to fail. + // The reduction is derived from the configured budget so max_buckets_ is enforced directly + // instead of relying on Increment() to fail. uint32_t scale_reduction = 0; if (!buckets->Empty()) { diff --git a/sdk/test/metrics/aggregation_test.cc b/sdk/test/metrics/aggregation_test.cc index 8f313c713e..814950f661 100644 --- a/sdk/test/metrics/aggregation_test.cc +++ b/sdk/test/metrics/aggregation_test.cc @@ -1124,11 +1124,11 @@ namespace constexpr double kTiny = (std::numeric_limits::denorm_min)(); constexpr double kHuge = (std::numeric_limits::max)(); -// The most demanding configuration: the scale already starts at the runtime floor and only two -// buckets are budgeted, while the full double range needs three at that scale. +// The most demanding configuration: the lowest scale the schema allows for max_scale and only two +// buckets budgeted, so the full double range forces the last downscale to the runtime floor. Base2ExponentialHistogramAggregationConfig FloorConfig() { - return MakeAggregationConfig(kMinRuntimeScale, kMaxSizeMin); + return MakeAggregationConfig(kMaxScaleMin, kMaxSizeMin); } int32_t BucketSpan(const AdaptingCircularBufferCounter &buckets) @@ -1136,8 +1136,8 @@ int32_t BucketSpan(const AdaptingCircularBufferCounter &buckets) return buckets.Empty() ? 0 : buckets.EndIndex() - buckets.StartIndex() + 1; } -// Point data as an external caller may legitimately supply it: already at the runtime floor, with -// the configured two-bucket budget and a matching two-slot buffer that holds kTiny at index -2. +// Point data as an external caller may legitimately supply it: already at the runtime floor and +// holding kTiny, but with a buffer narrower than the budget the same point advertises. Base2ExponentialHistogramPointData MakeFloorPointDataWithNarrowBuckets() { Base2ExponentialHistogramPointData point; @@ -1149,9 +1149,9 @@ Base2ExponentialHistogramPointData MakeFloorPointDataWithNarrowBuckets() point.max_ = kTiny; point.record_min_max_ = true; - point.positive_buckets_ = std::make_unique(kMaxSizeMin); - point.negative_buckets_ = std::make_unique(kMaxSizeMin); - EXPECT_TRUE(point.positive_buckets_->Increment(-2, 1)); + point.positive_buckets_ = std::make_unique(1); + point.negative_buckets_ = std::make_unique(1); + EXPECT_TRUE(point.positive_buckets_->Increment(-1, 1)); return point; } @@ -1162,8 +1162,8 @@ void ExpectFloorPointDataAcceptsFullRange(const Base2ExponentialHistogramPointDa EXPECT_EQ(point.scale_, kMinRuntimeScale); EXPECT_EQ(point.max_buckets_, kMaxSizeMin); ExpectCountInvariant(2u, point, label); - EXPECT_GE(point.positive_buckets_->MaxSize(), kMinBucketsAtFloor); - EXPECT_EQ(BucketSpan(*point.positive_buckets_), static_cast(kMinBucketsAtFloor)); + EXPECT_GE(point.positive_buckets_->MaxSize(), kMaxSizeMin); + EXPECT_EQ(BucketSpan(*point.positive_buckets_), static_cast(kMaxSizeMin)); } } // namespace @@ -1180,7 +1180,7 @@ TEST(Aggregation, Base2ExponentialHistogramAggregationScaleFloorFullRange) EXPECT_EQ(point.max_buckets_, kMaxSizeMin); ExpectCountInvariant(2u, point, "ScaleFloorFullRange"); EXPECT_TRUE(point.negative_buckets_->Empty()); - EXPECT_EQ(BucketSpan(*point.positive_buckets_), static_cast(kMinBucketsAtFloor)); + EXPECT_EQ(BucketSpan(*point.positive_buckets_), static_cast(kMaxSizeMin)); } TEST(Aggregation, Base2ExponentialHistogramAggregationScaleFloorFullRangeNegative) @@ -1195,7 +1195,7 @@ TEST(Aggregation, Base2ExponentialHistogramAggregationScaleFloorFullRangeNegativ EXPECT_EQ(point.scale_, kMinRuntimeScale); ExpectCountInvariant(2u, point, "ScaleFloorFullRangeNegative"); EXPECT_TRUE(point.positive_buckets_->Empty()); - EXPECT_EQ(BucketSpan(*point.negative_buckets_), static_cast(kMinBucketsAtFloor)); + EXPECT_EQ(BucketSpan(*point.negative_buckets_), static_cast(kMaxSizeMin)); } TEST(Aggregation, Base2ExponentialHistogramAggregationScaleFloorMixedSign) @@ -1214,8 +1214,8 @@ TEST(Aggregation, Base2ExponentialHistogramAggregationScaleFloorMixedSign) EXPECT_EQ(point.scale_, kMinRuntimeScale); ExpectCountInvariant(5u, point, "ScaleFloorMixedSign"); EXPECT_EQ(point.zero_count_, 1u); - EXPECT_EQ(BucketSpan(*point.positive_buckets_), static_cast(kMinBucketsAtFloor)); - EXPECT_EQ(BucketSpan(*point.negative_buckets_), static_cast(kMinBucketsAtFloor)); + EXPECT_EQ(BucketSpan(*point.positive_buckets_), static_cast(kMaxSizeMin)); + EXPECT_EQ(BucketSpan(*point.negative_buckets_), static_cast(kMaxSizeMin)); } TEST(Aggregation, Base2ExponentialHistogramAggregationScaleFloorIsIdempotent) @@ -1238,18 +1238,23 @@ TEST(Aggregation, Base2ExponentialHistogramAggregationMergeAtScaleFloor) { const auto config = FloorConfig(); - Base2ExponentialHistogramAggregation tiny(&config); - tiny.Aggregate(kTiny, {}); - Base2ExponentialHistogramAggregation huge(&config); - huge.Aggregate(-kHuge, {}); - huge.Aggregate(kHuge, {}); + // Each operand spans the full double range on one sign, so both are already pinned at the floor + // before the merge rather than merely starting at the lowest configurable scale. + Base2ExponentialHistogramAggregation positive(&config); + positive.Aggregate(kTiny, {}); + positive.Aggregate(kHuge, {}); + Base2ExponentialHistogramAggregation negative(&config); + negative.Aggregate(-kTiny, {}); + negative.Aggregate(-kHuge, {}); - ASSERT_EQ(MakePointData(tiny).scale_, kMinRuntimeScale); - ASSERT_EQ(MakePointData(huge).scale_, kMinRuntimeScale); + ASSERT_EQ(MakePointData(positive).scale_, kMinRuntimeScale); + ASSERT_EQ(MakePointData(negative).scale_, kMinRuntimeScale); - const auto merged = MakePointData(*tiny.Merge(huge)); - EXPECT_GE(merged.scale_, kMinRuntimeScale); - ExpectCountInvariant(3u, merged, "MergeAtScaleFloor"); + const auto merged = MakePointData(*positive.Merge(negative)); + EXPECT_EQ(merged.scale_, kMinRuntimeScale); + ExpectCountInvariant(4u, merged, "MergeAtScaleFloor"); + EXPECT_EQ(BucketSpan(*merged.positive_buckets_), static_cast(kMaxSizeMin)); + EXPECT_EQ(BucketSpan(*merged.negative_buckets_), static_cast(kMaxSizeMin)); } TEST(Aggregation, Base2ExponentialHistogramAggregationMergeFloorWithHighScale) @@ -1339,7 +1344,7 @@ TEST(Aggregation, Base2ExponentialHistogramIndexerSaturatesShiftAtExtremeNegativ TEST(Aggregation, Base2ExponentialHistogramAggregationCopiedPointDataKeepsFloorCapacity) { - // The caller's two-slot buffer cannot hold the three buckets the floor needs, so the copy has to + // The caller's buffer is narrower than the budget the same point advertises, so the copy has to // be widened or the next full-range recording is dropped. const auto point_data = MakeFloorPointDataWithNarrowBuckets(); Base2ExponentialHistogramAggregation aggr(point_data); @@ -1347,7 +1352,7 @@ TEST(Aggregation, Base2ExponentialHistogramAggregationCopiedPointDataKeepsFloorC aggr.Aggregate(kHuge, {}); ExpectFloorPointDataAcceptsFullRange(MakePointData(aggr), "CopiedPointDataKeepsFloorCapacity"); - EXPECT_EQ(point_data.positive_buckets_->MaxSize(), kMaxSizeMin); + EXPECT_EQ(point_data.positive_buckets_->MaxSize(), 1u); } TEST(Aggregation, Base2ExponentialHistogramAggregationMovedPointDataKeepsFloorCapacity) From 3b2df84ae59bcf94960af50b4d9bfa62c11c103e Mon Sep 17 00:00:00 2001 From: Tom Tan Date: Tue, 11 Aug 2026 17:06:49 -0700 Subject: [PATCH 06/11] Fix iwyu --- sdk/test/metrics/aggregation_test.cc | 1 + 1 file changed, 1 insertion(+) diff --git a/sdk/test/metrics/aggregation_test.cc b/sdk/test/metrics/aggregation_test.cc index 814950f661..cc09923184 100644 --- a/sdk/test/metrics/aggregation_test.cc +++ b/sdk/test/metrics/aggregation_test.cc @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include From 6831016fc885de9783c523ceb9215fb943b103b4 Mon Sep 17 00:00:00 2001 From: Tom Tan Date: Wed, 19 Aug 2026 11:42:53 -0700 Subject: [PATCH 07/11] Address feedback --- CHANGELOG.md | 9 ++- .../base2_exponential_histogram_aggregation.h | 3 + ...base2_exponential_histogram_aggregation.cc | 28 ++++---- sdk/test/metrics/aggregation_test.cc | 72 +++++++++++++++++++ 4 files changed, 98 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5bae5264ac..0dad30db2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,8 +15,13 @@ Increment the: ## [Unreleased] -* [METRICS SDK] Enforce a runtime minimum scale for - `Base2ExponentialHistogramAggregation`. +* [METRICS SDK] Enforce a runtime minimum scale of `-11` for + `Base2ExponentialHistogramAggregation`, so a recording that spans the full + double range no longer downscales without end. Exported histograms may now + carry a `scale` of `-11`, one step below the minimum the declarative + configuration accepts for `max_scale`, and a configured `max_size` is never + exceeded. This also stops a non-terminating scale reduction for externally + supplied point data whose `max_buckets_` is `0` or `1`. [#4353](https://github.com/open-telemetry/opentelemetry-cpp/pull/4353) * [CONFIGURATION] Build the configured resource detectors in SdkBuilder, apply the `detection.attributes` include/exclude filter to the detected attributes, diff --git a/sdk/include/opentelemetry/sdk/metrics/aggregation/base2_exponential_histogram_aggregation.h b/sdk/include/opentelemetry/sdk/metrics/aggregation/base2_exponential_histogram_aggregation.h index 631050f3db..75d539f57a 100644 --- a/sdk/include/opentelemetry/sdk/metrics/aggregation/base2_exponential_histogram_aggregation.h +++ b/sdk/include/opentelemetry/sdk/metrics/aggregation/base2_exponential_histogram_aggregation.h @@ -58,6 +58,9 @@ class Base2ExponentialHistogramAggregation : public Aggregation bool record_min_max_ = true; // Keeps the scale floor warning off the record hot path after the first occurrence. bool floor_warning_emitted_ = false; + // Same for the dropped-recording error, which repeats on every call once point data arrives with + // buckets that do not match its scale. + bool bucket_index_error_emitted_ = false; }; } // namespace metrics diff --git a/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc b/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc index d9be6ce7e0..6b40749625 100644 --- a/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc +++ b/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc @@ -337,27 +337,31 @@ void Base2ExponentialHistogramAggregation::AggregateIntoBuckets( } const int32_t index = indexer_.ComputeIndex(value); - - // The reduction is derived from the configured budget so max_buckets_ is enforced directly - // instead of relying on Increment() to fail. - uint32_t scale_reduction = 0; - if (!buckets->Empty()) + if (buckets->Increment(index, 1)) { - scale_reduction = - GetScaleReduction((std::min)(buckets->StartIndex(), index), - (std::max)(buckets->EndIndex(), index), point_data_.max_buckets_); + return; } + // A configured max_size is never below kMaxSizeMin, so the buffer capacity equals max_buckets_ + // and the failure above already means the span exceeds the budget. + const uint32_t scale_reduction = + GetScaleReduction((std::min)(buckets->StartIndex(), index), + (std::max)(buckets->EndIndex(), index), point_data_.max_buckets_); + // Downscale() may stop short of the request at the floor, so shift the index by what was // actually applied. const uint32_t applied = Downscale(scale_reduction); - if (!buckets->Increment(index >> applied, 1)) + if (!buckets->Increment(index >> applied, 1) && !bucket_index_error_emitted_) { + // Unreachable for buckets this class produced: at the floor every finite double maps to -1 or + // 0, which fits kMaxSizeMin. It is reachable through the point data constructors, so it is a + // caller input error rather than an assertable invariant. + bucket_index_error_emitted_ = true; OTEL_INTERNAL_LOG_ERROR( "[Base2ExponentialHistogramAggregation::AggregateIntoBuckets] bucket index " - << (index >> applied) << " out of range at scale " << point_data_.scale_ - << "; recording dropped from the buckets. SDK invariant violation"); - assert(false && "AggregateIntoBuckets: bucket index out of range"); + << (index >> applied) << " does not fit the buckets supplied at scale " + << point_data_.scale_ + << "; recording dropped. Further drops on this aggregation are not logged"); } } diff --git a/sdk/test/metrics/aggregation_test.cc b/sdk/test/metrics/aggregation_test.cc index cc09923184..40f1bc646d 100644 --- a/sdk/test/metrics/aggregation_test.cc +++ b/sdk/test/metrics/aggregation_test.cc @@ -13,6 +13,7 @@ #include "opentelemetry/nostd/string_view.h" #include "opentelemetry/nostd/variant.h" +#include "opentelemetry/sdk/common/global_log_handler.h" #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" @@ -24,6 +25,7 @@ #include "opentelemetry/sdk/metrics/data/circular_buffer.h" #include "opentelemetry/sdk/metrics/data/point_data.h" #include "opentelemetry/sdk/metrics/instruments.h" +#include "opentelemetry/test_common/sdk/common/scoped_test_log_handler.h" using namespace opentelemetry::sdk::metrics; namespace nostd = opentelemetry::nostd; @@ -1156,6 +1158,29 @@ Base2ExponentialHistogramPointData MakeFloorPointDataWithNarrowBuckets() return point; } +// A budget the configuration validator never produces, so no downscale can ever satisfy it. Only +// the iteration bound in GetScaleReduction() stops the search. +Base2ExponentialHistogramPointData MakeDegenerateBudgetPointData(size_t max_buckets) +{ + Base2ExponentialHistogramPointData point; + point.max_buckets_ = max_buckets; + return point; +} + +// Buckets that cannot be reconciled with the scale they are labelled with: at the runtime floor no +// finite double reaches index 100, and the floor leaves no downscale to merge it away. +Base2ExponentialHistogramPointData MakeMismatchedBucketPointData() +{ + Base2ExponentialHistogramPointData point; + point.max_buckets_ = kMaxSizeMin; + point.scale_ = kMinRuntimeScale; + point.count_ = 1; + + point.positive_buckets_ = std::make_unique(kMaxSizeMin); + EXPECT_TRUE(point.positive_buckets_->Increment(100, 1)); + return point; +} + void ExpectFloorPointDataAcceptsFullRange(const Base2ExponentialHistogramPointData &point, nostd::string_view label) { @@ -1164,6 +1189,7 @@ void ExpectFloorPointDataAcceptsFullRange(const Base2ExponentialHistogramPointDa EXPECT_EQ(point.max_buckets_, kMaxSizeMin); ExpectCountInvariant(2u, point, label); EXPECT_GE(point.positive_buckets_->MaxSize(), kMaxSizeMin); + EXPECT_LE(point.positive_buckets_->MaxSize(), point.max_buckets_); EXPECT_EQ(BucketSpan(*point.positive_buckets_), static_cast(kMaxSizeMin)); } } // namespace @@ -1182,6 +1208,8 @@ TEST(Aggregation, Base2ExponentialHistogramAggregationScaleFloorFullRange) ExpectCountInvariant(2u, point, "ScaleFloorFullRange"); EXPECT_TRUE(point.negative_buckets_->Empty()); EXPECT_EQ(BucketSpan(*point.positive_buckets_), static_cast(kMaxSizeMin)); + // The budget is a hard cap: reaching the floor must not buy extra buckets. + EXPECT_LE(point.positive_buckets_->MaxSize(), point.max_buckets_); } TEST(Aggregation, Base2ExponentialHistogramAggregationScaleFloorFullRangeNegative) @@ -1197,6 +1225,7 @@ TEST(Aggregation, Base2ExponentialHistogramAggregationScaleFloorFullRangeNegativ ExpectCountInvariant(2u, point, "ScaleFloorFullRangeNegative"); EXPECT_TRUE(point.positive_buckets_->Empty()); EXPECT_EQ(BucketSpan(*point.negative_buckets_), static_cast(kMaxSizeMin)); + EXPECT_LE(point.negative_buckets_->MaxSize(), point.max_buckets_); } TEST(Aggregation, Base2ExponentialHistogramAggregationScaleFloorMixedSign) @@ -1364,3 +1393,46 @@ TEST(Aggregation, Base2ExponentialHistogramAggregationMovedPointDataKeepsFloorCa ExpectFloorPointDataAcceptsFullRange(MakePointData(aggr), "MovedPointDataKeepsFloorCapacity"); } + +TEST(Aggregation, Base2ExponentialHistogramAggregationDegenerateMaxBucketsTerminates) +{ + // max_buckets_ below kMaxSizeMin only arrives through the point data constructors. The span can + // never shrink to fit, so the reduction search has to stop and the recording still has to land. + for (size_t max_buckets : {size_t{0}, size_t{1}}) + { + SCOPED_TRACE(max_buckets); + Base2ExponentialHistogramAggregation aggr(MakeDegenerateBudgetPointData(max_buckets)); + + aggr.Aggregate(kTiny, {}); + aggr.Aggregate(kHuge, {}); + + const auto point = MakePointData(aggr); + EXPECT_EQ(point.scale_, kMinRuntimeScale); + ExpectCountInvariant(2u, point, "DegenerateMaxBucketsTerminates"); + EXPECT_EQ(point.positive_buckets_->MaxSize(), kMaxSizeMin); + EXPECT_EQ(BucketSpan(*point.positive_buckets_), static_cast(kMaxSizeMin)); + } +} + +TEST(Aggregation, Base2ExponentialHistogramAggregationMismatchedBucketsDropRecordings) +{ + // Already at the floor, so Downscale() cannot merge the stale bucket away and every recording is + // dropped. The point of the test is that this reports and continues instead of aborting. + opentelemetry::test_common::ScopedTestLogHandler log_handler{ + opentelemetry::sdk::common::internal_log::LogLevel::Error}; + + Base2ExponentialHistogramAggregation aggr(MakeMismatchedBucketPointData()); + + aggr.Aggregate(1.0, {}); + aggr.Aggregate(kHuge, {}); + + const auto point = MakePointData(aggr); + EXPECT_EQ(point.scale_, kMinRuntimeScale); + EXPECT_EQ(point.count_, 3u); + EXPECT_EQ(SumAllBuckets(point), 1u); + EXPECT_EQ(BucketSpan(*point.positive_buckets_), 1); + + // Two drops, one log line. Nothing about the state can change between recordings, so repeating + // the message would flood the handler from the record path. + EXPECT_EQ(log_handler.Drain().size(), 1u); +} From 396b814dcef5fd7e5d1404a9ca9937ffb83243a4 Mon Sep 17 00:00:00 2001 From: Tom Tan Date: Wed, 19 Aug 2026 15:14:45 -0700 Subject: [PATCH 08/11] Fix bad merge --- CHANGELOG.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b22d1786c1..e15fe4b541 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,8 +18,7 @@ Increment the: * [METRICS SDK] Enforce a runtime minimum scale of `-11` for `Base2ExponentialHistogramAggregation`, so a recording that spans the full double range no longer downscales without end. - [#4353](https://github.com/open-telemetry/opentelemetry-cpp/pull/4353 - + [#4353](https://github.com/open-telemetry/opentelemetry-cpp/pull/4353) * [CONFIGURATION] Add a configuration builder for the host resource detector [#4451](https://github.com/open-telemetry/opentelemetry-cpp/issues/4451) * [CONFIGURATION] Build the configured resource detectors in SdkBuilder, apply From abf4fbbad38b1fd0dadbac95b46c8ff8b265d1cd Mon Sep 17 00:00:00 2001 From: Tom Tan Date: Thu, 3 Sep 2026 21:56:59 -0700 Subject: [PATCH 09/11] Reject malformed base2 exponential histogram points --- .../base2_exponential_histogram_aggregation.h | 3 - ...base2_exponential_histogram_aggregation.cc | 64 ++++++++++++++----- sdk/test/metrics/aggregation_test.cc | 59 ++++++++++++----- 3 files changed, 91 insertions(+), 35 deletions(-) diff --git a/sdk/include/opentelemetry/sdk/metrics/aggregation/base2_exponential_histogram_aggregation.h b/sdk/include/opentelemetry/sdk/metrics/aggregation/base2_exponential_histogram_aggregation.h index 75d539f57a..631050f3db 100644 --- a/sdk/include/opentelemetry/sdk/metrics/aggregation/base2_exponential_histogram_aggregation.h +++ b/sdk/include/opentelemetry/sdk/metrics/aggregation/base2_exponential_histogram_aggregation.h @@ -58,9 +58,6 @@ class Base2ExponentialHistogramAggregation : public Aggregation bool record_min_max_ = true; // Keeps the scale floor warning off the record hot path after the first occurrence. bool floor_warning_emitted_ = false; - // Same for the dropped-recording error, which repeats on every call once point data arrives with - // buckets that do not match its scale. - bool bucket_index_error_emitted_ = false; }; } // namespace metrics diff --git a/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc b/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc index 6b40749625..520f223692 100644 --- a/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc +++ b/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc @@ -110,7 +110,13 @@ size_t BucketCapacity(size_t max_buckets) noexcept void EnsureBucketCapacity(std::unique_ptr &buckets, size_t capacity) noexcept { - if (!buckets || buckets->MaxSize() >= capacity) + if (!buckets) + { + buckets = std::make_unique(capacity); + return; + } + + if (buckets->MaxSize() >= capacity) { return; } @@ -133,6 +139,41 @@ void EnsureBucketCapacity(std::unique_ptr &bucket buckets = std::move(widened); } +bool BucketIndicesMatchScale(const AdaptingCircularBufferCounter &buckets, + int32_t min_index, + int32_t max_index) noexcept +{ + return buckets.Empty() || + (buckets.StartIndex() >= min_index && buckets.EndIndex() <= max_index); +} + +void NormalizeSuppliedPointData(Base2ExponentialHistogramPointData &point_data) noexcept +{ + const size_t capacity = BucketCapacity(point_data.max_buckets_); + EnsureBucketCapacity(point_data.positive_buckets_, capacity); + EnsureBucketCapacity(point_data.negative_buckets_, capacity); + + const Base2ExponentialHistogramIndexer indexer(point_data.scale_); + const int32_t min_index = indexer.ComputeIndex((std::numeric_limits::denorm_min)()); + const int32_t max_index = indexer.ComputeIndex((std::numeric_limits::max)()); + if (BucketIndicesMatchScale(*point_data.positive_buckets_, min_index, max_index) && + BucketIndicesMatchScale(*point_data.negative_buckets_, min_index, max_index)) + { + return; + } + + OTEL_INTERNAL_LOG_ERROR( + "[Base2ExponentialHistogramAggregation] supplied bucket indexes do not match scale " + << point_data.scale_ << "; point data discarded"); + point_data.sum_ = 0.0; + point_data.min_ = (std::numeric_limits::max)(); + point_data.max_ = (std::numeric_limits::min)(); + point_data.count_ = 0; + point_data.zero_count_ = 0; + point_data.positive_buckets_->Clear(); + point_data.negative_buckets_->Clear(); +} + // Truncates `requested` to the reduction that can be applied without pushing `current_scale` below // kMinRuntimeScale. Returns 0 once the floor is reached. uint32_t ClampScaleReduction(int32_t current_scale, uint32_t requested) noexcept @@ -264,8 +305,7 @@ Base2ExponentialHistogramAggregation::Base2ExponentialHistogramAggregation( std::make_unique(*point_data.negative_buckets_); } - EnsureBucketCapacity(point_data_.positive_buckets_, BucketCapacity(point_data_.max_buckets_)); - EnsureBucketCapacity(point_data_.negative_buckets_, BucketCapacity(point_data_.max_buckets_)); + NormalizeSuppliedPointData(point_data_); } Base2ExponentialHistogramAggregation::Base2ExponentialHistogramAggregation( @@ -274,8 +314,7 @@ Base2ExponentialHistogramAggregation::Base2ExponentialHistogramAggregation( indexer_(point_data_.scale_), record_min_max_{point_data_.record_min_max_} { - EnsureBucketCapacity(point_data_.positive_buckets_, BucketCapacity(point_data_.max_buckets_)); - EnsureBucketCapacity(point_data_.negative_buckets_, BucketCapacity(point_data_.max_buckets_)); + NormalizeSuppliedPointData(point_data_); } void Base2ExponentialHistogramAggregation::Aggregate( @@ -351,17 +390,12 @@ void Base2ExponentialHistogramAggregation::AggregateIntoBuckets( // Downscale() may stop short of the request at the floor, so shift the index by what was // actually applied. const uint32_t applied = Downscale(scale_reduction); - if (!buckets->Increment(index >> applied, 1) && !bucket_index_error_emitted_) + if (!buckets->Increment(index >> applied, 1)) { - // Unreachable for buckets this class produced: at the floor every finite double maps to -1 or - // 0, which fits kMaxSizeMin. It is reachable through the point data constructors, so it is a - // caller input error rather than an assertable invariant. - bucket_index_error_emitted_ = true; OTEL_INTERNAL_LOG_ERROR( "[Base2ExponentialHistogramAggregation::AggregateIntoBuckets] bucket index " - << (index >> applied) << " does not fit the buckets supplied at scale " - << point_data_.scale_ - << "; recording dropped. Further drops on this aggregation are not logged"); + << (index >> applied) << " out of range; count dropped. SDK invariant violation"); + assert(false && "AggregateIntoBuckets: bucket index out of range"); } } @@ -531,9 +565,9 @@ std::unique_ptr Base2ExponentialHistogramAggregation::Diff( (right.zero_count_ >= left.zero_count_) ? (right.zero_count_ - left.zero_count_) : 0; result_value.positive_buckets_ = - std::make_unique(BucketCapacity(right.max_buckets_)); + std::make_unique(BucketCapacity(result_value.max_buckets_)); result_value.negative_buckets_ = - std::make_unique(BucketCapacity(right.max_buckets_)); + std::make_unique(BucketCapacity(result_value.max_buckets_)); if (!left.positive_buckets_->Empty() || !right.positive_buckets_->Empty()) { diff --git a/sdk/test/metrics/aggregation_test.cc b/sdk/test/metrics/aggregation_test.cc index 40f1bc646d..3eb10c3031 100644 --- a/sdk/test/metrics/aggregation_test.cc +++ b/sdk/test/metrics/aggregation_test.cc @@ -993,6 +993,25 @@ TEST(Aggregation, Base2ExponentialHistogramAggregationDiffScaleMismatch) ExpectCountInvariant(right_pt.count_ - 1u, diffed_point, "DiffScaleMismatch"); } +TEST(Aggregation, Base2ExponentialHistogramAggregationDiffUsesReportedBucketBudget) +{ + const auto narrow_config = MakeAggregationConfig(-1, kMaxSizeMin); + Base2ExponentialHistogramAggregation left(&narrow_config); + left.Aggregate(1.0, {}); + + const auto wide_config = MakeAggregationConfig(0, 8); + Base2ExponentialHistogramAggregation next(&wide_config); + next.Aggregate(1.0, {}); + next.Aggregate(4.0, {}); + + const auto diffed_point = MakePointData(*left.Diff(next)); + + ExpectCountInvariant(1u, diffed_point, "DiffUsesReportedBucketBudget"); + EXPECT_EQ(diffed_point.max_buckets_, kMaxSizeMin); + EXPECT_EQ(diffed_point.positive_buckets_->MaxSize(), diffed_point.max_buckets_); + EXPECT_EQ(diffed_point.negative_buckets_->MaxSize(), diffed_point.max_buckets_); +} + TEST(Aggregation, Base2ExponentialHistogramAggregationDefaultConfigMerge) { Base2ExponentialHistogramAggregationConfig config; @@ -1168,7 +1187,7 @@ Base2ExponentialHistogramPointData MakeDegenerateBudgetPointData(size_t max_buck } // Buckets that cannot be reconciled with the scale they are labelled with: at the runtime floor no -// finite double reaches index 100, and the floor leaves no downscale to merge it away. +// finite double reaches index 100. Base2ExponentialHistogramPointData MakeMismatchedBucketPointData() { Base2ExponentialHistogramPointData point; @@ -1414,25 +1433,31 @@ TEST(Aggregation, Base2ExponentialHistogramAggregationDegenerateMaxBucketsTermin } } -TEST(Aggregation, Base2ExponentialHistogramAggregationMismatchedBucketsDropRecordings) +TEST(Aggregation, Base2ExponentialHistogramAggregationRejectsMismatchedBuckets) { - // Already at the floor, so Downscale() cannot merge the stale bucket away and every recording is - // dropped. The point of the test is that this reports and continues instead of aborting. opentelemetry::test_common::ScopedTestLogHandler log_handler{ opentelemetry::sdk::common::internal_log::LogLevel::Error}; - Base2ExponentialHistogramAggregation aggr(MakeMismatchedBucketPointData()); + const auto malformed = MakeMismatchedBucketPointData(); + Base2ExponentialHistogramAggregation recorded(malformed); + recorded.Aggregate(1.0, {}); + ExpectCountInvariant(1u, MakePointData(recorded), "MismatchedRecord"); - aggr.Aggregate(1.0, {}); - aggr.Aggregate(kHuge, {}); - - const auto point = MakePointData(aggr); - EXPECT_EQ(point.scale_, kMinRuntimeScale); - EXPECT_EQ(point.count_, 3u); - EXPECT_EQ(SumAllBuckets(point), 1u); - EXPECT_EQ(BucketSpan(*point.positive_buckets_), 1); - - // Two drops, one log line. Nothing about the state can change between recordings, so repeating - // the message would flood the handler from the record path. - EXPECT_EQ(log_handler.Drain().size(), 1u); + Base2ExponentialHistogramAggregation merge_left(MakeMismatchedBucketPointData()); + merge_left.Aggregate(kTiny, {}); + const auto config = FloorConfig(); + Base2ExponentialHistogramAggregation merge_right(&config); + merge_right.Aggregate(kHuge, {}); + const auto merged = merge_left.Merge(merge_right); + ExpectCountInvariant(2u, MakePointData(*merged), "MismatchedMerge"); + + Base2ExponentialHistogramAggregation diff_left(MakeMismatchedBucketPointData()); + diff_left.Aggregate(kTiny, {}); + Base2ExponentialHistogramAggregation diff_extra(&config); + diff_extra.Aggregate(kHuge, {}); + const auto diff_right = diff_left.Merge(diff_extra); + const auto diffed = diff_left.Diff(*diff_right); + ExpectCountInvariant(1u, MakePointData(*diffed), "MismatchedDiff"); + + EXPECT_EQ(log_handler.Drain().size(), 3u); } From 08dcb54d09d1a7f2b8cd764e5202b64feb56ed85 Mon Sep 17 00:00:00 2001 From: Tom Tan Date: Thu, 3 Sep 2026 22:04:24 -0700 Subject: [PATCH 10/11] Fix format --- .../aggregation/base2_exponential_histogram_aggregation.cc | 3 +-- sdk/test/metrics/aggregation_test.cc | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc b/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc index 520f223692..91efd757a1 100644 --- a/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc +++ b/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc @@ -143,8 +143,7 @@ bool BucketIndicesMatchScale(const AdaptingCircularBufferCounter &buckets, int32_t min_index, int32_t max_index) noexcept { - return buckets.Empty() || - (buckets.StartIndex() >= min_index && buckets.EndIndex() <= max_index); + return buckets.Empty() || (buckets.StartIndex() >= min_index && buckets.EndIndex() <= max_index); } void NormalizeSuppliedPointData(Base2ExponentialHistogramPointData &point_data) noexcept diff --git a/sdk/test/metrics/aggregation_test.cc b/sdk/test/metrics/aggregation_test.cc index 3eb10c3031..9b864c624a 100644 --- a/sdk/test/metrics/aggregation_test.cc +++ b/sdk/test/metrics/aggregation_test.cc @@ -1456,7 +1456,7 @@ TEST(Aggregation, Base2ExponentialHistogramAggregationRejectsMismatchedBuckets) Base2ExponentialHistogramAggregation diff_extra(&config); diff_extra.Aggregate(kHuge, {}); const auto diff_right = diff_left.Merge(diff_extra); - const auto diffed = diff_left.Diff(*diff_right); + const auto diffed = diff_left.Diff(*diff_right); ExpectCountInvariant(1u, MakePointData(*diffed), "MismatchedDiff"); EXPECT_EQ(log_handler.Drain().size(), 3u); From bb77c835f65024d809faadde35efb648c651f090 Mon Sep 17 00:00:00 2001 From: Tom Tan Date: Thu, 24 Sep 2026 09:43:29 -0700 Subject: [PATCH 11/11] Fix base2 histogram Diff count loss and UB on supplied points --- ...base2_exponential_histogram_aggregation.cc | 92 ++++++++------ sdk/test/metrics/aggregation_test.cc | 120 ++++++++++++++++++ 2 files changed, 173 insertions(+), 39 deletions(-) diff --git a/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc b/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc index 91efd757a1..5068d52f98 100644 --- a/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc +++ b/sdk/src/metrics/aggregation/base2_exponential_histogram_aggregation.cc @@ -51,10 +51,16 @@ uint32_t GetScaleReductionForUnion(const AdaptingCircularBufferCounter &low, const AdaptingCircularBufferCounter &high, size_t max_buckets) noexcept { - if (low.Empty() || high.Empty()) + if (low.Empty() && high.Empty()) { return 0; } + // The populated side alone can exceed a result sized for the narrower operand's budget. + if (low.Empty() || high.Empty()) + { + const AdaptingCircularBufferCounter &populated = low.Empty() ? high : low; + return GetScaleReduction(populated.StartIndex(), populated.EndIndex(), max_buckets); + } return GetScaleReduction((std::min)(low.StartIndex(), high.StartIndex()), (std::max)(low.EndIndex(), high.EndIndex()), max_buckets); } @@ -97,6 +103,32 @@ void DownscaleBuckets(std::unique_ptr &buckets, u buckets->Downscale(by); } +// Folds `high_res` onto `target_scale`. The bucket shift has to match the scale delta exactly, so +// the runtime floor is deliberately not applied here: it bounds the reductions the SDK chooses, +// not the alignment of an operand that already sits lower. +void AlignToScale(Base2ExponentialHistogramPointData &high_res, int32_t target_scale) noexcept +{ + if (high_res.scale_ <= target_scale) + { + return; + } + + // AdaptingCircularBufferCounter::Downscale() saturates at 31, which is idempotent for int32_t + // indices, so a larger delta needs no special handling. + const int64_t delta = static_cast(high_res.scale_) - target_scale; + const uint32_t by = delta > 31 ? 31u : static_cast(delta); + + if (high_res.positive_buckets_) + { + DownscaleBuckets(high_res.positive_buckets_, by); + } + if (high_res.negative_buckets_) + { + DownscaleBuckets(high_res.negative_buckets_, by); + } + high_res.scale_ = target_scale; +} + // Guards point data that arrives through the public constructors with a smaller budget than the // configuration validator would ever produce. A configured max_size is at least kMaxSizeMin, so // this never allocates more buckets than the user asked for. @@ -124,10 +156,10 @@ void EnsureBucketCapacity(std::unique_ptr &bucket auto widened = std::make_unique(capacity); if (!buckets->Empty()) { - for (int32_t index = buckets->StartIndex(); index <= buckets->EndIndex(); ++index) + for (int64_t index = buckets->StartIndex(); index <= buckets->EndIndex(); ++index) { - const uint64_t count = buckets->Get(index); - if (count > 0 && !widened->Increment(index, count)) + const uint64_t count = buckets->Get(static_cast(index)); + if (count > 0 && !widened->Increment(static_cast(index), count)) { OTEL_INTERNAL_LOG_ERROR( "[Base2ExponentialHistogramAggregation::EnsureBucketCapacity] bucket index " @@ -139,25 +171,28 @@ void EnsureBucketCapacity(std::unique_ptr &bucket buckets = std::move(widened); } -bool BucketIndicesMatchScale(const AdaptingCircularBufferCounter &buckets, +bool BucketIndicesMatchScale(const AdaptingCircularBufferCounter *buckets, int32_t min_index, int32_t max_index) noexcept { - return buckets.Empty() || (buckets.StartIndex() >= min_index && buckets.EndIndex() <= max_index); + return buckets == nullptr || buckets->Empty() || + (buckets->StartIndex() >= min_index && buckets->EndIndex() <= max_index); } void NormalizeSuppliedPointData(Base2ExponentialHistogramPointData &point_data) noexcept { - const size_t capacity = BucketCapacity(point_data.max_buckets_); - EnsureBucketCapacity(point_data.positive_buckets_, capacity); - EnsureBucketCapacity(point_data.negative_buckets_, capacity); + // Index bounds above kMaxScaleMax overflow int32_t; folding keeps every supplied count. + AlignToScale(point_data, kMaxScaleMax); + const size_t capacity = BucketCapacity(point_data.max_buckets_); const Base2ExponentialHistogramIndexer indexer(point_data.scale_); const int32_t min_index = indexer.ComputeIndex((std::numeric_limits::denorm_min)()); const int32_t max_index = indexer.ComputeIndex((std::numeric_limits::max)()); - if (BucketIndicesMatchScale(*point_data.positive_buckets_, min_index, max_index) && - BucketIndicesMatchScale(*point_data.negative_buckets_, min_index, max_index)) + if (BucketIndicesMatchScale(point_data.positive_buckets_.get(), min_index, max_index) && + BucketIndicesMatchScale(point_data.negative_buckets_.get(), min_index, max_index)) { + EnsureBucketCapacity(point_data.positive_buckets_, capacity); + EnsureBucketCapacity(point_data.negative_buckets_, capacity); return; } @@ -169,8 +204,9 @@ void NormalizeSuppliedPointData(Base2ExponentialHistogramPointData &point_data) point_data.max_ = (std::numeric_limits::min)(); point_data.count_ = 0; point_data.zero_count_ = 0; - point_data.positive_buckets_->Clear(); - point_data.negative_buckets_->Clear(); + // Fresh counters rather than Clear(): a moved-in counter may be null. + point_data.positive_buckets_ = std::make_unique(capacity); + point_data.negative_buckets_ = std::make_unique(capacity); } // Truncates `requested` to the reduction that can be applied without pushing `current_scale` below @@ -207,32 +243,6 @@ uint32_t ApplyDownscale(Base2ExponentialHistogramPointData &point_data, uint32_t return applied; } -// Folds `high_res` onto `target_scale`. The bucket shift has to match the scale delta exactly, so -// the runtime floor is deliberately not applied here: it bounds the reductions the SDK chooses, -// not the alignment of an operand that already sits lower. -void AlignToScale(Base2ExponentialHistogramPointData &high_res, int32_t target_scale) noexcept -{ - if (high_res.scale_ <= target_scale) - { - return; - } - - // AdaptingCircularBufferCounter::Downscale() saturates at 31, which is idempotent for int32_t - // indices, so a larger delta needs no special handling. - const int64_t delta = static_cast(high_res.scale_) - target_scale; - const uint32_t by = delta > 31 ? 31u : static_cast(delta); - - if (high_res.positive_buckets_) - { - DownscaleBuckets(high_res.positive_buckets_, by); - } - if (high_res.negative_buckets_) - { - DownscaleBuckets(high_res.negative_buckets_, by); - } - high_res.scale_ = target_scale; -} - } // namespace Base2ExponentialHistogramAggregation::Base2ExponentialHistogramAggregation( @@ -305,6 +315,8 @@ Base2ExponentialHistogramAggregation::Base2ExponentialHistogramAggregation( } NormalizeSuppliedPointData(point_data_); + // Normalization may have folded the supplied scale. + indexer_ = Base2ExponentialHistogramIndexer(point_data_.scale_); } Base2ExponentialHistogramAggregation::Base2ExponentialHistogramAggregation( @@ -314,6 +326,8 @@ Base2ExponentialHistogramAggregation::Base2ExponentialHistogramAggregation( record_min_max_{point_data_.record_min_max_} { NormalizeSuppliedPointData(point_data_); + // Normalization may have folded the supplied scale. + indexer_ = Base2ExponentialHistogramIndexer(point_data_.scale_); } void Base2ExponentialHistogramAggregation::Aggregate( diff --git a/sdk/test/metrics/aggregation_test.cc b/sdk/test/metrics/aggregation_test.cc index 9b864c624a..3a469171c9 100644 --- a/sdk/test/metrics/aggregation_test.cc +++ b/sdk/test/metrics/aggregation_test.cc @@ -1012,6 +1012,38 @@ TEST(Aggregation, Base2ExponentialHistogramAggregationDiffUsesReportedBucketBudg EXPECT_EQ(diffed_point.negative_buckets_->MaxSize(), diffed_point.max_buckets_); } +TEST(Aggregation, Base2ExponentialHistogramAggregationDiffOneSideEmptyFitsReportedBudget) +{ + // left has no buckets on the populated sign, so only next's own span shows that the narrow result + // budget needs a reduction. + const auto narrow_config = MakeAggregationConfig(-1, kMaxSizeMin); + const auto wide_config = MakeAggregationConfig(0, 8); + + for (double sign : {1.0, -1.0}) + { + SCOPED_TRACE(sign); + Base2ExponentialHistogramAggregation left(&narrow_config); + Base2ExponentialHistogramAggregation next(&wide_config); + next.Aggregate(sign * 1.0, {}); // index -1 + next.Aggregate(sign * 16.0, {}); // index 3 + + const auto diffed_point = MakePointData(*left.Diff(next)); + ExpectCountInvariant(2u, diffed_point, "DiffOneSideEmpty"); + EXPECT_EQ(diffed_point.positive_buckets_->MaxSize(), diffed_point.max_buckets_); + EXPECT_EQ(diffed_point.negative_buckets_->MaxSize(), diffed_point.max_buckets_); + } + + // The negative union fits, so only the empty positive side can demand the reduction. + Base2ExponentialHistogramAggregation left(&narrow_config); + left.Aggregate(-1.0, {}); + Base2ExponentialHistogramAggregation next(&wide_config); + next.Aggregate(-1.0, {}); + next.Aggregate(1.0, {}); + next.Aggregate(16.0, {}); + + ExpectCountInvariant(2u, MakePointData(*left.Diff(next)), "DiffOneSignEmpty"); +} + TEST(Aggregation, Base2ExponentialHistogramAggregationDefaultConfigMerge) { Base2ExponentialHistogramAggregationConfig config; @@ -1200,6 +1232,39 @@ Base2ExponentialHistogramPointData MakeMismatchedBucketPointData() return point; } +// A one-slot counter at INT32_MAX is narrower than any budget, so it reaches the widening copy loop +// unless the index check runs first. Only the move constructor can receive a null counter. +Base2ExponentialHistogramPointData MakeMaxIndexPointData(bool null_negative_buckets) +{ + Base2ExponentialHistogramPointData point; + point.max_buckets_ = kMaxSizeMin; + point.count_ = 1; + + point.positive_buckets_ = std::make_unique(1); + EXPECT_TRUE(point.positive_buckets_->Increment((std::numeric_limits::max)(), 1)); + if (null_negative_buckets) + { + point.negative_buckets_.reset(); + } + return point; +} + +// Scale 21 is the lowest scale whose index bounds for the full double range overflow int32_t. +Base2ExponentialHistogramPointData MakeTooFineScalePointData(bool with_bucket) +{ + Base2ExponentialHistogramPointData point; + point.max_buckets_ = kMaxSizeMin; + point.scale_ = kMaxScaleMax + 1; + if (with_bucket) + { + point.count_ = 1; + point.positive_buckets_ = std::make_unique(kMaxSizeMin); + EXPECT_TRUE(point.positive_buckets_->Increment( + Base2ExponentialHistogramIndexer(point.scale_).ComputeIndex(1.5), 1)); + } + return point; +} + void ExpectFloorPointDataAcceptsFullRange(const Base2ExponentialHistogramPointData &point, nostd::string_view label) { @@ -1461,3 +1526,58 @@ TEST(Aggregation, Base2ExponentialHistogramAggregationRejectsMismatchedBuckets) EXPECT_EQ(log_handler.Drain().size(), 3u); } + +TEST(Aggregation, Base2ExponentialHistogramAggregationRejectsMaxIndexBeforeWidening) +{ + opentelemetry::test_common::ScopedTestLogHandler log_handler{ + opentelemetry::sdk::common::internal_log::LogLevel::Error}; + + const auto copied_source = MakeMaxIndexPointData(false); + Base2ExponentialHistogramAggregation copied(copied_source); + Base2ExponentialHistogramAggregation moved(MakeMaxIndexPointData(false)); + Base2ExponentialHistogramAggregation moved_null_negative(MakeMaxIndexPointData(true)); + + for (auto *aggr : {&copied, &moved, &moved_null_negative}) + { + const auto point = MakePointData(*aggr); + EXPECT_EQ(point.count_, 0u); + ASSERT_TRUE(point.positive_buckets_ != nullptr); + ASSERT_TRUE(point.negative_buckets_ != nullptr); + EXPECT_TRUE(point.positive_buckets_->Empty()); + EXPECT_GE(point.negative_buckets_->MaxSize(), kMaxSizeMin); + + aggr->Aggregate(1.0, {}); + ExpectCountInvariant(1u, MakePointData(*aggr), "RecordAfterRejectedMaxIndex"); + } + + EXPECT_EQ(log_handler.Drain().size(), 3u); +} + +TEST(Aggregation, Base2ExponentialHistogramAggregationFoldsScaleAboveMaximum) +{ + const int32_t bucket_index = Base2ExponentialHistogramIndexer(kMaxScaleMax + 1).ComputeIndex(1.5); + + for (bool with_bucket : {false, true}) + { + SCOPED_TRACE(with_bucket); + const uint64_t supplied_count = with_bucket ? 1 : 0; + const auto copied_source = MakeTooFineScalePointData(with_bucket); + Base2ExponentialHistogramAggregation copied(copied_source); + Base2ExponentialHistogramAggregation moved(MakeTooFineScalePointData(with_bucket)); + + for (auto *aggr : {&copied, &moved}) + { + const auto folded = MakePointData(*aggr); + EXPECT_EQ(folded.scale_, kMaxScaleMax); + ExpectCountInvariant(supplied_count, folded, "FoldedScale"); + + // The same value lands in the folded bucket only if the indexer follows the new scale. + aggr->Aggregate(1.5, {}); + EXPECT_EQ(MakePointData(*aggr).positive_buckets_->Get(bucket_index >> 1), supplied_count + 1); + + aggr->Aggregate(kTiny, {}); + aggr->Aggregate(kHuge, {}); + ExpectCountInvariant(supplied_count + 3, MakePointData(*aggr), "RecordAfterFold"); + } + } +}