Skip to content

Add a metric handle API for telemetry - #404

Open
cataphract wants to merge 2 commits into
mainfrom
glopes/telemetry-metric-handle-api
Open

cataphract wants to merge 2 commits into
mainfrom
glopes/telemetry-metric-handle-api

Conversation

@cataphract

@cataphract cataphract commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Overview

Adds metric handles. A metric is registered once, with its fixed tags and a struct that describes its other tags. Recording a point then takes that struct and a number. Nothing uses the handles yet.

struct RequestTags {
  bool blocked = false;
  Outcome outcome = Outcome::ok;  // an enum with tag_value_names(Outcome)
  TagString rules_version;        // values not known in advance

  static auto tag_fields() {
    return std::tuple{tag("request_blocked", &RequestTags::blocked),
                      tag("outcome", &RequestTags::outcome),
                      tag("event_rules_version", &RequestTags::rules_version)};
  }
};

auto requests = registry.counter<RequestTags>(
    {"waf.requests", "appsec", true}, {"waf_version:1.30.1"});
requests->record({true, Outcome::ok, rules_version}, 1);

Stacked on #401.

Motivation

The current API makes every point pay for the full tag strings. Each call to counter::increment(counter, tags) does this:

  1. The caller builds a std::vector<std::string> with one "name:value" string per tag.
  2. Telemetry takes a mutex that every counter in the process shares. Rates and distributions each have one too.
  3. counters_[{counter, tags}] builds a temporary MetricContext key. That copies the metric's name and namespace and every tag string. The key is then hashed in full, and compared in full with the stored key.
  4. Each capture swaps the map out. So the next point of each series inserts it again: a new node, with its own copy of every string.

The cost grows with the number of tags and with traffic. nginx-datadog will send AppSec metrics such as appsec.waf.requests, which has up to 13 tags and is recorded once per request. With the current API, each request would build those strings, then copy, hash and compare about 250 bytes under a lock that every thread takes.

Tags are also free-form strings. Nothing checks the tag names, or limits the values. A typo at one call site, or an unbounded value such as a raw status code, silently creates new series.

With a handle, the work moves to creation time:

  • The fixed tags, and the name:value string of every enum and bool value, are built once.
  • record() reads each field as a number, and combines the numbers into a 64-bit series id. It then updates the handle's own store, under the handle's own lock. It builds, copies and hashes no strings.
  • The tag strings of a series are built only when telemetry sends it.
  • The tag struct is the schema. Enum fields declare their value names once. A TagString is for values not known in advance; it is interned, and after 65535 strings new ones are sent as other. A static_assert checks that every combination of tag values fits in the series id.

Additional Notes

  • A distribution handle keeps one LogBinnedDistr (Add a DDSketch-compatible distribution for telemetry #401) per series, so its memory does not grow with traffic.
  • A details::MetricRegistry creates the handles and takes their series. It holds only weak references: a handle that its owner drops is forgotten, so the metric can be created again with other fixed tags.
  • Follow-ups will make Telemetry send the handles' series, then remove the string-tagged functions and move their callers to handles.
  • ./build/test/tests '[metric_handle]' runs the new tests. The full suite passes.

References

Jira ticket: APPSEC-70954

Contributor Checklist

  • I am the author of this pull request and I own it.
  • I reviewed every line of this pull request.
  • This pull request follows the Contributing Guidelines.

@cataphract
cataphract added this pull request to stack #405 November 13, 2026 23:39
@pr-commenter

pr-commenter Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-11-24 14:40:00

Comparing candidate commit 22ee92f in PR branch glopes/telemetry-metric-handle-api with baseline commit f54a882 in branch main.

📊 Benchmarking dashboard

Found 0 performance improvements and 0 performance regressions! Performance is the same for 8 metrics, 0 unstable metrics.

Explanation

This is an A/B test comparing a candidate commit's performance against that of a baseline commit. Performance changes are noted in the tables below as:

  • 🟩 = significantly better candidate vs. baseline
  • 🟥 = significantly worse candidate vs. baseline

We compute a confidence interval (CI) over the relative difference of means between metrics from the candidate and baseline commits, considering the baseline as the reference.

If the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD), the change is considered significant.

Feel free to reach out to #apm-benchmarking-platform on Slack if you have any questions.

More details about the CI and significant changes

You can imagine this CI as a range of values that is likely to contain the true difference of means between the candidate and baseline commits.

CIs of the difference of means are often centered around 0%, because often changes are not that big:

