diff --git a/.github/workflows/dev.yml b/.github/workflows/dev.yml index 0d7d1dae..04c63b3c 100644 --- a/.github/workflows/dev.yml +++ b/.github/workflows/dev.yml @@ -64,8 +64,6 @@ jobs: run: cmake --build ${BUILD_DIR} -j -v - name: Test run: cd ${BUILD_DIR} && test/tests -r junit -o report.xml - env: - ASAN_OPTIONS: alloc_dealloc_mismatch=0 - name: Get Datadog credentials if: ${{ !cancelled() && github.event_name != 'pull_request' }} uses: ./.github/actions/dd-sts-credentials diff --git a/BUILD.bazel b/BUILD.bazel index 0a854130..a869a1a2 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -75,6 +75,10 @@ cc_library( "src/datadog/tags.h", "src/datadog/telemetry/configuration.cpp", "src/datadog/telemetry/log.h", + "src/datadog/telemetry/log_bin_index.cpp", + "src/datadog/telemetry/log_bin_index.h", + "src/datadog/telemetry/log_binned_distribution.cpp", + "src/datadog/telemetry/log_binned_distribution.h", "src/datadog/telemetry/metric_context.h", "src/datadog/telemetry/telemetry.cpp", "src/datadog/telemetry/telemetry_impl.cpp", diff --git a/CMakeLists.txt b/CMakeLists.txt index dddf6158..f459c3f1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -183,6 +183,8 @@ target_sources(dd-trace-cpp-objects PRIVATE src/datadog/common/hash.cpp src/datadog/telemetry/configuration.cpp + src/datadog/telemetry/log_bin_index.cpp + src/datadog/telemetry/log_binned_distribution.cpp src/datadog/telemetry/telemetry.cpp src/datadog/telemetry/telemetry_impl.cpp src/datadog/baggage.cpp diff --git a/src/datadog/telemetry/log_bin_index.cpp b/src/datadog/telemetry/log_bin_index.cpp new file mode 100644 index 00000000..b0257e1f --- /dev/null +++ b/src/datadog/telemetry/log_bin_index.cpp @@ -0,0 +1,36 @@ +#include "log_bin_index.h" + +#include + +namespace datadog::telemetry::log_bins { +namespace { + +double log_multiplier(); + +} // namespace + +BinIndex bin_index(double value) { + // Checks the bits, because -ffast-math can remove std::isnan() and friends. + const std::uint64_t bits = to_bits(value); + const bool not_finite = ((bits >> 52) & 0x7ff) == 0x7ff; + const bool below_zero = (bits >> 63) != 0 && (bits << 1) != 0; + if (not_finite || below_zero) return rejected_value; + if (value < zero_threshold) return zero_bin; + + // One rounding for the multiplication and the addition. Separate roundings + // would depend on whether the compiler fuses them. + const double scaled_log = + std::fma(std::log(value), log_multiplier(), bin_index_shift); + return static_cast(std::floor(scaled_log)); +} + +namespace { + +// Same formula as libdatadog: 1 / ln(bin_ratio). +double log_multiplier() { + static const double multiplier = 1.0 / std::log(bin_ratio); + return multiplier; +} + +} // namespace +} // namespace datadog::telemetry::log_bins diff --git a/src/datadog/telemetry/log_bin_index.h b/src/datadog/telemetry/log_bin_index.h new file mode 100644 index 00000000..54821310 --- /dev/null +++ b/src/datadog/telemetry/log_bin_index.h @@ -0,0 +1,50 @@ +#pragma once + +// Bin index of the log-binned distributions. See log_binned_distribution.h +// for the mapping. + +#include +#include +#include + +namespace datadog::telemetry::log_bins { + +// The number of a bin. Same type as LogBinnedDistribution's private BinIndex. +using BinIndex = std::int32_t; + +// Each bin's upper edge is this many times its lower edge. +inline constexpr double bin_ratio = 65.0 / 64.0; +// Shift so that 1e-9 falls in bin 1. +inline constexpr double bin_index_shift = 1338.5; +// Values below this, zero included, are counted apart. +inline constexpr double zero_threshold = + std::numeric_limits::min() * bin_ratio; + +// Special results of bin_index(). +inline constexpr BinIndex zero_bin = std::numeric_limits::min(); +inline constexpr BinIndex rejected_value = zero_bin + 1; + +// Returns the bin of `value`, floor(ln(value) × m + bin_index_shift), with +// m = 1 / ln(bin_ratio). The multiplication and the addition are rounded once. +// Returns `zero_bin` for values below `zero_threshold`, and `rejected_value` +// for negative values, NaN and infinities. +BinIndex bin_index(double value); + +// TODO: replace to_bits() and from_bits() with std::bit_cast after the upgrade +// to C++20. + +// The bits of a double, as an integer. +inline std::uint64_t to_bits(double value) { + std::uint64_t bits; + std::memcpy(&bits, &value, sizeof bits); + return bits; +} + +// The double with these bits. +inline double from_bits(std::uint64_t bits) { + double value; + std::memcpy(&value, &bits, sizeof value); + return value; +} + +} // namespace datadog::telemetry::log_bins diff --git a/src/datadog/telemetry/log_binned_distribution.cpp b/src/datadog/telemetry/log_binned_distribution.cpp new file mode 100644 index 00000000..3d6f83b8 --- /dev/null +++ b/src/datadog/telemetry/log_binned_distribution.cpp @@ -0,0 +1,248 @@ +#include "log_binned_distribution.h" + +#include +#include +#include + +#include "log_bin_index.h" + +namespace datadog::telemetry { +namespace { + +using BinIndex = log_bins::BinIndex; + +constexpr std::int32_t max_bins = 2048; +constexpr std::uint32_t min_window_size = 64; +constexpr std::uint32_t max_window_size = 2 * max_bins; + +// How a protobuf field's value is encoded. +enum class WireType : std::uint32_t { + varint = 0, + fixed64 = 1, + length_delimited = 2 +}; + +std::string encode_mapping(); +std::string encode_bin(BinIndex bin, std::uint64_t count); +void append_message(std::string& out, std::uint32_t field, + const std::string& message); +void append_double(std::string& out, std::uint32_t field, double value); +void append_tag(std::string& out, std::uint32_t field, WireType wire_type); +void append_varint(std::string& out, std::uint64_t value); +std::uint32_t zigzag(std::int32_t value); + +} // namespace + +LogBinnedDistribution::LogBinnedDistribution( + LogBinnedDistribution&& other) noexcept { + *this = std::move(other); +} + +LogBinnedDistribution& LogBinnedDistribution::operator=( + LogBinnedDistribution&& other) noexcept { + if (this == &other) return *this; + counts_ = std::exchange(other.counts_, {}); + window_start_ = std::exchange(other.window_start_, 0); + lowest_bin_ = std::exchange(other.lowest_bin_, 0); + bin_range_size_ = std::exchange(other.bin_range_size_, 0); + zero_count_ = std::exchange(other.zero_count_, 0); + return *this; +} + +bool LogBinnedDistribution::record(double value) { + static_assert(std::is_same_v); + const BinIndex bin = log_bins::bin_index(value); + if (bin == log_bins::rejected_value) return false; + + if (bin == log_bins::zero_bin) { + ++zero_count_; + } else { + add_to_bin(bin); + } + return true; +} + +// DDSketch message: mapping = 1, positiveValues = 2, negativeValues = 3, +// zeroCount = 4. Values are never negative, so negativeValues is left out. +std::string LogBinnedDistribution::encode_protobuf() const { + std::string sketch; + append_message(sketch, 1, encode_mapping()); + append_message(sketch, 2, encode_bins()); + if (zero_count_ != 0) { + append_double(sketch, 4, static_cast(zero_count_)); + } + return sketch; +} + +void LogBinnedDistribution::add_to_bin(BinIndex bin) { + const std::uint32_t position = + static_cast(bin) - static_cast(lowest_bin_); + if (position < bin_range_size_) { + ++count_at(bin); + return; + } + extend_range(bin); +} + +// Same rules as libdatadog's LowCollapsingDenseStore. +void LogBinnedDistribution::extend_range(BinIndex bin) { + if (bin_range_size_ == 0) { + start_range(bin); + return; + } + const BinIndex highest = + lowest_bin_ + static_cast(bin_range_size_) - 1; + if (bin < lowest_bin_) { + extend_down(bin, highest); + } else { + extend_up(bin, highest); + } +} + +void LogBinnedDistribution::start_range(BinIndex bin) { + ensure_window_covers(bin, bin); + lowest_bin_ = bin; + bin_range_size_ = 1; + ++count_at(bin); +} + +// The range grows down while it has room. Values below it go to its lowest +// bin. +void LogBinnedDistribution::extend_down(BinIndex bin, BinIndex highest) { + const BinIndex new_lowest = std::max(bin, highest - (max_bins - 1)); + ensure_window_covers(new_lowest, highest); + lowest_bin_ = new_lowest; + bin_range_size_ = static_cast(highest - new_lowest + 1); + ++count_at(new_lowest); +} + +// The range grows up. If it gets too wide, its lowest bins are merged into +// the new lowest bin. +void LogBinnedDistribution::extend_up(BinIndex bin, BinIndex highest) { + const BinIndex new_lowest = std::max(lowest_bin_, bin - (max_bins - 1)); + const BinIndex last_merged = std::min(new_lowest - 1, highest); + const std::uint64_t merged = sum_counts(lowest_bin_, last_merged); + // The window grows before any count changes. If the allocation throws, no + // count is lost. + ensure_window_covers(new_lowest, bin); + // The new window may have dropped some merged bins. Clears the others. + clear_counts(std::max(lowest_bin_, window_start_), last_merged); + lowest_bin_ = new_lowest; + bin_range_size_ = static_cast(bin - new_lowest + 1); + count_at(new_lowest) += merged; + ++count_at(bin); +} + +// Returns the sum of the counts of bins [lowest, highest]. +std::uint64_t LogBinnedDistribution::sum_counts(BinIndex lowest, + BinIndex highest) const { + std::uint64_t sum = 0; + for (BinIndex bin = lowest; bin <= highest; ++bin) sum += count_at(bin); + return sum; +} + +// Sets the counts of bins [lowest, highest] to zero. +void LogBinnedDistribution::clear_counts(BinIndex lowest, BinIndex highest) { + for (BinIndex bin = lowest; bin <= highest; ++bin) count_at(bin) = 0; +} + +// Makes the window cover bins [lowest, highest]. The new window has room on +// both sides, so that the range can grow without moving it each time. +void LogBinnedDistribution::ensure_window_covers(BinIndex lowest, + BinIndex highest) { + const BinIndex window_end = + window_start_ + static_cast(counts_.size()); + if (!counts_.empty() && lowest >= window_start_ && highest < window_end) { + return; + } + + const std::uint32_t needed = static_cast(highest - lowest + 1); + const std::uint32_t size = + std::clamp(2 * needed, min_window_size, max_window_size); + const BinIndex start = + lowest - static_cast((size - needed) / 2); + std::vector counts(size); + const BinIndex copy_start = std::max(window_start_, start); + const BinIndex copy_end = + std::min(window_end, start + static_cast(size)); + for (BinIndex bin = copy_start; bin < copy_end; ++bin) { + counts[static_cast(bin - start)] = count_at(bin); + } + counts_.swap(counts); + window_start_ = start; +} + +std::uint64_t& LogBinnedDistribution::count_at(BinIndex bin) { + return counts_[static_cast(bin - window_start_)]; +} + +std::uint64_t LogBinnedDistribution::count_at(BinIndex bin) const { + return counts_[static_cast(bin - window_start_)]; +} + +// Store message: binCounts = 1 (map), with only the bins that +// are not empty. +std::string LogBinnedDistribution::encode_bins() const { + std::string store; + for (std::uint32_t position = 0; position < bin_range_size_; ++position) { + const BinIndex bin = lowest_bin_ + static_cast(position); + const std::uint64_t count = count_at(bin); + if (count != 0) append_message(store, 1, encode_bin(bin, count)); + } + return store; +} + +namespace { + +// IndexMapping message: gamma = 1, indexOffset = 2. The interpolation is +// NONE, the default, so it is left out. +std::string encode_mapping() { + std::string mapping; + append_double(mapping, 1, log_bins::bin_ratio); + append_double(mapping, 2, log_bins::bin_index_shift); + return mapping; +} + +// Map entry message: key = 1 (sint32), value = 2 (double). +std::string encode_bin(BinIndex bin, std::uint64_t count) { + std::string entry; + append_tag(entry, 1, WireType::varint); + append_varint(entry, zigzag(bin)); + append_double(entry, 2, static_cast(count)); + return entry; +} + +void append_message(std::string& out, std::uint32_t field, + const std::string& message) { + append_tag(out, field, WireType::length_delimited); + append_varint(out, message.size()); + out += message; +} + +void append_double(std::string& out, std::uint32_t field, double value) { + append_tag(out, field, WireType::fixed64); + const std::uint64_t bits = log_bins::to_bits(value); + for (int byte = 0; byte < 8; ++byte) { + out.push_back(static_cast((bits >> (8 * byte)) & 0xff)); + } +} + +void append_tag(std::string& out, std::uint32_t field, WireType wire_type) { + append_varint(out, (field << 3) | static_cast(wire_type)); +} + +void append_varint(std::string& out, std::uint64_t value) { + while (value >= 0x80) { + out.push_back(static_cast((value & 0x7f) | 0x80)); + value >>= 7; + } + out.push_back(static_cast(value)); +} + +std::uint32_t zigzag(std::int32_t value) { + const std::uint32_t shifted = static_cast(value) << 1; + return value < 0 ? ~shifted : shifted; +} + +} // namespace +} // namespace datadog::telemetry diff --git a/src/datadog/telemetry/log_binned_distribution.h b/src/datadog/telemetry/log_binned_distribution.h new file mode 100644 index 00000000..e3fdb439 --- /dev/null +++ b/src/datadog/telemetry/log_binned_distribution.h @@ -0,0 +1,85 @@ +#pragma once + +#include +#include +#include + +namespace datadog::telemetry { + +// A distribution whose bins form a geometric series, compatible with +// DDSketch. Bin i covers [low(i), γ × low(i)), so each bin's upper edge is γ +// times its lower edge. +// +// Every value in bin i is reported as the same bin value x̂(i). It is the +// harmonic mean of the bin's edges: +// +// x̂ = 2 × low × γ × low / (low + γ × low) = low × (1 + α) +// +// This puts x̂ at the same relative error from both edges. So for any value x +// in the bin, |x̂ - x| / x <= α. +// +// Design parameters: +// * The maximum relative error, α = 1/129. That is about 2.1 significant +// digits. The bin ratio follows from it: γ = (1 + α) / (1 - α) = 65/64. +// * Where the bins start. Bin 1 is the bin that holds 1e-9, the smallest value +// the backend's sketches use. So the bin number is +// +// i(x) = floor(log_γ(x) + s), with s = 1 - floor(log_γ(1e-9)) + 0.5 +// +// which gives s = 1338.5. Values between 0 and 1e-9 get bins below 1. +// +// Other properties: +// * Values below DBL_MIN × γ, zero included, are counted apart, in the zero +// count. Negative values, NaN and infinities are rejected. +// * At most 2048 bins are kept: i_max - i_min <= 2047. When a new value would +// go past that, the lowest bins are merged into the lowest bin kept. Values +// below the range go to that lowest bin too. The highest bins are never +// merged. +// * `log` rounds, so about one value in 10^12, right next to a bin edge, goes +// to the neighbouring bin. The worst relative error is then +// α + 4 × 10^-13. This also moves a few bin edges by a double or so between +// C libraries, and from libdatadog's. +// * Not thread-safe: callers must lock. +class LogBinnedDistribution { + public: + LogBinnedDistribution() = default; + LogBinnedDistribution(const LogBinnedDistribution&) = default; + LogBinnedDistribution& operator=(const LogBinnedDistribution&) = default; + // A move leaves the source empty. The implicit move would leave the + // source's range without counts. + LogBinnedDistribution(LogBinnedDistribution&& other) noexcept; + LogBinnedDistribution& operator=(LogBinnedDistribution&& other) noexcept; + + // Returns false if the value is rejected. + bool record(double value); + + // Returns the distribution as a serialized DDSketch protobuf message. The + // bins are in the sparse form (`binCounts`). + std::string encode_protobuf() const; + + private: + // The number of a bin, i(x) above. Same type as log_bins::BinIndex. + using BinIndex = std::int32_t; + + void add_to_bin(BinIndex bin); + void extend_range(BinIndex bin); + void start_range(BinIndex bin); + void extend_down(BinIndex bin, BinIndex highest); + void extend_up(BinIndex bin, BinIndex highest); + std::uint64_t sum_counts(BinIndex lowest, BinIndex highest) const; + void clear_counts(BinIndex lowest, BinIndex highest); + void ensure_window_covers(BinIndex lowest, BinIndex highest); + std::uint64_t& count_at(BinIndex bin); + std::uint64_t count_at(BinIndex bin) const; + std::string encode_bins() const; + + // counts_[k] is the count of bin window_start_ + k. Bins outside the range + // [lowest_bin_, lowest_bin_ + bin_range_size_) are always zero. + std::vector counts_; + BinIndex window_start_ = 0; + BinIndex lowest_bin_ = 0; + std::uint32_t bin_range_size_ = 0; + std::uint64_t zero_count_ = 0; +}; + +} // namespace datadog::telemetry diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 86a47e77..0c65bdae 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -20,6 +20,7 @@ add_executable(tests # telemetry test cases telemetry/test_configuration.cpp + telemetry/test_log_binned_distribution.cpp telemetry/test_telemetry.cpp # test cases diff --git a/test/telemetry/test_log_binned_distribution.cpp b/test/telemetry/test_log_binned_distribution.cpp new file mode 100644 index 00000000..f5c7827f --- /dev/null +++ b/test/telemetry/test_log_binned_distribution.cpp @@ -0,0 +1,469 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "datadog/telemetry/log_bin_index.h" +#include "datadog/telemetry/log_binned_distribution.h" +#include "test.h" + +namespace { + +// While true, operator new throws std::bad_alloc. +bool fail_allocations = false; + +} // namespace + +// Replaced so that a test can make the window allocation fail. +void* operator new(std::size_t size) { + if (fail_allocations) throw std::bad_alloc(); + if (void* memory = std::malloc(size == 0 ? 1 : size)) return memory; + throw std::bad_alloc(); +} + +void* operator new(std::size_t size, const std::nothrow_t&) noexcept { + try { + return ::operator new(size); + } catch (const std::bad_alloc&) { + return nullptr; + } +} + +void operator delete(void* memory) noexcept { std::free(memory); } + +void operator delete(void* memory, std::size_t) noexcept { std::free(memory); } + +void operator delete(void* memory, const std::nothrow_t&) noexcept { + std::free(memory); +} + +using namespace datadog::telemetry; + +#define LOG_BINNED_TEST(x) TEST_CASE(x, "[telemetry][log_binned_distribution]") + +namespace { + +using BinIndex = log_bins::BinIndex; +using Bins = std::map; +using log_bins::from_bits; + +struct DecodedSketch { + double gamma = 0; + double index_offset = 0; + std::uint64_t interpolation = 0; + Bins bins; + bool has_negative_store = false; + Bins negative_bins; + double zero_count = 0; +}; + +DecodedSketch decode_sketch(const std::string& data); + +// The bins expected once `values` are recorded. Each value counts in its own +// bin, but only the 2048 highest bins are kept. Lower values count in the +// lowest bin kept. +Bins expected_bins(const std::vector& values) { + Bins exact; + for (const double value : values) { + const BinIndex bin = log_bins::bin_index(value); + if (bin != log_bins::zero_bin) exact[bin] += 1; + } + if (exact.empty()) return exact; + + const BinIndex lowest_kept = exact.rbegin()->first - 2047; + Bins expected; + for (const auto& [bin, count] : exact) { + expected[std::max(bin, lowest_kept)] += count; + } + return expected; +} + +// A value in the middle of `bin`, half a bin from both edges. Bin 1338 holds +// 1.0. +double value_in_bin(BinIndex bin) { + return std::pow(log_bins::bin_ratio, bin - 1338); +} + +Bins recorded_bins(const std::vector& bins) { + LogBinnedDistribution distribution; + for (const BinIndex bin : bins) distribution.record(value_in_bin(bin)); + return decode_sketch(distribution.encode_protobuf()).bins; +} + +void check_bins(const std::vector& values) { + LogBinnedDistribution distribution; + for (const double value : values) distribution.record(value); + const double zero_count = + static_cast(std::count(values.begin(), values.end(), 0.0)); + + const DecodedSketch decoded = decode_sketch(distribution.encode_protobuf()); + CHECK(decoded.bins == expected_bins(values)); + CHECK(decoded.zero_count == zero_count); +} + +std::vector log_uniform(std::size_t count, double lowest, + double highest, std::uint64_t seed) { + std::mt19937_64 generator(seed); + std::uniform_real_distribution exponent(std::log(lowest), + std::log(highest)); + std::vector values(count); + for (double& value : values) value = std::exp(exponent(generator)); + return values; +} + +} // namespace + +LOG_BINNED_TEST("mapping constants follow libdatadog's formulas") { + const double relative_accuracy = 0.007751937984496124; + CHECK((1 + relative_accuracy) / (1 - relative_accuracy) == + log_bins::bin_ratio); + + const double log_ratio = std::log(log_bins::bin_ratio); + CHECK((1 - std::floor(std::log(1e-9) / log_ratio)) + 0.5 == + log_bins::bin_index_shift); + + const double multiplier = 1 / log_ratio; + const double lowest_bin = std::numeric_limits::min(); + const double int32_limit = + std::exp((lowest_bin - log_bins::bin_index_shift) / multiplier + 1.0); + CHECK(std::max(std::numeric_limits::min() * log_bins::bin_ratio, + int32_limit) == log_bins::zero_threshold); +} + +LOG_BINNED_TEST("bin index of special values") { + const double infinity = std::numeric_limits::infinity(); + const std::vector> cases{ + {std::nan(""), log_bins::rejected_value}, + {infinity, log_bins::rejected_value}, + {-infinity, log_bins::rejected_value}, + {-1.0, log_bins::rejected_value}, + {-std::numeric_limits::min(), log_bins::rejected_value}, + {0.0, log_bins::zero_bin}, + {-0.0, log_bins::zero_bin}, + {std::numeric_limits::denorm_min(), log_bins::zero_bin}, + {std::numeric_limits::min(), log_bins::zero_bin}, + {std::nextafter(log_bins::zero_threshold, 0.0), log_bins::zero_bin}, + {log_bins::zero_threshold, -44352}, + {1e-9, 1}, + {1.0, 1338}, + {1000.0, 1784}, + {std::numeric_limits::max(), 47118}, + }; + for (const auto& [value, expected_bin] : cases) { + INFO("value " << value); + CHECK(log_bins::bin_index(value) == expected_bin); + } +} + +LOG_BINNED_TEST("bin index of values far from an edge is exact") { + // Exact bins, computed with 300-bit arithmetic (mpmath): the floor of + // ln(x) / ln(65/64) + 1338.5. Each value is at least 0.04 bins from an edge. + const std::vector> cases{ + {1e-300, -43216}, {5e-300, -43112}, {1e-20, -1632}, {3.3e-15, -813}, + {1e-9, 1}, {0.001, 892}, {0.37, 1274}, {0.5, 1293}, + {1.0, 1338}, {2.5, 1397}, {3.0, 1409}, {123.456, 1649}, + {1000.0, 1784}, {65536.0, 2053}, {1e9, 2675}, {1e12, 3120}, + {1e18, 4011}, {1e25, 5051}, {1e100, 16189}, {1e300, 45892}, + }; + for (const auto& [value, expected_bin] : cases) { + INFO("value " << value); + CHECK(log_bins::bin_index(value) == expected_bin); + } +} + +LOG_BINNED_TEST("bin index rounds the multiplication and the addition once") { + // ln(x) / ln(65/64) + 1338.5 is 3253.99999999999995516 for this x, so the + // exact bin is 3253. Rounding the multiplication first would round the + // result up to 3254. + const double value = 7'903'045'517'381.0; + CHECK(log_bins::bin_index(value) == 3253); +} + +LOG_BINNED_TEST("a move takes the values and empties the source") { + static_assert(std::is_nothrow_move_constructible_v); + static_assert(std::is_nothrow_move_assignable_v); + LogBinnedDistribution source; + source.record(0.0); + source.record(1.0); + source.record(1000.0); + const std::string encoded = source.encode_protobuf(); + + SECTION("move construction") { + const LogBinnedDistribution target(std::move(source)); + CHECK(target.encode_protobuf() == encoded); + } + SECTION("move assignment") { + LogBinnedDistribution target; + target.record(5.0); + target = std::move(source); + CHECK(target.encode_protobuf() == encoded); + } + CHECK(source.encode_protobuf() == LogBinnedDistribution().encode_protobuf()); + CHECK(source.record(1000.0)); + LogBinnedDistribution expected; + expected.record(1000.0); + CHECK(source.encode_protobuf() == expected.encode_protobuf()); +} + +LOG_BINNED_TEST("a self-move keeps the values") { + LogBinnedDistribution distribution; + distribution.record(1.0); + const std::string encoded = distribution.encode_protobuf(); + LogBinnedDistribution& same = distribution; + distribution = std::move(same); + CHECK(distribution.encode_protobuf() == encoded); +} + +LOG_BINNED_TEST("record keeps old counts if the window allocation fails") { + LogBinnedDistribution distribution; + distribution.record(value_in_bin(0)); + distribution.record(value_in_bin(2047)); + + // Bin 3100 merges bins 0 to 1052, and needs a new window. + fail_allocations = true; + bool threw = false; + try { + distribution.record(value_in_bin(3100)); + } catch (const std::bad_alloc&) { + threw = true; + } + fail_allocations = false; + + CHECK(threw); + CHECK(decode_sketch(distribution.encode_protobuf()).bins == + Bins{{0, 1}, {2047, 1}}); +} + +LOG_BINNED_TEST("record rejects invalid values") { + LogBinnedDistribution distribution; + CHECK_FALSE(distribution.record(std::nan(""))); + CHECK_FALSE(distribution.record(-1.0)); + CHECK_FALSE(distribution.record(std::numeric_limits::infinity())); + CHECK(distribution.record(0.0)); + CHECK(distribution.record(-0.0)); + + const DecodedSketch decoded = decode_sketch(distribution.encode_protobuf()); + CHECK(decoded.bins.empty()); + CHECK(decoded.zero_count == 2); +} + +LOG_BINNED_TEST("encoding of an empty distribution") { + const LogBinnedDistribution distribution; + const unsigned char expected[] = { + 0x0a, 0x12, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0xf0, 0x3f, + 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0xea, 0x94, 0x40, 0x12, 0x00}; + CHECK(distribution.encode_protobuf() == + std::string(reinterpret_cast(expected), sizeof expected)); +} + +LOG_BINNED_TEST("encoding of one value") { + LogBinnedDistribution distribution; + distribution.record(1.0); + const unsigned char expected[] = { + 0x0a, 0x12, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0xf0, 0x3f, 0x11, + 0x00, 0x00, 0x00, 0x00, 0x00, 0xea, 0x94, 0x40, 0x12, 0x0e, 0x0a, 0x0c, + 0x08, 0xf4, 0x14, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f}; + CHECK(distribution.encode_protobuf() == + std::string(reinterpret_cast(expected), sizeof expected)); + + const DecodedSketch decoded = decode_sketch(distribution.encode_protobuf()); + CHECK(decoded.gamma == 65.0 / 64.0); + CHECK(decoded.index_offset == 1338.5); + CHECK(decoded.interpolation == 0); + CHECK(decoded.bins == Bins{{1338, 1.0}}); + CHECK_FALSE(decoded.has_negative_store); +} + +LOG_BINNED_TEST("encoding of one value in a negative bin") { + // Bin -147 holds values around 1e-10. Its key is zigzag(-147) = 293. + LogBinnedDistribution distribution; + distribution.record(value_in_bin(-147)); + const unsigned char expected[] = { + 0x0a, 0x12, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0xf0, 0x3f, 0x11, + 0x00, 0x00, 0x00, 0x00, 0x00, 0xea, 0x94, 0x40, 0x12, 0x0e, 0x0a, 0x0c, + 0x08, 0xa5, 0x02, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f}; + CHECK(distribution.encode_protobuf() == + std::string(reinterpret_cast(expected), sizeof expected)); + CHECK(decode_sketch(distribution.encode_protobuf()).bins == + Bins{{-147, 1.0}}); +} + +LOG_BINNED_TEST("the store keeps the 2048 highest bins") { + SECTION("a range of 2048 bins keeps every bin") { + CHECK(recorded_bins({1000, 3047}) == Bins{{1000, 1}, {3047, 1}}); + } + SECTION("a higher value merges the lowest bins into the lowest bin kept") { + CHECK(recorded_bins({1000, 1000, 1500, 3048}) == + Bins{{1001, 2}, {1500, 1}, {3048, 1}}); + CHECK(recorded_bins({1000, 1500, 9000}) == Bins{{6953, 2}, {9000, 1}}); + } + SECTION("a lower value goes to the lowest bin kept") { + CHECK(recorded_bins({3047, 1000, 999, 10}) == Bins{{1000, 3}, {3047, 1}}); + CHECK(recorded_bins({3047, 500}) == Bins{{1000, 1}, {3047, 1}}); + CHECK(recorded_bins({1000, 3048, 5}) == Bins{{1001, 2}, {3048, 1}}); + } +} + +LOG_BINNED_TEST("bins of many values") { + SECTION("narrow durations") { + check_bins(log_uniform(100'000, 100, 10'000, 3)); + } + SECTION("wide range, which collapses the lowest bins") { + check_bins(log_uniform(100'000, 1e-12, 1e22, 4)); + } + SECTION("values that only increase") { + std::vector values = log_uniform(20'000, 1e-9, 1e20, 5); + std::sort(values.begin(), values.end()); + check_bins(values); + } + SECTION("values that only decrease") { + std::vector values = log_uniform(20'000, 1e-9, 1e20, 6); + std::sort(values.begin(), values.end(), std::greater()); + check_bins(values); + } + SECTION("values alternating between both ends") { + std::vector values; + for (int step = 0; step < 5'000; ++step) { + values.push_back(1e-6 * (1 + step % 7)); + values.push_back(1e15 * (1 + step % 5)); + } + check_bins(values); + } + SECTION("low values, then high ones, then low ones again") { + std::vector values = log_uniform(5'000, 1, 100, 7); + const std::vector high = log_uniform(5'000, 1e14, 1e16, 8); + const std::vector low = log_uniform(5'000, 1e-3, 10, 9); + values.insert(values.end(), high.begin(), high.end()); + values.insert(values.end(), low.begin(), low.end()); + check_bins(values); + } + SECTION("zeros and fractions mixed") { + std::vector values = log_uniform(50'000, 1e-4, 1, 10); + for (std::size_t index = 0; index < values.size(); index += 10) { + values[index] = 0; + } + check_bins(values); + } +} + +namespace { + +// A minimal protobuf reader, for the messages of a DDSketch. +class ProtobufReader { + public: + explicit ProtobufReader(const std::string& data) : data_(data) {} + + bool done() const { return position_ >= data_.size(); } + + std::uint64_t read_varint() { + std::uint64_t value = 0; + for (int shift = 0;; shift += 7) { + const unsigned char byte = + static_cast(data_.at(position_++)); + value |= std::uint64_t{byte & 0x7fu} << shift; + if ((byte & 0x80) == 0) return value; + } + } + + double read_double() { + std::uint64_t bits = 0; + for (int byte = 0; byte < 8; ++byte) { + const unsigned char value = + static_cast(data_.at(position_++)); + bits |= std::uint64_t{value} << (8 * byte); + } + return from_bits(bits); + } + + std::string read_bytes() { + const std::size_t length = read_varint(); + REQUIRE(position_ + length <= data_.size()); + std::string bytes = data_.substr(position_, length); + position_ += length; + return bytes; + } + + private: + const std::string& data_; + std::size_t position_ = 0; +}; + +std::int32_t unzigzag(std::uint64_t value) { + const std::uint32_t low = static_cast(value); + return static_cast((low >> 1) ^ (0u - (low & 1))); +} + +void decode_bin(const std::string& data, Bins& bins) { + ProtobufReader reader(data); + BinIndex bin = 0; + double count = 0; + while (!reader.done()) { + const std::uint64_t tag = reader.read_varint(); + if (tag == ((1 << 3) | 0)) { + bin = unzigzag(reader.read_varint()); + } else if (tag == ((2 << 3) | 1)) { + count = reader.read_double(); + } else { + FAIL("unexpected field in a bin entry: " << tag); + } + } + bins[bin] += count; +} + +Bins decode_store(const std::string& data) { + ProtobufReader reader(data); + Bins bins; + while (!reader.done()) { + const std::uint64_t tag = reader.read_varint(); + REQUIRE(tag == ((1 << 3) | 2)); + decode_bin(reader.read_bytes(), bins); + } + return bins; +} + +void decode_mapping(const std::string& data, DecodedSketch& sketch) { + ProtobufReader reader(data); + while (!reader.done()) { + const std::uint64_t tag = reader.read_varint(); + if (tag == ((1 << 3) | 1)) { + sketch.gamma = reader.read_double(); + } else if (tag == ((2 << 3) | 1)) { + sketch.index_offset = reader.read_double(); + } else if (tag == ((3 << 3) | 0)) { + sketch.interpolation = reader.read_varint(); + } else { + FAIL("unexpected field in the mapping: " << tag); + } + } +} + +DecodedSketch decode_sketch(const std::string& data) { + ProtobufReader reader(data); + DecodedSketch sketch; + while (!reader.done()) { + const std::uint64_t tag = reader.read_varint(); + if (tag == ((1 << 3) | 2)) { + decode_mapping(reader.read_bytes(), sketch); + } else if (tag == ((2 << 3) | 2)) { + sketch.bins = decode_store(reader.read_bytes()); + } else if (tag == ((3 << 3) | 2)) { + sketch.has_negative_store = true; + sketch.negative_bins = decode_store(reader.read_bytes()); + } else if (tag == ((4 << 3) | 1)) { + sketch.zero_count = reader.read_double(); + } else { + FAIL("unexpected field in the sketch: " << tag); + } + } + return sketch; +} + +} // namespace