Skip to content

feat(codecs): add prometheus_text encoding codec - #27305

Open
valerypetrov wants to merge 4 commits into
vectordotdev:masterfrom
valerypetrov:feature/prometheus-text-codec
Open

valerypetrov wants to merge 4 commits into
vectordotdev:masterfrom
valerypetrov:feature/prometheus-text-codec

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Adds a prometheus_text encoding codec that writes metrics in the Prometheus text exposition format.

Why: no codec could produce it. The text codec only resembles it (<timestamp> name{a="b"} = 1), so Prometheus parsers reject it, for example Telegraf's kafka_consumer with data_format = "prometheus". The real encoder is private to the prometheus_exporter sink.

What it does: each event is encoded alone as a # TYPE line plus one line per series. Absolute counters, gauges, sets, aggregated histograms and aggregated summaries are supported. Incremental metrics, distributions and sketches return an error, because they need state or settings that a codec does not have.

Testing: 12 new unit tests, and all 298 codecs tests pass. Output from a real Vector binary was parsed by Telegraf's prometheus parser without errors.

Not done: I edited the generated docs .cue entry by hand and did not run make generate-component-docs.

Generated with Claude Sonnet 5.5.

🤖 Generated with Claude Code

Vector had no way to write metrics in the Prometheus text exposition
format to sinks such as `kafka`, `file` or `http`. The `text` codec only
resembles that format (it prefixes a timestamp and uses ` = ` before the
value), and the real encoder lives inside the `prometheus_exporter` sink,
which is not reusable as a codec.

Add a small, stateless `prometheus_text` serializer. Each event is encoded
on its own as a `# TYPE` line followed by one line per series. Absolute
counters, gauges, sets, aggregated histograms and aggregated summaries are
supported. Incremental metrics, distributions and sketches are rejected with
an error, because encoding them needs state or settings (such as buckets)
that a codec does not have.

The default framing is `bytes`, because every output line already ends with a
line feed.

Generated with Claude Sonnet 5.5

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@valerypetrov
valerypetrov requested review from a team as code owners November 23, 2026 23:02
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 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-24T20:28:17.551492Z 86a7db2 New commits
ℹ️ 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.

@github-actions github-actions Bot added docs review on hold The documentation team reviews PRs only after a PR is approved by the COSE team. domain:sinks Anything related to Vector's sinks domain:external docs Anything related to Vector's external, public documentation labels Nov 23, 2026
@datadog-official datadog-official Bot added domain:metrics Anything related to Vector's metrics events sink:http Anything `http` sink related labels Nov 23, 2026

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 15a6db5e95

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

}
};

Ok(format!("# TYPE {name} {kind}\n{out}"))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Emit each metric family's TYPE header only once per payload

When the HTTP sink batches two events with the same metric name and different tags, HttpEncoder::encode_input (src/sinks/http/encoder.rs:67-74) concatenates both serializations into one payload. This produces a second # TYPE line for that metric name, which the Prometheus text format forbids and strict parsers reject, making ordinary multi-series batches unreadable. Unlike the existing StringCollector::emit_metadata, this path never deduplicates headers. Emit metadata once per metric family within each exposition payload and cover multi-event batch encoding in the tests.

Useful? React with 👍 / 👎.

Comment on lines +89 to +90
if contains_line_break(&name)
|| tags.is_some_and(|tags| tags.iter_single().any(|(key, _)| contains_line_break(key)))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Validate identifiers before emitting bare metric and label names

For an absolute StatsD gauge named foo.bar, which statsd::parser::sanitize_key preserves, this check passes and the codec returns success with # TYPE foo.bar gauge and a bare foo.bar sample. Dots are not legal in bare Prometheus metric identifiers, so consumers reject the payload; the repository's prometheus-parser::line::parse_name rejects it too. Tag keys such as http.method are likewise written verbatim. Validate or normalize metric names, namespaces and label keys, or use a supported quoted-name representation, rather than accepting everything except line breaks.

Useful? React with 👍 / 👎.

@datadoghq-integration datadoghq-integration 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

HTTP batches containing multiple series of the same metric emit repeated TYPE declarations that strict Prometheus parsers reject. Dotted identifiers and collisions with generated histogram or summary labels also produce invalid output.

Open Bits AI session

🤖 Bits Code Review · Commit 15a6db5

}
};

Ok(format!("# TYPE {name} {kind}\n{out}"))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Emit TYPE metadata once per family within each payload