---------------------------------(------|---^--------)-------------------------------->
                              -0.6%    0%  0.3%     +1.2%
                                 |          |        |
         lower bound of the CI --'          |        |
sample mean (center of the CI) -------------'        |
         upper bound of the CI ----------------------'

As described above, a change is considered significant if the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD).

For instance, for an execution time metric, this confidence interval indicates a significantly worse performance:

----------------------------------------|---------|---(---------^---------)---------->
                                       0%        1%  1.3%      2.2%      3.1%
                                                  |   |         |         |
       significant impact threshold --------------'   |         |         |
                      lower bound of CI --------------'         |         |
       sample mean (center of the CI) --------------------------'         |
                      upper bound of CI ----------------------------------'

Base automatically changed from glopes/telemetry-ddsketch to main November 24, 2026 12:07
@cataphract
cataphract force-pushed the glopes/telemetry-metric-handle-api branch 3 times, most recently from 572f18f to be4aea3 Compare November 24, 2026 14:11
@cataphract
cataphract marked this pull request as ready for review November 24, 2026 14:11
@cataphract
cataphract requested review from a team as code owners November 24, 2026 14:11
@cataphract
cataphract requested review from xlamorlette-datadog and removed request for a team November 24, 2026 14:11
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-24T14:12:44.546075Z be4aea3 Draft marked ready
🔒 Security Review ✅ Completed 2026-11-24T14:15:27.413659Z be4aea3 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

A metric is registered once with typed tags, so recording a point builds,
copies and hashes no tag strings. Nothing uses the handles yet.
@cataphract
cataphract force-pushed the glopes/telemetry-metric-handle-api branch from be4aea3 to 1d99d30 Compare November 24, 2026 14:16

@datadog-official datadog-official Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bits Code Review: FAIL

An optional enum containing an unnamed -1 value wraps to the missing-tag encoding, causing its metric point to be counted in the wrong series instead of being dropped.

Open Bits AI session

🤖 Bits Code Review · Commit 1d99d30

@datadog-official datadog-official Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bits Code Review: PASS

More details

The PR adds typed metric handles with schema-defined tags and per-handle storage, with telemetry sending deferred to follow-up work. The new commit fixes the optional-enum -1 wraparound and adds regression coverage; no reportable findings remain open, though runtime tests were not run.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 22ee92f

@xlamorlette-datadog xlamorlette-datadog left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Impressive!

enum class MetricType : char { counter, rate, distribution };
}

/// A DDSketch protobuf message, as bytes.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

opt, nit, tiny: rather use double slash // not triple ///. I do see you so this to conform to surrounding code, but I would prefer to fix this whole (little) file.
Actually, I don't know where this comes from. Quick internet search seems to show that it could come from old Visual Studio or Doxygen conventions, or even from C#.

#include <type_traits>

namespace datadog {
namespace telemetry {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

opt, nit, tiny: by the way, use compound namespaces

}

/// A DDSketch protobuf message, as bytes.
using EncodedSketch = std::string;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: more explicit EncodedDDSketch

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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

opt, nit: suggestion for slightly improved comment: Value type of a series: encoded sketch for a distribution, integer for a count or a rate

#include <datadog/string_view.h>
#include <datadog/telemetry/metrics.h>

#include <algorithm>

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: remove include lines already indirectly included: this shrinks lines 52-63 to:

#include <unordered_map>
#include <vector>

}

std::string StringTable::value(std::uint16_t id) {
if (id == overflow_id) return "other";

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Maybe we should use a more explicit string stating that we overflown the table. (If changed, change also the comment line 69 of metric_handle.h.)

}

std::string render(std::uint64_t value) const override {
return name_ + ":" + interned_string(value);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An empty TagString will render as name:. Is this intended?

class MetricHandle final : public MetricBase<Metric> {
static_assert(
fits_in_series_id(static_cast<decltype(Tags::tag_fields())*>(nullptr)),
"Too many combinations of tag values for a 64-bit SeriesId");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Given the checks in fits_in_series_id(), we get this Too many combinations error message for an enum with no values.

// | DistributionHandle) | fixed_tags_
// | |
// | record(Tags, value) v
// | take_series() vector<unique_ptr<TagCodec>> -|> NamedCodec

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: NamedCode, OptionalCodec and StringCodecderive fromTagCodec`: the arrow is in the wrong direction.

namespace {

// Id of every new string once the table is full.
constexpr std::uint16_t overflow_id = 0xFFFF;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: rather TagString::id_count - 1?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants