Skip to content
Merged
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ Increment the:
* [OTLP/HTTP] Honor `Retry-After` response header when retrying exports,
supporting both delay-seconds and HTTP-date formats per RFC 7231 §7.1.3.
[#4172](https://github.com/open-telemetry/opentelemetry-cpp/issues/4172)

* [BUILD] Run the ext_http component install test on Windows
[#4326](https://github.com/open-telemetry/opentelemetry-cpp/pull/4326)

Expand Down Expand Up @@ -106,6 +107,9 @@ Increment the:
* [SDK] Implement the ProbabilitySampler
[#4135](https://github.com/open-telemetry/opentelemetry-cpp/pull/4135)

* [SDK] Downscale base2 exponential histogram buckets in place
[#4324](https://github.com/open-telemetry/opentelemetry-cpp/pull/4324)

Breaking changes:

* [METRICS SDK] Rename Base2 Exponential Histogram Aggregation config field
Expand Down
33 changes: 33 additions & 0 deletions sdk/include/opentelemetry/sdk/metrics/data/circular_buffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down Expand Up @@ -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<int32_t>::min)();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,27 +89,9 @@ void DiffBuckets(const AdaptingCircularBufferCounter &left,

void DownscaleBuckets(std::unique_ptr<AdaptingCircularBufferCounter> &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<AdaptingCircularBufferCounter>(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);
Comment thread
dbarker marked this conversation as resolved.
Resolved
}

} // namespace
Expand Down
108 changes: 103 additions & 5 deletions sdk/src/metrics/data/circular_buffer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,32 @@ struct AdaptingIntegerArrayClear
}
};

struct AdaptingIntegerArrayFold
{
size_t from;
size_t to;

template <typename T>
uint64_t operator()(std::vector<T> &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<T>::max()))
{
backing[to] = static_cast<T>(result);
backing[from] = static_cast<T>(0);
return 0;
}
// Leaves the source untouched so the retry after widening sees it again.
return result;
}
};

struct AdaptingIntegerArrayCopy
{
template <class T1, class T2>
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -154,7 +200,7 @@ bool AdaptingCircularBufferCounter::Increment(int32_t index, uint64_t delta)
if (index > end_index_)
{
// Move end, check max size.
if (index + 1 > static_cast<int32_t>(backing_.Size()) + start_index_)
if (static_cast<int64_t>(index) - start_index_ + 1 > static_cast<int64_t>(backing_.Size()))
{
return false;
}
Expand All @@ -163,7 +209,7 @@ 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<int32_t>(backing_.Size()) + index)
if (static_cast<int64_t>(end_index_) - index + 1 > static_cast<int64_t>(backing_.Size()))
{
return false;
}
Expand All @@ -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<uint32_t>(std::numeric_limits<int32_t>::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<int32_t>(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<int64_t>(base_index_) - 1; index >= start_index_; --index)
{
FoldBucket(static_cast<int32_t>(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<size_t>(index + backing_.Size() - base_index_);
return static_cast<size_t>(index + backing_.Size() - base_index);
}
return static_cast<size_t>(index - base_index_);
return static_cast<size_t>(index - base_index);
}

} // namespace metrics
Expand Down
114 changes: 114 additions & 0 deletions sdk/test/metrics/aggregation_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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<double> &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)
Expand Down Expand Up @@ -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<double> 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<int32_t>(config.max_size_));
EXPECT_LE(point.negative_buckets_->EndIndex() - point.negative_buckets_->StartIndex() + 1,
static_cast<int32_t>(config.max_size_));

ExpectBucketsMatchIndexer(recorded, *point.positive_buckets_, point.scale_, 1.0, "positive");
ExpectBucketsMatchIndexer(recorded, *point.negative_buckets_, point.scale_, -1.0, "negative");
}
Loading
Loading