When an HTTP batch contains multiple events with the same metric name, including different label sets, HttpEncoder concatenates their serialized output. This produces repeated # TYPE declarations after samples for that family, which strict Prometheus parsers reject, making the request unreadable. Metadata emission must respect payload boundaries and declare each family only once before its samples.

React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it

What each reaction means
  • 👍 Useful: correct, and you're fixing it or will.
  • 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
  • 😕 Unclear: you can't tell what it means or why it matters.
  • 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.

🤖 Bits Code Review · Open Bits AI session

Comment on lines +89 to +93
if contains_line_break(&name)
|| tags.is_some_and(|tags| tags.iter_single().any(|(key, _)| contains_line_break(key)))
{
return Err(format!("metric `{name}` has a line break in its name or a tag name").into());
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Validate unquoted metric and label identifiers

The StatsD source preserves dotted names even with sanitization enabled, so input foo.bar:1|g reaches this codec as an absolute gauge. This check accepts it and emits '# TYPE foo.bar gauge' and 'foo.bar 1', although dots are invalid in unquoted Prometheus identifiers. Downstream parsing therefore fails despite successful serialization. Validate the combined metric name and label names against their respective identifier grammars.

Suggested change
if contains_line_break(&name)
|| tags.is_some_and(|tags| tags.iter_single().any(|(key, _)| contains_line_break(key)))
{
return Err(format!("metric `{name}` has a line break in its name or a tag name").into());
}
let invalid_identifier = |value: &str, allow_colon: bool| {
value.is_empty()
|| contains_line_break(value)
|| value.bytes().enumerate().any(|(index, byte)| {
!(byte.is_ascii_alphabetic()
|| byte == b'_'
|| (allow_colon && byte == b':')
|| (index > 0 && byte.is_ascii_digit()))
})
};
if invalid_identifier(&name, true)
|| tags.is_some_and(|tags| {
tags.iter_single()
.any(|(key, _)| invalid_identifier(key, false))
})
{
return Err(format!("metric `{name}` has an invalid metric or tag name").into());
}

React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it

What each reaction means
  • 👍 Useful: correct, and you're fixing it or will.
  • 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
  • 😕 Unclear: you can't tell what it means or why it matters.
  • 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.

🤖 Bits Code Review · Open Bits AI session

return Err(format!("metric `{name}` has a line break in its name or a tag name").into());
}

let timestamp = metric.timestamp().map(|t| t.timestamp_millis());

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Reject collisions with generated histogram and summary labels

An aggregated histogram carrying an le tag, or a summary carrying a quantile tag, passes validation. encode_tags then appends the generated label, producing duplicate names such as latency_bucket{le="1",le="tenant"}. Strict consumers reject these samples; Vector's parser overwrites a duplicate value and can fail while parsing the boundary. Reject reserved-label collisions before emitting the family or handle them consistently across all its series.

Suggested change
let timestamp = metric.timestamp().map(|t| t.timestamp_millis());
let reserved_label = match metric.value() {
MetricValue::AggregatedHistogram { .. } => Some("le"),
MetricValue::AggregatedSummary { .. } => Some("quantile"),
_ => None,
};
if let Some(label) = reserved_label {
if tags.is_some_and(|tags| tags.iter_single().any(|(key, _)| key == label)) {
return Err(format!("metric `{name}` has reserved tag `{label}`").into());
}
}
let timestamp = metric.timestamp().map(|t| t.timestamp_millis());

React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it

What each reaction means
  • 👍 Useful: correct, and you're fixing it or will.
  • 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
  • 😕 Unclear: you can't tell what it means or why it matters.
  • 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.

🤖 Bits Code Review · Open Bits AI session

The `http` sink concatenates the output of all events of a batch, so two
events of one metric family (for example with different tags) produced a
repeated `# TYPE` line and a split family. The Prometheus text format
forbids both, and strict parsers such as `expfmt` reject the request. Add
`PrometheusTextSerializer::encode_batch`, which writes every family once,
as a single `# TYPE` line followed by all of its series, and use it in the
`http` sink, so that each request body is one valid exposition. A batch in
which one family has two different types is rejected.

Metric names, namespaces and tag names were written verbatim, so a StatsD
gauge named `foo.bar` or a tag named `http.method` produced output that
consumers cannot parse. They are now checked against the Prometheus name
grammar, and invalid ones are rejected. An aggregated histogram with an
`le` tag and a summary with a `quantile` tag, which would duplicate the
label that the codec adds, are rejected too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@datadoghq-integration datadoghq-integration 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

The PR adds Prometheus text encoding for metrics and now fixes duplicate HTTP TYPE declarations, invalid identifiers, and reserved-label collisions. One issue remains: HTTP batch encoding bypasses explicitly configured framing, so receivers expecting length prefixes or delimiters cannot decode the payload.

