From 1d99d30a39d55aa5026d61956c1f2d3901fec7ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustavo=20Andr=C3=A9=20dos=20Santos=20Lopes?= Date: Fri, 13 Nov 2026 19:18:21 +0000 Subject: [PATCH 1/2] Add a metric handle API for telemetry A metric is registered once with typed tags, so recording a point builds, copies and hashes no tag strings. Nothing uses the handles yet. --- BUILD.bazel | 2 + CMakeLists.txt | 2 + include/datadog/telemetry/metric_handle.h | 472 ++++++++++++++++++++++ include/datadog/telemetry/metrics.h | 9 + src/datadog/telemetry/metric_handle.cpp | 163 ++++++++ test/CMakeLists.txt | 1 + test/telemetry/test_metric_handle.cpp | 165 ++++++++ 7 files changed, 814 insertions(+) create mode 100644 include/datadog/telemetry/metric_handle.h create mode 100644 src/datadog/telemetry/metric_handle.cpp create mode 100644 test/telemetry/test_metric_handle.cpp diff --git a/BUILD.bazel b/BUILD.bazel index a869a1a2f..52ae28852 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -80,6 +80,7 @@ cc_library( "src/datadog/telemetry/log_binned_distribution.cpp", "src/datadog/telemetry/log_binned_distribution.h", "src/datadog/telemetry/metric_context.h", + "src/datadog/telemetry/metric_handle.cpp", "src/datadog/telemetry/telemetry.cpp", "src/datadog/telemetry/telemetry_impl.cpp", "src/datadog/telemetry/telemetry_impl.h", @@ -151,6 +152,7 @@ cc_library( "include/datadog/span_sampler_config.h", "include/datadog/string_view.h", "include/datadog/telemetry/configuration.h", + "include/datadog/telemetry/metric_handle.h", "include/datadog/telemetry/metrics.h", "include/datadog/telemetry/product.h", "include/datadog/telemetry/telemetry.h", diff --git a/CMakeLists.txt b/CMakeLists.txt index f459c3f1d..04df32cbe 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -135,6 +135,7 @@ target_sources(dd-trace-cpp-objects include/datadog/remote_config/listener.h include/datadog/remote_config/product.h include/datadog/telemetry/configuration.h + include/datadog/telemetry/metric_handle.h include/datadog/telemetry/metrics.h include/datadog/telemetry/product.h include/datadog/telemetry/telemetry.h @@ -185,6 +186,7 @@ target_sources(dd-trace-cpp-objects src/datadog/telemetry/configuration.cpp src/datadog/telemetry/log_bin_index.cpp src/datadog/telemetry/log_binned_distribution.cpp + src/datadog/telemetry/metric_handle.cpp src/datadog/telemetry/telemetry.cpp src/datadog/telemetry/telemetry_impl.cpp src/datadog/baggage.cpp diff --git a/include/datadog/telemetry/metric_handle.h b/include/datadog/telemetry/metric_handle.h new file mode 100644 index 000000000..616c6ba7e --- /dev/null +++ b/include/datadog/telemetry/metric_handle.h @@ -0,0 +1,472 @@ +#pragma once + +// Metrics registered once with all their tags. +// +// A struct describes the tags. Its static `tag_fields()` returns a std::tuple +// of tag() calls, which bind each field to a tag name. String tags come in two +// kinds: +// * values known in advance: an enum field. `tag_value_names(Enum{})`, found +// by argument-dependent lookup, returns a std::array with one name per +// value, in order. +// * values not known in advance: a TagString field. +// +// Each tag value is identified by a number. The sequence of tags for a metric +// is identified by a 64-bit number (the `SeriesId`) resulting from placing +// these indiviual tag values inside it. This scheme sets an upper bound on the +// number of tags a metric can have and the more values a tag can have, the +// more space a tag takes. In practice, the set of tag values is small, because +// cardinality tags are rejected for storage out of performance concerns. +// +// How the classes fit together (A --> B: A uses B; A -|> B: A derives from B): +// +// MetricRegistry +// | holds weak_ptr>, one list per metric kind +// | creates (counter(), rate(), distribution()) +// v +// MetricHandle -|> MetricBase +// | (CounterHandle, RateHandle, | owns tags_, strides_, +// | DistributionHandle) | fixed_tags_ +// | | +// | record(Tags, value) v +// | take_series() vector> -|> NamedCodec +// v -|> OptionalCodec +// Store -|> StringCodec +// | SeriesIntegers (Counter, Rate) | +// | SeriesSketches (Distribution) | +// | keeps a LogBinnedDistribution per series v +// v TagString +// SeriesId -> Value (interned string id) +// +// The Tags struct's tag_fields() returns TagField objects, built by tag(). +// Each one carries the TagCodec of one field. +// +// test/telemetry/test_metric_handle.cpp has examples. +// +// Telemetry does not collect these handles yet. + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace datadog::telemetry { + +// A tag value not known in advance, such as a version. Creating one stores +// the string in a global table; copying it copies a small number. The table +// holds at most 65535 strings. Later new strings all read as "other". +class TagString { + public: + static constexpr std::uint64_t id_count = std::uint64_t{1} << 16; + + // The empty string. + TagString() = default; + explicit TagString(tracing::StringView value); + + std::uint16_t id() const { return id_; } + std::string value() const; + + private: + std::uint16_t id_ = 0; +}; + +namespace details { + +// Identifies one series of a metric: one combination of its tag values. Each +// tag's value is multiplied by the tag's stride, and the results added. +using SeriesId = std::uint64_t; + +// One tag of a metric: reads the tag's field from a tag struct, and renders +// the tag's values. The tag struct's type is hidden, so that MetricBase does +// not depend on it. +class TagCodec { + public: + virtual ~TagCodec() = default; + // The value of the tag's field in `*tags`, as a number. `tags` points to the + // tag struct that the codec was made for. + virtual std::uint64_t read(const void* tags) const = 0; + // "name:value", or an empty string if the tag is not sent. + virtual std::string render(std::uint64_t value) const = 0; +}; + +std::string interned_string(std::uint64_t id); +// "name:value_name" for each value name. +std::vector render_names( + const std::string& name, const std::vector& value_names); + +// A bool or enum field. Value i renders as rendered[i]. +template +class NamedCodec final : public TagCodec { + public: + NamedCodec(Field Tags::*field, std::vector rendered) + : field_(field), rendered_(std::move(rendered)) {} + + std::uint64_t read(const void* tags) const override { + return static_cast(static_cast(tags)->*field_); + } + + std::string render(std::uint64_t value) const override { + return rendered_[value]; + } + + private: + Field Tags::*field_; + std::vector rendered_; +}; + +// An optional enum field. Value 0 is an empty field, which is not sent. Value +// i + 1 renders as rendered[i]. +template +class OptionalCodec final : public TagCodec { + public: + OptionalCodec(tracing::Optional Tags::*field, + std::vector rendered) + : field_(field), rendered_(std::move(rendered)) {} + + std::uint64_t read(const void* tags) const override { + const auto& value = static_cast(tags)->*field_; + return value ? static_cast(*value) + 1 : 0; + } + + std::string render(std::uint64_t value) const override { + return value == 0 ? std::string() : rendered_[value - 1]; + } + + private: + tracing::Optional Tags::*field_; + std::vector rendered_; +}; + +// A TagString field. The value is the string's id. +template +class StringCodec final : public TagCodec { + public: + StringCodec(TagString Tags::*field, std::string name) + : field_(field), name_(std::move(name)) {} + + std::uint64_t read(const void* tags) const override { + return (static_cast(tags)->*field_).id(); + } + + std::string render(std::uint64_t value) const override { + return name_ + ":" + interned_string(value); + } + + private: + TagString Tags::*field_; + std::string name_; +}; + +template +constexpr std::uint64_t enum_value_count() { + return std::tuple_size< + std::decay_t>::value; +} + +template +std::vector enum_value_names() { + std::vector names; + for (const char* name : tag_value_names(Enum{})) names.emplace_back(name); + return names; +} + +// One tag of a metric. Build it with tag(). The tag's values are numbered +// from 0 to ValueCount - 1. `Field` is the type of the field in `Tags`. +template +struct TagField { + using TagStruct = Tags; + using FieldType = Field; + static constexpr std::uint64_t value_count = ValueCount; + std::unique_ptr codec; +}; + +// True if each combination of the fields' values has its own SeriesId. +template +constexpr bool fits_in_series_id(const std::tuple*) { + std::uint64_t combinations = 1; + for (std::uint64_t count : + std::initializer_list{Fields::value_count...}) { + if (count == 0 || + combinations > std::numeric_limits::max() / count) { + return false; + } + combinations *= count; + } + return true; +} + +// Tags of a metric that has only fixed tags. +struct NoTags { + static std::tuple<> tag_fields() { return {}; } +}; + +// One series of a metric: the metric, the series' tags and its value. +template +struct MetricSeries { + Metric metric; + std::vector tags; + typename Metric::Value value; +}; + +class MetricRegistry; + +// The integer of each series. Counters add the values recorded for a series; +// rates keep the last one. Thread-safe. +template +class SeriesIntegers { + public: + using Value = std::uint64_t; + + void record(SeriesId series, std::uint64_t value) { + std::lock_guard lock(mutex_); + Value& current = values_[series]; + current = keep_last ? value : current + value; + } + + std::vector> take() { + std::unordered_map taken; + { + std::lock_guard lock(mutex_); + taken.swap(values_); + } + return {taken.begin(), taken.end()}; + } + + private: + std::mutex mutex_; + std::unordered_map values_; +}; + +// The sketch of each series. Recording adds the value to it. Thread-safe. +class SeriesSketches { + public: + using Value = EncodedSketch; + + SeriesSketches(); + ~SeriesSketches(); + + void record(SeriesId series, std::uint64_t value); + std::vector> take(); + + private: + struct Impl; + std::unique_ptr impl_; +}; + +// Everything about a metric handle that depends neither on its Tags type nor +// on how it stores its values. +template +class MetricBase { + public: + // Removes the series recorded so far, and appends them to `series`. + virtual void take_series(std::vector>& series) = 0; + + protected: + // Handles are not deleted through MetricBase. + ~MetricBase() = default; + + MetricBase(Metric metric, std::vector fixed_tags, + std::vector value_counts, + std::vector> tags); + + const Metric& metric() const { return metric_; } + // The series of the tag struct `*tags`. Empty if a value is out of range. + tracing::Optional series_id(const void* tags) const; + // The fixed tags, then the tags of series `id` that are sent. + std::vector series_tags(SeriesId id) const; + + private: + Metric metric_; + std::vector fixed_tags_; + std::vector value_counts_; + std::vector> tags_; + std::vector strides_; +}; + +// A metric registered with all its tags. Only a MetricRegistry creates them. +// `Store` keeps the value of each series: record() combines a new value into +// it, and take() removes them. record() is thread-safe. +template +class MetricHandle final : public MetricBase { + static_assert( + fits_in_series_id(static_cast(nullptr)), + "Too many combinations of tag values for a 64-bit SeriesId"); + static_assert( + std::is_same_v() + .take())::value_type::second_type, + typename Metric::Value>, + "The store's values must have the metric's Value type"); + + public: + void record(const Tags& tags, std::uint64_t value) { + if (const auto series = this->series_id(&tags)) { + store_.record(*series, value); + } + } + + void take_series(std::vector>& series) override { + for (auto& [id, value] : store_.take()) { + series.push_back( + {this->metric(), this->series_tags(id), std::move(value)}); + } + } + + private: + friend class MetricRegistry; + + MetricHandle(Metric metric, std::vector fixed_tags) + : MetricHandle(std::move(metric), std::move(fixed_tags), + Tags::tag_fields()) {} + + // The codecs read `Tags` structs, so every field must be one of Tags. + template + MetricHandle(Metric metric, std::vector fixed_tags, + std::tuple fields) + : MetricBase(std::move(metric), std::move(fixed_tags), + {Fields::value_count...}, + codecs(std::move(fields))) { + static_assert((std::is_same_v && ...), + "tag_fields() must only bind fields of its own struct"); + } + + template + static std::vector> codecs( + std::tuple fields) { + std::vector> codecs; + std::apply( + [&codecs](auto&... field) { + (codecs.push_back(std::move(field.codec)), ...); + }, + fields); + return codecs; + } + + Store store_; +}; + +} // namespace details + +template +details::TagField tag(const std::string& name, + bool Tags::*field) { + return {std::make_unique>( + field, details::render_names(name, {"false", "true"}))}; +} + +template >> +details::TagField(), Enum> tag( + const std::string& name, Enum Tags::*field) { + return {std::make_unique>( + field, details::render_names(name, details::enum_value_names()))}; +} + +// An empty field is not sent. +template +details::TagField() + 1, + tracing::Optional> +tag(const std::string& name, tracing::Optional Tags::*field) { + return {std::make_unique>( + field, details::render_names(name, details::enum_value_names()))}; +} + +template +details::TagField tag( + const std::string& name, TagString Tags::*field) { + return {std::make_unique>(field, name)}; +} + +// Recording a value adds it to the series' count. +template +using CounterHandle = + details::MetricHandle>; + +// Recording a value replaces the series' rate. +template +using RateHandle = + details::MetricHandle>; + +// Recording a value adds it to the series' sketch. +template +using DistributionHandle = + details::MetricHandle; + +namespace details { + +// Creates metric handles, and takes the series of those still in use. The +// registry holds only weak references: a handle that its caller drops is +// forgotten, with the values it recorded since the last take. Creating and +// taking lock the registry; recording does not. +class MetricRegistry { + public: + template + std::shared_ptr> counter( + Counter metric, std::vector fixed_tags = {}) { + return add>(std::move(metric), std::move(fixed_tags)); + } + + template + std::shared_ptr> rate( + Rate metric, std::vector fixed_tags = {}) { + return add>(std::move(metric), std::move(fixed_tags)); + } + + template + std::shared_ptr> distribution( + Distribution metric, std::vector fixed_tags = {}) { + return add>(std::move(metric), + std::move(fixed_tags)); + } + + // Removes and returns the series that the handles of `Metric` recorded + // since the last call. Forgets the handles that were dropped. + template + std::vector> take() { + std::vector> series; + std::lock_guard lock(mutex_); + auto& handles = std::get>(handles_); + for (const auto& weak_handle : handles) { + if (const auto handle = weak_handle.lock()) handle->take_series(series); + } + handles.erase(std::remove_if(handles.begin(), handles.end(), + [](const auto& weak_handle) { + return weak_handle.expired(); + }), + handles.end()); + return series; + } + + private: + template + using Handles = std::vector>>; + + template + std::shared_ptr add(Metric metric, + std::vector fixed_tags) { + std::shared_ptr handle( + new Handle(std::move(metric), std::move(fixed_tags))); + std::lock_guard lock(mutex_); + std::get>(handles_).push_back(handle); + return handle; + } + + std::mutex mutex_; + std::tuple, Handles, Handles> handles_; +}; + +} // namespace details +} // namespace datadog::telemetry diff --git a/include/datadog/telemetry/metrics.h b/include/datadog/telemetry/metrics.h index 3cca54e3c..d83beeb4f 100644 --- a/include/datadog/telemetry/metrics.h +++ b/include/datadog/telemetry/metrics.h @@ -1,6 +1,8 @@ #pragma once +#include #include +#include namespace datadog { namespace telemetry { @@ -9,11 +11,18 @@ namespace details { enum class MetricType : char { counter, rate, distribution }; } +/// A DDSketch protobuf message, as bytes. +using EncodedSketch = std::string; + /// TODO: pre-compute hash? template struct Metric final { /// The type of the metric. static constexpr details::MetricType type = T; + /// The value of one series: a count or a rate, or the sketch of a + /// distribution. + using Value = std::conditional_t; /// The name of the metric that will be published. A transformation occurs /// based on the name and whether it is "common" or "language-specific" when /// it is recorded. diff --git a/src/datadog/telemetry/metric_handle.cpp b/src/datadog/telemetry/metric_handle.cpp new file mode 100644 index 000000000..067af7d6f --- /dev/null +++ b/src/datadog/telemetry/metric_handle.cpp @@ -0,0 +1,163 @@ +#include + +#include "log_binned_distribution.h" + +namespace datadog::telemetry { +namespace { + +// Id of every new string once the table is full. +constexpr std::uint16_t overflow_id = 0xFFFF; + +// The strings of TagString values. Id 0 is the empty string. +class StringTable { + public: + static StringTable& instance() { + static StringTable table; + return table; + } + + std::uint16_t intern(tracing::StringView value); + std::string value(std::uint16_t id); + + private: + StringTable() { add(""); } + std::uint16_t add(const std::string& value); + + std::mutex mutex_; + std::vector strings_; + std::unordered_map ids_; +}; + +std::vector series_id_strides( + const std::vector& value_counts); + +} // namespace + +TagString::TagString(tracing::StringView value) + : id_(StringTable::instance().intern(value)) {} + +std::string TagString::value() const { return details::interned_string(id_); } + +namespace details { + +std::string interned_string(std::uint64_t id) { + return StringTable::instance().value(static_cast(id)); +} + +std::vector render_names( + const std::string& name, const std::vector& value_names) { + std::vector rendered; + for (const std::string& value_name : value_names) { + rendered.push_back(name + ":" + value_name); + } + return rendered; +} + +template +MetricBase::MetricBase( + Metric metric, std::vector fixed_tags, + std::vector value_counts, + std::vector> tags) + : metric_(std::move(metric)), + fixed_tags_(std::move(fixed_tags)), + value_counts_(std::move(value_counts)), + tags_(std::move(tags)), + strides_(series_id_strides(value_counts_)) {} + +template +tracing::Optional MetricBase::series_id( + const void* tags) const { + SeriesId id = 0; + for (std::size_t index = 0; index < tags_.size(); ++index) { + const std::uint64_t value = tags_[index]->read(tags); + if (value >= value_counts_[index]) return tracing::nullopt; + id += value * strides_[index]; + } + return id; +} + +template +std::vector MetricBase::series_tags(SeriesId id) const { + std::vector tags = fixed_tags_; + for (std::size_t index = 0; index < tags_.size(); ++index) { + const std::uint64_t value = id / strides_[index] % value_counts_[index]; + std::string rendered = tags_[index]->render(value); + if (!rendered.empty()) tags.push_back(std::move(rendered)); + } + return tags; +} + +template class MetricBase; +template class MetricBase; +template class MetricBase; + +struct SeriesSketches::Impl { + std::mutex mutex; + std::unordered_map sketches; +}; + +SeriesSketches::SeriesSketches() : impl_(std::make_unique()) {} + +SeriesSketches::~SeriesSketches() = default; + +void SeriesSketches::record(SeriesId series, std::uint64_t value) { + std::lock_guard lock(impl_->mutex); + impl_->sketches[series].record(static_cast(value)); +} + +std::vector> SeriesSketches::take() { + std::unordered_map taken; + { + std::lock_guard lock(impl_->mutex); + taken.swap(impl_->sketches); + } + std::vector> encoded; + for (const auto& [series, sketch] : taken) { + encoded.emplace_back(series, sketch.encode_protobuf()); + } + return encoded; +} + +} // namespace details + +namespace { + +std::uint16_t StringTable::intern(tracing::StringView value) { + const std::string key(value); + std::lock_guard lock(mutex_); + if (const auto found = ids_.find(key); found != ids_.end()) { + return found->second; + } + if (strings_.size() >= overflow_id) return overflow_id; + return add(key); +} + +std::string StringTable::value(std::uint16_t id) { + if (id == overflow_id) return "other"; + std::lock_guard lock(mutex_); + return id < strings_.size() ? strings_[id] : std::string(); +} + +// Expects the lock to be held, or the table to be under construction. +std::uint16_t StringTable::add(const std::string& value) { + const auto id = static_cast(strings_.size()); + strings_.push_back(value); + ids_.emplace(value, id); + return id; +} + +// The last tag has stride 1. Each other tag's stride is the number of +// combinations of the values of the tags after it. +std::vector series_id_strides( + const std::vector& value_counts) { + std::vector strides(value_counts.size()); + std::uint64_t stride = 1; + for (std::size_t index = value_counts.size(); index-- > 0;) { + strides[index] = stride; + stride *= value_counts[index]; + } + return strides; +} + +} // namespace +} // namespace datadog::telemetry diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 27676e5ba..af4d025aa 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -21,6 +21,7 @@ add_executable(tests # telemetry test cases telemetry/test_configuration.cpp telemetry/test_log_binned_distribution.cpp + telemetry/test_metric_handle.cpp telemetry/test_telemetry.cpp # test cases diff --git a/test/telemetry/test_metric_handle.cpp b/test/telemetry/test_metric_handle.cpp new file mode 100644 index 000000000..599c69403 --- /dev/null +++ b/test/telemetry/test_metric_handle.cpp @@ -0,0 +1,165 @@ +#include + +#include + +#include "datadog/telemetry/log_binned_distribution.h" +#include "test.h" + +using namespace datadog::telemetry; +using datadog::tracing::Optional; + +#define METRIC_HANDLE_TEST(x) TEST_CASE(x, "[telemetry][metric_handle]") + +namespace { + +enum class Step { request_first, request_body }; + +std::array tag_value_names(Step) { + return {"req.first", "req.body"}; +} + +struct RequestTags { + TagString rules_version; + bool blocked = false; + Optional step; + + static auto tag_fields() { + using Self = RequestTags; + return std::tuple{tag("rules_version", &Self::rules_version), + tag("blocked", &Self::blocked), tag("step", &Self::step)}; + } +}; + +// Only the first two values have names. +enum class Size { small, large, unnamed }; + +std::array tag_value_names(Size) { return {"small", "large"}; } + +struct SizeTags { + Size size = Size::small; + + static auto tag_fields() { return std::tuple{tag("size", &SizeTags::size)}; } +}; + +struct TooManyTags { + TagString first, second, third, fourth, fifth; + + static auto tag_fields() { + using Self = TooManyTags; + return std::tuple{tag("first", &Self::first), tag("second", &Self::second), + tag("third", &Self::third), tag("fourth", &Self::fourth), + tag("fifth", &Self::fifth)}; + } +}; + +// A handle for TooManyTags would not compile: 65536^5 combinations do not fit +// in a 64-bit series id. +static_assert(!details::fits_in_series_id( + static_cast(nullptr))); +static_assert(details::fits_in_series_id( + static_cast(nullptr))); + +template +std::map, typename Metric::Value> by_tags( + const std::vector>& series) { + std::map, typename Metric::Value> result; + for (const auto& one_series : series) { + result[one_series.tags] = one_series.value; + } + return result; +} + +std::string sketch_of(std::initializer_list values) { + LogBinnedDistribution sketch; + for (double value : values) sketch.record(value); + return sketch.encode_protobuf(); +} + +} // namespace + +METRIC_HANDLE_TEST("a counter without tags has one series") { + details::MetricRegistry registry; + const auto requests = registry.counter({"requests", "tracers", true}, + {"integration_name:datadog"}); + requests->record({}, 1); + requests->record({}, 1); + + const auto series = registry.take(); + REQUIRE(series.size() == 1); + CHECK(series[0].metric.name == "requests"); + CHECK(series[0].tags == std::vector{"integration_name:datadog"}); + CHECK(series[0].value == 2); + CHECK(registry.take().empty()); +} + +METRIC_HANDLE_TEST("each combination of tag values is a series") { + details::MetricRegistry registry; + const auto requests = registry.counter( + {"waf.requests", "appsec", true}, {"waf_version:1.30.1"}); + RequestTags tags; + tags.rules_version = TagString{"1.18.2"}; + requests->record(tags, 1); + tags.blocked = true; + tags.step = Step::request_body; + requests->record(tags, 1); + tags.rules_version = TagString{"1.18.2"}; // the same string, interned again + requests->record(tags, 1); + + using Counts = std::map, std::uint64_t>; + CHECK( + by_tags(registry.take()) == + Counts{ + {{"waf_version:1.30.1", "rules_version:1.18.2", "blocked:false"}, 1}, + {{"waf_version:1.30.1", "rules_version:1.18.2", "blocked:true", + "step:req.body"}, + 2}, + }); +} + +METRIC_HANDLE_TEST("a dropped handle is forgotten") { + details::MetricRegistry registry; + auto requests = + registry.counter({"requests", "tracers", true}, {"version:1"}); + requests->record({}, 1); + requests = registry.counter({"requests", "tracers", true}, {"version:2"}); + requests->record({}, 1); + + using Counts = std::map, std::uint64_t>; + CHECK(by_tags(registry.take()) == Counts{{{"version:2"}, 1}}); +} + +METRIC_HANDLE_TEST("a rate keeps its last value") { + details::MetricRegistry registry; + const auto rate = registry.rate({"spans", "tracers", true}); + rate->record({}, 5); + rate->record({}, 3); + CHECK(registry.take().at(0).value == 3); +} + +METRIC_HANDLE_TEST("a distribution has one sketch per series") { + details::MetricRegistry registry; + const auto duration = + registry.distribution({"waf.duration", "appsec", true}); + RequestTags tags; + duration->record(tags, 100); + duration->record(tags, 250); + tags.blocked = true; + duration->record(tags, 7); + + using Sketches = std::map, EncodedSketch>; + CHECK(by_tags(registry.take()) == + Sketches{ + {{"rules_version:", "blocked:false"}, sketch_of({100, 250})}, + {{"rules_version:", "blocked:true"}, sketch_of({7})}, + }); +} + +METRIC_HANDLE_TEST("an enum value without a name is dropped") { + details::MetricRegistry registry; + const auto bodies = registry.counter({"bodies", "appsec", true}); + bodies->record({Size::large}, 1); + bodies->record({Size::unnamed}, 1); + + using Counts = std::map, std::uint64_t>; + CHECK(by_tags(registry.take()) == Counts{{{"size:large"}, 1}}); +} From 22ee92f264ef68d5fe59839ce5a1fa73db350ee8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustavo=20Andr=C3=A9=20dos=20Santos=20Lopes?= Date: Tue, 24 Nov 2026 14:33:22 +0000 Subject: [PATCH 2/2] Handle all invalid enum values --- include/datadog/telemetry/metric_handle.h | 11 ++++++++-- test/telemetry/test_metric_handle.cpp | 26 +++++++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/include/datadog/telemetry/metric_handle.h b/include/datadog/telemetry/metric_handle.h index 616c6ba7e..e8730406e 100644 --- a/include/datadog/telemetry/metric_handle.h +++ b/include/datadog/telemetry/metric_handle.h @@ -127,17 +127,24 @@ class NamedCodec final : public TagCodec { }; // An optional enum field. Value 0 is an empty field, which is not sent. Value -// i + 1 renders as rendered[i]. +// i + 1 renders as rendered[i]. An enum value without a name reads as +// `invalid_enum_value`, which is out of range, so its series is dropped. template class OptionalCodec final : public TagCodec { public: + static constexpr std::uint64_t invalid_enum_value = + std::numeric_limits::max(); + OptionalCodec(tracing::Optional Tags::*field, std::vector rendered) : field_(field), rendered_(std::move(rendered)) {} std::uint64_t read(const void* tags) const override { const auto& value = static_cast(tags)->*field_; - return value ? static_cast(*value) + 1 : 0; + if (!value) return 0; + // Checks before adding 1, which would wrap UINT64_MAX (from -1) to 0. + const auto index = static_cast(*value); + return index < rendered_.size() ? index + 1 : invalid_enum_value; } std::string render(std::uint64_t value) const override { diff --git a/test/telemetry/test_metric_handle.cpp b/test/telemetry/test_metric_handle.cpp index 599c69403..42e9f3a5c 100644 --- a/test/telemetry/test_metric_handle.cpp +++ b/test/telemetry/test_metric_handle.cpp @@ -41,6 +41,19 @@ struct SizeTags { static auto tag_fields() { return std::tuple{tag("size", &SizeTags::size)}; } }; +// A signed enum can hold -1, which has no name. +enum class Level : int { low, high }; + +std::array tag_value_names(Level) { return {"low", "high"}; } + +struct LevelTags { + Optional level; + + static auto tag_fields() { + return std::tuple{tag("level", &LevelTags::level)}; + } +}; + struct TooManyTags { TagString first, second, third, fourth, fifth; @@ -163,3 +176,16 @@ METRIC_HANDLE_TEST("an enum value without a name is dropped") { using Counts = std::map, std::uint64_t>; CHECK(by_tags(registry.take()) == Counts{{{"size:large"}, 1}}); } + +METRIC_HANDLE_TEST("an optional enum value without a name is dropped") { + details::MetricRegistry registry; + const auto hits = registry.counter({"hits", "appsec", true}); + hits->record({}, 1); + hits->record({Level::high}, 1); + hits->record({static_cast(-1)}, 1); + hits->record({static_cast(2)}, 1); + + using Counts = std::map, std::uint64_t>; + CHECK(by_tags(registry.take()) == + Counts{{{}, 1}, {{"level:high"}, 1}}); +}