Repository navigation
feat(codecs): add prometheus_text encoding codec - #27305
valerypetrov wants to merge 4 commits into
Conversation
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>
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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}")) |
There was a problem hiding this comment.
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 👍 / 👎.
| if contains_line_break(&name) | ||
| || tags.is_some_and(|tags| tags.iter_single().any(|(key, _)| contains_line_break(key))) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
🤖 Bits Code Review · Commit 15a6db5
| } | ||
| }; | ||
|
|
||
| Ok(format!("# TYPE {name} {kind}\n{out}")) |
There was a problem hiding this comment.
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
| 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()); | ||
| } |
There was a problem hiding this comment.
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.
| 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()); |
There was a problem hiding this comment.
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.
| 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>
There was a problem hiding this comment.
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.
🤖 Bits Code Review · Commit af036f8
| serializer | ||
| .encode_batch(events, &mut body) | ||
| .map_err(|error| { | ||
| emit(EncoderSerializeError { error: &error }); | ||
| io::Error::other("unable to encode event") | ||
| })?; |
There was a problem hiding this comment.
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.
| 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
There was a problem hiding this comment.
💡 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), |
There was a problem hiding this comment.
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 👍 / 👎.
| for bucket in buckets.iter().filter(|b| !b.upper_limit.is_infinite()) { | ||
| bucket_count += bucket.count as f64; |
There was a problem hiding this comment.
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 👍 / 👎.
|
|
||
| for mut event in events { | ||
| self.transformer.transform(&mut event); | ||
| if let PrometheusText(serializer) = self.encoder.serializer() { |
There was a problem hiding this comment.
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 👍 / 👎.
…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>
There was a problem hiding this comment.
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.
🤖 Bits Code Review · Commit 39fef99
There was a problem hiding this comment.
💡 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) { |
There was a problem hiding this comment.
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 👍 / 👎.
| let reserved = match metric.value() { | ||
| MetricValue::AggregatedHistogram { .. } => Some("le"), | ||
| MetricValue::AggregatedSummary { .. } => Some("quantile"), | ||
| _ => None, |
There was a problem hiding this comment.
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>
There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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 👍 / 👎.
| let mut labels = String::new(); | ||
| encode_tags(&mut labels, metric.tags(), None); |
There was a problem hiding this comment.
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 👍 / 👎.
Adds a
prometheus_textencoding codec that writes metrics in the Prometheus text exposition format.Why: no codec could produce it. The
textcodec only resembles it (<timestamp> name{a="b"} = 1), so Prometheus parsers reject it, for example Telegraf'skafka_consumerwithdata_format = "prometheus". The real encoder is private to theprometheus_exportersink.What it does: each event is encoded alone as a
# TYPEline 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
codecstests pass. Output from a real Vector binary was parsed by Telegraf'sprometheusparser without errors.Not done: I edited the generated docs
.cueentry by hand and did not runmake generate-component-docs.Generated with Claude Sonnet 5.5.
🤖 Generated with Claude Code