Open Bits AI session

🤖 Bits Code Review · Commit af036f8

Comment thread src/sinks/http/encoder.rs
Comment on lines +78 to +83
serializer
.encode_batch(events, &mut body)
.map_err(|error| {
emit(EncoderSerializeError { error: &error });
io::Error::other("unable to encode event")
})?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Apply configured framing to HTTP batch output

With prometheus_text and explicit length_delimited or character_delimited framing, configuration accepts and builds the requested framer, but this new branch calls encode_batch directly and never applies it. Even a single-event request therefore loses its configured length prefix or delimiter, preventing receivers expecting that framing from decoding the payload. Frame the completed exposition, including enforcing framing limits, or reject unsupported settings during configuration validation.

Suggested change
serializer
.encode_batch(events, &mut body)
.map_err(|error| {
emit(EncoderSerializeError { error: &error });
io::Error::other("unable to encode event")
})?;
serializer
.encode_batch(events, &mut body)
.map_err(|error| {
emit(EncoderSerializeError { error: &error });
io::Error::other("unable to encode event")
})?;
let mut framer = self.encoder.framer().clone();
framer.encode((), &mut body).map_err(|error| {
emit(vector_lib::codecs::internal_events::EncoderFramingError {
error: &error,
});
io::Error::other("unable to frame exposition")
})?;

React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it

What each reaction means
  • 👍 Useful: correct, and you're fixing it or will.
  • 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
  • 😕 Unclear: you can't tell what it means or why it matters.
  • 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.

🤖 Bits Code Review · Open Bits AI session

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: af036f89d3

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

format!("metric `{name}` is both a {family_kind} and a {kind}").into(),
);
}
Some((_, family_series)) => family_series.push_str(&series),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Deduplicate repeated series within each exposition

When an HTTP batch contains multiple updates for the same series—for example, timestamp-less StatsD gauge updates up:1|g and up:2|g within the default one-second batching window—this appends both up 1 and up 2 beneath one TYPE header. Prometheus exposition requires each metric-name/label combination to be unique, so receivers enforcing that requirement cannot ingest the request even though both input metrics are supported. Retain one sample per emitted series or split repeated updates into separate expositions, and cover same-series batches in the tests.

Useful? React with 👍 / 👎.

Comment on lines +159 to +160
for bucket in buckets.iter().filter(|b| !b.upper_limit.is_infinite()) {
bucket_count += bucket.count as f64;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve negative-infinity bucket contributions

When an aggregated histogram contains a -Inf bucket with observations, this filter removes it before adding its count to the cumulative total. Such buckets are preserved by src/sources/prometheus/parser.rs:139-164; an input with bucket counts (-Inf, 2) and (1, 3) therefore emits le="1" with count 3 instead of 5, silently corrupting the histogram. Only the positive-infinity bucket is regenerated from the total count; retain negative-infinity buckets and their contributions.

Useful? React with 👍 / 👎.

Comment thread src/sinks/http/encoder.rs

for mut event in events {
self.transformer.transform(&mut event);
if let PrometheusText(serializer) = self.encoder.serializer() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Honor explicit framing in the Prometheus HTTP path

When prometheus_text is configured with explicit length_delimited or character_delimited framing, configuration building still accepts and constructs that framer, but this branch invokes the serializer directly instead of the configured encoder. The HTTP body consequently lacks the requested length prefix or delimiter, so a receiver expecting that framing cannot decode it. Honor the configured framing or reject incompatible framing during validation rather than silently ignoring it.

Useful? React with 👍 / 👎.

@pront pront added the meta:awaiting author Pull requests that are awaiting their author. label Nov 24, 2026
…ometheus_text`

A batch with several updates of one series, such as two timestamp-less
StatsD gauge updates in one `http` sink request, was encoded as several
samples of that series under one `# TYPE` line. The text format allows
each metric name and label set only once per exposition, and receivers
such as the Pushgateway reject the request. `encode_batch` now keeps one
sample per series, from the last event of that series, as the
`prometheus_exporter` sink does. Samples with different timestamps are
still the same series in this format, so they are collapsed too.

An aggregated histogram bucket with an upper limit of `-Inf`, which the
`prometheus_scrape` source keeps, was dropped together with its count, so
every later cumulative bucket was too low. Only the `+Inf` bucket, which
is written from the total count, is skipped now, and a `-Inf` bucket is
written as `le="-Inf"`.

The `http` sink encoded the request with the serializer only, so an
explicitly configured framing such as `length_delimited` was built but
silently ignored. It now frames the exposition as a whole, which also
enforces the limits of the framing. The default framing is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@datadoghq-integration datadoghq-integration 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 Prometheus text encoding for absolute metrics, with HTTP batches emitting one sample per series and framing the complete exposition. Duplicate TYPE declarations, invalid identifiers, reserved-label collisions, and ignored HTTP framing are fixed; no review findings remain open.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 39fef99

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 39fef99afc

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

let (name, kind, series) = encode_metric(&metric)?;
let mut labels = String::new();
encode_tags(&mut labels, metric.tags(), None);
match families.get_mut(&name) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Detect collisions with generated histogram and summary series

If an HTTP batch contains a histogram latency with count 1 and a gauge latency_count with value 42 and the same tags, encoding succeeds and emits both latency_count 1 and latency_count 42. These are separate input families, so the new per-family de-duplication does not cover this collision. The resulting exposition violates series uniqueness and can be rejected by strict receivers. Check emitted sample names across families, including generated _count and _sum names, and reject conflicting inputs before writing the payload.

Useful? React with 👍 / 👎.

Comment on lines +235 to +238
let reserved = match metric.value() {
MetricValue::AggregatedHistogram { .. } => Some("le"),
MetricValue::AggregatedSummary { .. } => Some("quantile"),
_ => None,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject the reserved __name__ label on every metric type

For an absolute gauge tagged __name__="other", lexical validation accepts the key and this reserved-label check returns None, so encoding successfully produces up{__name__="other"} 1. Prometheus text parsers such as expfmt.TextParser reject __name__ because it is reserved for the metric name, making this event's output unusable and potentially invalidating its HTTP batch. Reject __name__ for every metric type in addition to the type-specific le and quantile checks.

Useful? React with 👍 / 👎.

…ometheus_text`

A metric tagged `__name__`, such as a gauge `up` with `__name__="other"`,
was encoded as `up{__name__="other"} 1`. The label is reserved for the
metric name, and Prometheus text parsers such as `expfmt.TextParser`
reject the whole exposition. The tag is now rejected for every metric
type, next to the `le` and `quantile` checks of histograms and summaries.

In the `http` sink, a histogram `latency` and a gauge `latency_count` in
one request were written as two families that both have `latency_count`
samples, which strict receivers reject ("second TYPE line for metric
name"). `encode_batch` now rejects a batch in which a metric is named like
the `_bucket`, `_sum` or `_count` series of a histogram, or the `_sum` or
`_count` series of a summary, the same way it rejects two types for one
family, and writes nothing. Labels do not matter, because the parsers
reject the second `# TYPE` line itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 86a7db2824

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

type Error = vector_common::Error;

fn encode(&mut self, event: Event, buffer: &mut BytesMut) -> Result<(), Self::Error> {
self.encode_batch([event], buffer)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Apply exposition batching to shared batch-sink encoding

When an aws_s3 batch contains two metrics from the same family with different labels, its shared encoder (src/sinks/util/encoding.rs:45-67) invokes this single-event method twice and concatenates the results into one object. The new batch-aware integration in HttpEncoder does not cover that path. With the default bytes framing, the object contains two # TYPE declarations for the same family without any boundary separating the expositions, so strict Prometheus text parsers reject an ordinary multi-series batch. Use the family-aware batch encoder at shared batch-sink boundaries, or require framing that preserves separate expositions.

Useful? React with 👍 / 👎.

Comment on lines +81 to +82
let mut labels = String::new();
encode_tags(&mut labels, metric.tags(), None);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Canonicalize empty labels before deduplicating series

When an HTTP batch contains StatsD updates up:1|g and up:2|g|#env:, the empty tag value is preserved by src/sources/util/mod.rs:98-100. The new deduplication map therefore uses different keys for the untagged metric and {env=""}, retaining both and emitting up 1 followed by up{env=""} 2. Prometheus considers an empty-valued label equivalent to an absent label, so these are conflicting samples for the same series, and a canonicalizing receiver can reject the batch instead of receiving the documented last value. Normalize empty-valued labels when constructing the deduplication key and cover absent-versus-empty tags.

Useful? React with 👍 / 👎.

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

docs review on hold The documentation team reviews PRs only after a PR is approved by the COSE team. domain:external docs Anything related to Vector's external, public documentation domain:metrics Anything related to Vector's metrics events domain:sinks Anything related to Vector's sinks meta:awaiting author Pull requests that are awaiting their author. sink:http Anything `http` sink related

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants