:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(capture-logs): ingest Prometheus remote-write v1 into metrics (#85868)
Daniel Visca551ebc4b9773
diff --git a/proto/prometheus/v1/remote_write.proto b/proto/prometheus/v1/remote_write.protonew file mode 100644index 000000000000..3c21d7fa4dd5--- /dev/null+++ b/proto/prometheus/v1/remote_write.proto@@ -0,0 +1,56 @@+syntax = "proto3";++package prometheus.v1;++// Minimal subset of the Prometheus remote-write v1 protocol+// (github.com/prometheus/prometheus/prompb) sufficient to decode a write+// request. Field numbers MUST match upstream for wire compatibility.+//+// TimeSeries fields 3 (exemplars) and 4 (native histograms) are intentionally+// omitted: proto3 skips unknown fields during decoding, so a v1 sender that+// includes them is decoded without error and those payloads are dropped. Native+// histogram and exemplar support is deferred (and would require RW v2 for+// per-series type metadata anyway).++message WriteRequest {+ repeated TimeSeries timeseries = 1;+ // Field 2 is reserved upstream.+ repeated MetricMetadata metadata = 3;+}++message TimeSeries {+ repeated Label labels = 1;+ repeated Sample samples = 2;+}++message Label {+ string name = 1;+ string value = 2;+}++message Sample {+ double value = 1;+ // Milliseconds since the Unix epoch.+ int64 timestamp = 2;+}++message MetricMetadata {+ // Values carry buf's required METRIC_TYPE_ prefix, which upstream omits; the+ // numbers are what the wire format pins, and prost strips the prefix so the+ // generated Rust variants are unchanged. Zero is upstream's UNKNOWN.+ enum MetricType {+ METRIC_TYPE_UNSPECIFIED = 0;+ METRIC_TYPE_COUNTER = 1;+ METRIC_TYPE_GAUGE = 2;+ METRIC_TYPE_HISTOGRAM = 3;+ METRIC_TYPE_GAUGEHISTOGRAM = 4;+ METRIC_TYPE_SUMMARY = 5;+ METRIC_TYPE_INFO = 6;+ METRIC_TYPE_STATESET = 7;+ }++ MetricType type = 1;+ string metric_family_name = 2;+ string help = 4;+ string unit = 5;+}diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 53ed562bec3d..16fac2f583b1 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2235,12 +2235,14 @@ dependencies = ["limiters","metrics","opentelemetry-proto 0.29.0",+ "prometheus-rw-proto","prost 0.13.5","rdkafka","serde","serde_derive","serde_json","siphasher 1.0.2",+ "snap","thiserror 2.0.18","tokio","tonic 0.12.3",@@ -9201,6 +9203,14 @@ dependencies = ["watto",]+[[package]]+name = "prometheus-rw-proto"+version = "0.1.0"+dependencies = [+ "prost 0.13.5",+ "tonic-build 0.12.3",+]+[[package]]name = "property-defs-rs"version = "0.1.0"diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex 6c37a01dc056..6a11f6f11ca8 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -62,6 +62,7 @@ members = ["personhog-leader","personhog-writer","personhog-proto",+ "prometheus-rw-proto","personhog-replica","personhog-router","personhog-stateright",@@ -195,6 +196,7 @@ serde_derive = { version = "1.0" }serde_json = { version = "1.0" }serde_urlencoded = "0.7.1"siphasher = "1.0.1"+snap = "1"sqlx = { version = "0.8.6", features = ["chrono","json",diff --git a/rust/affected-services/determinator-rules.toml b/rust/affected-services/determinator-rules.tomlindex 222e10b18e53..b2b8a90aa70c 100644--- a/rust/affected-services/determinator-rules.toml+++ b/rust/affected-services/determinator-rules.toml@@ -28,10 +28,18 @@ mark-changed = "all"globs = [".sqlx/**"]mark-changed = "all"-# Proto files trigger the build-script crates that read them.+# Proto files trigger every build-script crate that reads them. The+# proto_build_scripts_are_in_determinator_rules test fails if a crate compiles+# protos and is missing here, so keep this list complete rather than counted.[[path-rule]]globs = ["../proto/**"]-mark-changed = ["personhog-proto", "kafka-assigner-proto", "cymbal-proto", "ingestion-worker-proto"]+mark-changed = [+ "personhog-proto",+ "kafka-assigner-proto",+ "cymbal-proto",+ "ingestion-worker-proto",+ "prometheus-rw-proto",+]# Hypercache contract: Python serializer changes may break Rust deserialization.# Must come BEFORE the catch-all rule below.diff --git a/rust/capture-logs/Cargo.toml b/rust/capture-logs/Cargo.tomlindex 305eab11bbf8..267cf8fdbfb5 100644--- a/rust/capture-logs/Cargo.toml+++ b/rust/capture-logs/Cargo.toml@@ -37,6 +37,8 @@ prost = { workspace = true }bytes = { workspace = true }tower-http = { workspace = true }hex = "0.4"+snap = { workspace = true }+prometheus-rw-proto = { path = "../prometheus-rw-proto" }[dev-dependencies]tower = { workspace = true }diff --git a/rust/capture-logs/src/endpoints/mod.rs b/rust/capture-logs/src/endpoints/mod.rsindex e9dd6d896e63..7c5ecac44a03 100644--- a/rust/capture-logs/src/endpoints/mod.rs+++ b/rust/capture-logs/src/endpoints/mod.rs@@ -1 +1,2 @@pub mod datadog;+pub mod prometheus;diff --git a/rust/capture-logs/src/endpoints/prometheus.rs b/rust/capture-logs/src/endpoints/prometheus.rsnew file mode 100644index 000000000000..3b54b0fe522e--- /dev/null+++ b/rust/capture-logs/src/endpoints/prometheus.rs@@ -0,0 +1,425 @@+use std::collections::HashMap;++use anyhow::{anyhow, Result};+use axum::extract::{Path, Query, State};+use axum::http::{HeaderMap, StatusCode};+use axum::Json;+use bytes::Bytes;+use chrono::{TimeZone, Utc};+use metrics::counter;+use prometheus_rw_proto::prometheus::v1::{+ metric_metadata::MetricType, MetricMetadata, WriteRequest,+};+use prost::Message;+use serde::Deserialize;+use serde_json::json;+use tracing::{debug, error, instrument, warn};+use uuid::Uuid;++use crate::authorizer::Signal;+use crate::metric_record::{compute_series_fingerprint, override_timestamp, KafkaMetricRow};+use crate::service::Service;++const METRIC_NAME_LABEL: &str = "__name__";+const JOB_LABEL: &str = "job";+const INSTANCE_LABEL: &str = "instance";++/// Approximate in-memory/Avro cost of one row beyond its label data (uuid,+/// timestamps, type/temporality strings, map overhead). Used by+/// [`estimate_expanded_bytes`] so a request full of near-empty samples still+/// registers a per-row cost.+const ROW_OVERHEAD_BYTES: u64 = 256;++/// How much larger than the (already decompression-capped) request body the+/// expanded row set may be. Row building clones the series label map per+/// sample and the whole batch becomes a single Kafka message, so a 2 wire-byte+/// sample expands to hundreds of bytes — legitimate senders (Prometheus+/// defaults to 2k samples per send, vmagent to 10k rows per block) stay far+/// below this; only expansion-bomb payloads exceed it.+const MAX_EXPANSION_FACTOR: u64 = 16;++/// Decode a snappy-compressed Prometheus remote-write v1 payload.+///+/// Prometheus sends `Content-Encoding: snappy` using the snappy *block* format+/// (not the framed format), so we decode the raw body ourselves — the global+/// `RequestDecompressionLayer` does not understand snappy.+///+/// The block format's length header is sender-controlled, so the claimed+/// decompressed size is checked against `max_decompressed_bytes` before any+/// allocation happens.+pub fn decode_write_request(body: &[u8], max_decompressed_bytes: usize) -> Result<WriteRequest> {+ let claimed =+ snap::raw::decompress_len(body).map_err(|e| anyhow!("snappy decode failed: {e}"))?;+ if claimed > max_decompressed_bytes {+ return Err(anyhow!(+ "decompressed request body exceeds limit ({claimed} > {max_decompressed_bytes} bytes)"+ ));+ }+ let decompressed = snap::raw::Decoder::new()+ .decompress_vec(body)+ .map_err(|e| anyhow!("snappy decode failed: {e}"))?;+ WriteRequest::decode(decompressed.as_slice())+ .map_err(|e| anyhow!("remote-write protobuf decode failed: {e}"))+}++/// Translate a decoded remote-write request into `KafkaMetricRow` records — the+/// same Avro shape the OTLP path produces, so the rest of the pipeline+/// (`ingestion-metrics` consumer → `clickhouse_metrics` → `metrics1`) is+/// unchanged. One row is emitted per sample. Returns the rows and the number of+/// samples whose timestamp was clamped by `override_timestamp`.+pub fn write_request_to_kafka_rows(req: WriteRequest) -> (Vec<KafkaMetricRow>, u64) {+ // Metric-family name -> declared (type, unit). Only populated when the+ // sender includes the optional metadata block (vmagent and many agents+ // omit it, so the name-suffix heuristic in `classify` is the primary path).+ let metadata = build_metadata_map(&req.metadata);++ let mut rows = Vec::new();+ let mut timestamps_overridden = 0u64;+ let mut dropped_series = 0u64;+ let mut dropped_samples = 0u64;++ for series in req.timeseries {+ let mut metric_name = String::new();+ let mut service_name = String::new();+ let mut resource_attributes: HashMap<String, String> = HashMap::new();+ let mut attributes: HashMap<String, String> = HashMap::new();++ for label in series.labels {+ match label.name.as_str() {+ METRIC_NAME_LABEL => metric_name = label.value,+ // Map Prometheus topology labels onto OTel resource semantics so+ // `service_name` populates the same way it does for OTLP. Map+ // values are JSON-encoded to match the OTLP/Datadog paths — the+ // ClickHouse MV applies JSONExtractString to them.+ JOB_LABEL => {+ service_name = label.value.clone();+ resource_attributes+ .insert("service.name".to_string(), json!(label.value).to_string());+ }+ INSTANCE_LABEL => {+ resource_attributes.insert(+ "service.instance.id".to_string(),+ json!(label.value).to_string(),+ );+ }+ _ => {+ attributes.insert(label.name, json!(label.value).to_string());+ }+ }+ }++ // A series with no metric name is unusable; skip it.+ if metric_name.is_empty() {+ continue;+ }++ // The vendored v1 proto deliberately skips native-histogram fields, so a+ // native-histogram series decodes to labels with no float samples and+ // yields no rows. Count it rather than let the whole request 204 as if+ // nothing were lost — the sender would otherwise drop the batch silently.+ if series.samples.is_empty() {+ dropped_series += 1;+ continue;+ }++ let declared = lookup_metadata(&metadata, &metric_name);+ let unit = declared.map(|(_, u)| u.clone()).unwrap_or_default();+ let (metric_type, is_monotonic, temporality) =+ classify(&metric_name, declared.map(|(t, _)| *t));++ let series_fingerprint = compute_series_fingerprint(+ &metric_name,+ metric_type,+ &service_name,+ &resource_attributes,+ &attributes,+ );++ for sample in series.samples {+ // Prometheus marks a series stale with a NaN payload and remote-write+ // forwards it (vmagent emits these by default on scrape failure or+ // series churn). The metrics pipeline has no stale-marker concept, and+ // a non-finite value survives the storage/query path uncaught —+ // `ifNull` never fires on NaN, and it corrupts rate/aggregate results.+ // Drop it here, as staleness-unaware receivers do.+ if !sample.value.is_finite() {+ dropped_samples += 1;+ continue;+ }++ // Remote-write sample timestamps are milliseconds since the epoch.+ let raw_timestamp = Utc+ .timestamp_millis_opt(sample.timestamp)+ .single()+ .unwrap_or_else(Utc::now);+ let (timestamp, original_timestamp) = override_timestamp(raw_timestamp);++ let mut sample_attributes = attributes.clone();+ if let Some(original) = original_timestamp {+ timestamps_overridden += 1;+ sample_attributes.insert("$originalTimestamp".to_string(), original.to_rfc3339());+ }++ rows.push(KafkaMetricRow {+ uuid: Uuid::now_v7().to_string(),+ trace_id: String::new(),+ span_id: String::new(),+ trace_flags: 0,+ timestamp,+ observed_timestamp: Utc::now(),+ service_name: service_name.clone(),+ metric_name: metric_name.clone(),+ metric_type: metric_type.to_string(),+ value: sample.value,+ count: 1,+ histogram_bounds: Vec::new(),+ histogram_counts: Vec::new(),+ unit: unit.clone(),+ aggregation_temporality: temporality.to_string(),+ is_monotonic,+ resource_attributes: resource_attributes.clone(),+ instrumentation_scope: String::new(),+ attributes: sample_attributes,+ series_fingerprint,+ });+ }+ }++ if dropped_series > 0 {+ counter!("capture_metrics_remote_write_dropped_series").increment(dropped_series);+ warn!(+ "Dropped {dropped_series} remote-write series with no ingestable samples (native histograms are not yet supported)"+ );+ }++ // Stale markers are routine, so this is counted (for volume visibility) but+ // not warned about, unlike the dropped-series case above.+ if dropped_samples > 0 {+ counter!("capture_metrics_remote_write_dropped_samples").increment(dropped_samples);+ }++ (rows, timestamps_overridden)+}++/// Build the metric-family-name -> (type, unit) map from the optional metadata+/// block. Entries with an unrecognized type are dropped. Shared by the row+/// builder and the expansion estimate so both agree on exactly which units get+/// cloned into rows.+fn build_metadata_map(metadata: &[MetricMetadata]) -> HashMap<String, (MetricType, String)> {+ metadata+ .iter()+ .filter_map(|m| {+ MetricType::try_from(m.r#type)+ .ok()+ .map(|t| (m.metric_family_name.clone(), (t, m.unit.clone())))+ })+ .collect()+}++/// Look up declared metadata, falling back to the base family name —+/// histogram/summary/counter families register under a base name while the+/// exposed series append `_bucket`/`_sum`/`_count`/`_total`.+fn lookup_metadata<'a>(+ metadata: &'a HashMap<String, (MetricType, String)>,+ name: &str,+) -> Option<&'a (MetricType, String)> {+ if let Some(m) = metadata.get(name) {+ return Some(m);+ }+ for suffix in ["_bucket", "_sum", "_count", "_total"] {+ if let Some(base) = name.strip_suffix(suffix) {+ if let Some(m) = metadata.get(base) {+ return Some(m);+ }+ }+ }+ None+}++/// Approximate the bytes the request expands to as `KafkaMetricRow`s: every+/// sample becomes a row carrying a clone of its series' label data, its declared+/// metadata unit, plus fixed per-row overhead. Wire size bounds none of these —+/// a zero-valued `Sample` is 2 wire bytes, and one fat label set or a fat+/// `MetricMetadata.unit` is encoded once but cloned per sample — so this is+/// checked against a multiple of the body limit before any row is built. Also+/// keeps the single Kafka message the batch becomes bounded.+pub fn estimate_expanded_bytes(req: &WriteRequest) -> u64 {+ let metadata = build_metadata_map(&req.metadata);+ req.timeseries+ .iter()+ .map(|series| {+ let label_bytes: u64 = series+ .labels+ .iter()+ .map(|l| (l.name.len() + l.value.len()) as u64)+ .sum();+ // The declared unit is cloned into every row (see `write_request_to_+ // kafka_rows`), so it must be part of the per-row cost — otherwise a+ // fat unit plus many compact samples slips under the cap and only+ // explodes at row-build time. Take the largest candidate rather than+ // one specific `__name__` label: nothing rejects a series carrying+ // several, the builder's loop keeps the last, and an estimate that+ // resolved a different one would under-count by the whole unit.+ let unit_bytes = series+ .labels+ .iter()+ .filter(|l| l.name == METRIC_NAME_LABEL)+ .filter_map(|l| lookup_metadata(&metadata, &l.value))+ .map(|(_, unit)| unit.len() as u64)+ .max()+ .unwrap_or(0);+ (series.samples.len() as u64) * (ROW_OVERHEAD_BYTES + label_bytes + unit_bytes)+ })+ .sum()+}++/// Infer (metric_type, is_monotonic, aggregation_temporality) for a series.+///+/// Prometheus counters, histograms and summaries are cumulative. RW v1 carries+/// no per-sample type, so declared metadata (when present) takes precedence and+/// the `_total`/`_bucket`/`_sum`/`_count` suffix heuristic is the fallback.+/// Classic histograms/summaries are stored as their decomposed scalar component+/// series (queryable via PromQL); native-histogram array reconstruction is+/// deferred.+fn classify(name: &str, declared: Option<MetricType>) -> (&'static str, bool, &'static str) {+ if let Some(t) = declared {+ match t {+ MetricType::Counter => return ("sum", true, "cumulative"),+ MetricType::Gauge => return ("gauge", false, ""),+ // Histogram/Summary expose decomposed cumulative component series;+ // type each component via the suffix heuristic below.+ _ => {}+ }+ }++ if name.ends_with("_total")+ || name.ends_with("_bucket")+ || name.ends_with("_count")+ || name.ends_with("_sum")+ {+ ("sum", true, "cumulative")+ } else {+ ("gauge", false, "")+ }+}++#[derive(Deserialize)]+pub struct RemoteWriteQueryParams {+ token: Option<String>,+}++/// Resolve the project token from (in order) the URL path, the Authorization+/// header (Bearer or bare), or the `token` query param — matching the+/// flexibility remote-write senders actually have.+fn extract_token(+ path_token: Option<String>,+ headers: &HeaderMap,+ query_token: Option<&str>,+) -> Option<String> {+ if let Some(token) = path_token {+ if !token.is_empty() {+ return Some(token);+ }+ }+ if let Some(auth) = headers.get("authorization").and_then(|v| v.to_str().ok()) {+ let token = auth+ .strip_prefix("Bearer ")+ .or_else(|| auth.strip_prefix("bearer "))+ .unwrap_or(auth)+ .trim();+ if !token.is_empty() {+ return Some(token.to_string());+ }+ }+ query_token.filter(|t| !t.is_empty()).map(str::to_string)+}++/// Prometheus remote-write v1 ingestion endpoint.+///+/// Snappy-decodes the protobuf body, maps it to `KafkaMetricRow` records, and+/// produces them through the shared `KafkaSink` so the rest of the pipeline is+/// identical to OTLP ingestion. Response codes follow remote-write semantics:+/// 204 on success, 400 on a permanent decode failure (sender drops the batch),+/// 5xx on a transient produce failure (sender retries).+#[instrument(skip_all, fields(+ token = tracing::field::Empty,+ user_agent = %headers.get("user-agent")+ .and_then(|v| v.to_str().ok())+ .unwrap_or(""),+ content_length = %headers.get("content-length")+ .and_then(|v| v.to_str().ok())+ .unwrap_or("")))+]+pub async fn export_prometheus_remote_write_http(+ State(service): State<Service>,+ path_token: Option<Path<String>>,+ Query(query_params): Query<RemoteWriteQueryParams>,+ headers: HeaderMap,+ body: Bytes,+) -> Result<StatusCode, (StatusCode, Json<serde_json::Value>)> {+ let token = match extract_token(+ path_token.map(|Path(t)| t),+ &headers,+ query_params.token.as_deref(),+ ) {+ Some(token) => token,+ None => {+ error!("No token provided");+ return Err((+ StatusCode::UNAUTHORIZED,+ Json(json!({"error": "No token provided"})),+ ));+ }+ };++ service+ .authorizer+ .authorize_token(&token, Signal::Metrics)?;++ tracing::Span::current().record("token", &token);++ let write_request = match decode_write_request(&body, service.max_request_body_size_bytes) {+ Ok(request) => request,+ Err(e) => {+ error!("Failed to decode remote-write request: {e}");+ return Err((+ StatusCode::BAD_REQUEST,+ Json(json!({ "error": format!("{e}") })),+ ));+ }+ };++ // 400, not 5xx: a batch that expands past the limit will never fit, so the+ // sender must drop it rather than retry it forever.+ let expanded = estimate_expanded_bytes(&write_request);+ let max_expanded = MAX_EXPANSION_FACTOR * service.max_request_body_size_bytes as u64;+ if expanded > max_expanded {+ error!(+ "Rejecting remote-write request expanding to ~{expanded} bytes (limit {max_expanded})"+ );+ return Err((+ StatusCode::BAD_REQUEST,+ Json(json!({+ "error": format!("request expands to too many samples (~{expanded} > {max_expanded} bytes); send smaller batches")+ })),+ ));+ }++ let (rows, timestamps_overridden) = write_request_to_kafka_rows(write_request);+ let row_count = rows.len();++ if let Err(e) = service+ .sink+ .write_metrics(&token, rows, body.len() as u64, timestamps_overridden)+ .await+ {+ error!("Failed to send remote-write metrics to Kafka: {e}");+ return Err((+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(json!({"error": "Internal server error"})),+ ));+ }++ debug!("Sent {row_count} remote-write data points to Kafka");+ Ok(StatusCode::NO_CONTENT)+}diff --git a/rust/capture-logs/src/main.rs b/rust/capture-logs/src/main.rsindex 96f0cb851cc7..560df6904c89 100644--- a/rust/capture-logs/src/main.rs+++ b/rust/capture-logs/src/main.rs@@ -6,6 +6,7 @@ use capture::metrics_middleware::track_metrics;use capture_logs::authorizer::Authorizer;use capture_logs::config::Config;use capture_logs::endpoints::datadog;+use capture_logs::endpoints::prometheus;use capture_logs::kafka::KafkaSink;use capture_logs::middleware::translate_compression_query_param;use capture_logs::service::Service;@@ -180,12 +181,30 @@ async fn main() {"/i/v1/logs/datadog/:token/api/v2/logs",post(datadog::export_datadog_logs_http).options(options_handler),)- .with_state(logs_service)+ .with_state(logs_service.clone()).layer(DefaultBodyLimit::max(config.max_request_body_size_bytes)).layer(axum::middleware::from_fn(track_metrics)).layer(RequestDecompressionLayer::new())- .layer(axum::middleware::from_fn(translate_compression_query_param))- .layer(cors);+ .layer(axum::middleware::from_fn(translate_compression_query_param));++ // Prometheus remote-write sends `Content-Encoding: snappy`, which+ // RequestDecompressionLayer rejects with 415 before the handler runs. This+ // route is deliberately kept off that layer (and the gzip query-param+ // shim); the handler snappy-decodes the body itself.+ let prometheus_router = Router::new()+ .route(+ "/i/v1/prometheus/write",+ post(prometheus::export_prometheus_remote_write_http).options(options_handler),+ )+ .route(+ "/i/v1/prometheus/write/:token",+ post(prometheus::export_prometheus_remote_write_http).options(options_handler),+ )+ .with_state(logs_service)+ .layer(DefaultBodyLimit::max(config.max_request_body_size_bytes))+ .layer(axum::middleware::from_fn(track_metrics));++ let http_router = http_router.merge(prometheus_router).layer(cors);let http_server = tokio::spawn(async move {if let Err(e) = axum::serve(diff --git a/rust/capture-logs/src/metric_record.rs b/rust/capture-logs/src/metric_record.rsindex f8f05cc0bf95..23fbaea2704c 100644--- a/rust/capture-logs/src/metric_record.rs+++ b/rust/capture-logs/src/metric_record.rs@@ -355,7 +355,7 @@ fn build_number_row(/// `metric_type` is part of the identity: a gauge and a sum sharing a name and labels/// are different series, and `metric_series` stores `metric_type` per fingerprint — so/// omitting it would let one type's row silently overwrite the other's on dedup.-fn compute_series_fingerprint(+pub(crate) fn compute_series_fingerprint(metric_name: &str,metric_type: &str,service_name: &str,diff --git a/rust/capture-logs/tests/prometheus_remote_write_test.rs b/rust/capture-logs/tests/prometheus_remote_write_test.rsnew file mode 100644index 000000000000..5460e00c7b29--- /dev/null+++ b/rust/capture-logs/tests/prometheus_remote_write_test.rs@@ -0,0 +1,697 @@+use capture_logs::endpoints::prometheus::{decode_write_request, write_request_to_kafka_rows};+use chrono::{Duration, Utc};+use prometheus_rw_proto::prometheus::v1::{+ metric_metadata::MetricType, Label, MetricMetadata, Sample, TimeSeries, WriteRequest,+};+use prost::Message;++const MAX_DECOMPRESSED: usize = 1 << 20;++fn label(name: &str, value: &str) -> Label {+ Label {+ name: name.to_string(),+ value: value.to_string(),+ }+}++fn series(labels: Vec<Label>, samples: Vec<Sample>) -> TimeSeries {+ TimeSeries { labels, samples }+}++/// A timestamp comfortably within the ±24h window so it is not clamped.+fn now_ms() -> i64 {+ Utc::now().timestamp_millis()+}++#[test]+fn maps_labels_to_name_service_and_attributes() {+ let req = WriteRequest {+ timeseries: vec![series(+ vec![+ label("__name__", "node_cpu_seconds"),+ label("job", "node-exporter"),+ label("instance", "10.0.0.1:9100"),+ label("mode", "idle"),+ ],+ vec![Sample {+ value: 12.5,+ timestamp: now_ms(),+ }],+ )],+ metadata: vec![],+ };++ let (rows, overridden) = write_request_to_kafka_rows(req);++ assert_eq!(rows.len(), 1);+ assert_eq!(overridden, 0);+ let row = &rows[0];+ assert_eq!(row.metric_name, "node_cpu_seconds");+ assert_eq!(row.service_name, "node-exporter");+ assert_eq!(row.metric_type, "gauge");+ assert!(!row.is_monotonic);+ assert_eq!(row.value, 12.5);+ assert_eq!(row.count, 1);+ // Map values are JSON-encoded to match the OTLP/Datadog paths, since the+ // ClickHouse MV applies JSONExtractString to them.+ assert_eq!(+ row.resource_attributes.get("service.name").unwrap(),+ "\"node-exporter\""+ );+ assert_eq!(+ row.resource_attributes.get("service.instance.id").unwrap(),+ "\"10.0.0.1:9100\""+ );+ assert_eq!(row.attributes.get("mode").unwrap(), "\"idle\"");+ // __name__/job/instance are not duplicated into the attributes map.+ assert!(!row.attributes.contains_key("__name__"));+ assert!(!row.attributes.contains_key("job"));+}++#[test]+fn infers_counter_from_total_suffix() {+ let req = WriteRequest {+ timeseries: vec![series(+ vec![+ label("__name__", "http_requests_total"),+ label("job", "api"),+ ],+ vec![Sample {+ value: 99.0,+ timestamp: now_ms(),+ }],+ )],+ metadata: vec![],+ };++ let (rows, _) = write_request_to_kafka_rows(req);++ assert_eq!(rows[0].metric_type, "sum");+ assert!(rows[0].is_monotonic);+ assert_eq!(rows[0].aggregation_temporality, "cumulative");+}++#[test]+fn types_histogram_bucket_as_cumulative_sum() {+ let req = WriteRequest {+ timeseries: vec![series(+ vec![+ label("__name__", "http_req_duration_bucket"),+ label("job", "api"),+ label("le", "0.5"),+ ],+ vec![Sample {+ value: 10.0,+ timestamp: now_ms(),+ }],+ )],+ metadata: vec![],+ };++ let (rows, _) = write_request_to_kafka_rows(req);++ assert_eq!(rows[0].metric_type, "sum");+ assert!(rows[0].is_monotonic);+ assert_eq!(rows[0].aggregation_temporality, "cumulative");+ // The bucket boundary label is preserved so PromQL can reconstruct quantiles.+ assert_eq!(rows[0].attributes.get("le").unwrap(), "\"0.5\"");+}++#[test]+fn metadata_counter_overrides_default_gauge() {+ // A bare name (no _total suffix) would default to gauge, but declared+ // metadata says COUNTER and must win.+ let req = WriteRequest {+ timeseries: vec![series(+ vec![label("__name__", "requests"), label("job", "api")],+ vec![Sample {+ value: 1.0,+ timestamp: now_ms(),+ }],+ )],+ metadata: vec![MetricMetadata {+ r#type: MetricType::Counter as i32,+ metric_family_name: "requests".to_string(),+ help: String::new(),+ unit: String::new(),+ }],+ };++ let (rows, _) = write_request_to_kafka_rows(req);++ assert_eq!(rows[0].metric_type, "sum");+ assert!(rows[0].is_monotonic);+ assert_eq!(rows[0].aggregation_temporality, "cumulative");+}++#[test]+fn emits_one_row_per_sample() {+ let req = WriteRequest {+ timeseries: vec![series(+ vec![label("__name__", "g"), label("job", "j")],+ vec![+ Sample {+ value: 1.0,+ timestamp: now_ms(),+ },+ Sample {+ value: 2.0,+ timestamp: now_ms(),+ },+ Sample {+ value: 3.0,+ timestamp: now_ms(),+ },+ ],+ )],+ metadata: vec![],+ };++ let (rows, _) = write_request_to_kafka_rows(req);++ assert_eq!(rows.len(), 3);+ assert_eq!(+ rows.iter().map(|r| r.value).collect::<Vec<_>>(),+ vec![1.0, 2.0, 3.0]+ );+}++#[test]+fn clamps_far_past_timestamp_and_counts_override() {+ let two_days_ago = (Utc::now() - Duration::hours(48)).timestamp_millis();+ let req = WriteRequest {+ timeseries: vec![series(+ vec![label("__name__", "g"), label("job", "j")],+ vec![Sample {+ value: 1.0,+ timestamp: two_days_ago,+ }],+ )],+ metadata: vec![],+ };++ let (rows, overridden) = write_request_to_kafka_rows(req);++ assert_eq!(overridden, 1);+ assert!(rows[0].attributes.contains_key("$originalTimestamp"));+ // Clamped forward to ~now.+ assert!((Utc::now() - rows[0].timestamp).num_seconds().abs() < 5);+}++#[test]+fn skips_series_without_metric_name() {+ let req = WriteRequest {+ timeseries: vec![series(+ vec![label("job", "j")],+ vec![Sample {+ value: 1.0,+ timestamp: now_ms(),+ }],+ )],+ metadata: vec![],+ };++ let (rows, _) = write_request_to_kafka_rows(req);++ assert!(rows.is_empty());+}++/// Prometheus marks a series stale with a specific NaN payload+/// (`0x7ff0000000000002`) and remote-write forwards it. It must not become a+/// metric value: NaN survives the storage `ifNull` and corrupts rate/aggregate+/// queries. Non-finite samples are dropped before a row is built.+#[test]+fn drops_stale_marker_nan_samples() {+ const STALE_NAN_BITS: u64 = 0x7ff0000000000002;+ let req = WriteRequest {+ timeseries: vec![series(+ vec![+ label("__name__", "http_requests_total"),+ label("job", "api"),+ ],+ vec![+ Sample {+ value: 7.0,+ timestamp: now_ms(),+ },+ Sample {+ value: f64::from_bits(STALE_NAN_BITS),+ timestamp: now_ms() + 1,+ },+ Sample {+ value: f64::INFINITY,+ timestamp: now_ms() + 2,+ },+ ],+ )],+ metadata: vec![],+ };++ let (rows, _) = write_request_to_kafka_rows(req);++ // Only the finite sample survives; the stale marker and the infinity are dropped.+ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0].value, 7.0);+ assert!(rows.iter().all(|r| r.value.is_finite()));+}++#[test]+fn snappy_round_trip_decodes_and_maps() {+ let req = WriteRequest {+ timeseries: vec![series(+ vec![label("__name__", "up"), label("job", "prometheus")],+ vec![Sample {+ value: 1.0,+ timestamp: now_ms(),+ }],+ )],+ metadata: vec![],+ };++ let mut encoded = Vec::new();+ req.encode(&mut encoded).unwrap();+ let compressed = snap::raw::Encoder::new().compress_vec(&encoded).unwrap();++ let decoded =+ decode_write_request(&compressed, MAX_DECOMPRESSED).expect("snappy+protobuf decode");+ let (rows, _) = write_request_to_kafka_rows(decoded);++ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0].metric_name, "up");+ assert_eq!(rows[0].service_name, "prometheus");+}++#[test]+fn rejects_non_snappy_garbage() {+ assert!(decode_write_request(b"not snappy at all", MAX_DECOMPRESSED).is_err());+}++/// The raw-snappy length header is sender-controlled: a tiny body can claim a+/// multi-gigabyte decompressed size, and an uncapped decoder would allocate it+/// before finding out the data is short. The claimed length must be checked+/// against the cap before any allocation happens.+#[test]+fn rejects_decompression_bomb_before_allocating() {+ let req = WriteRequest {+ timeseries: vec![series(+ vec![label("__name__", "up"), label("job", "prometheus")],+ vec![Sample {+ value: 1.0,+ timestamp: now_ms(),+ }],+ )],+ metadata: vec![],+ };+ let mut encoded = Vec::new();+ req.encode(&mut encoded).unwrap();+ let compressed = snap::raw::Encoder::new().compress_vec(&encoded).unwrap();++ // A cap below the (legitimate) decompressed size must reject the payload.+ assert!(decode_write_request(&compressed, encoded.len() - 1).is_err());+ // The same payload passes with an adequate cap, so the rejection above is+ // the cap and not a decode failure.+ assert!(decode_write_request(&compressed, encoded.len()).is_ok());+}++/// The prometheus route is deliberately kept off `RequestDecompressionLayer`, so+/// a `Content-Encoding: snappy` request reaches the handler with the raw body to+/// decode itself — proving the 415 problem is avoided.+#[tokio::test]+async fn snappy_body_reaches_handler_without_decompression_layer() {+ use axum::{body::Body, http::Request, routing::post, Router};+ use bytes::Bytes;+ use tower::ServiceExt;++ async fn echo(body: Bytes) -> Bytes {+ body+ }++ let app = Router::new().route("/i/v1/prometheus/write", post(echo));++ let compressed = snap::raw::Encoder::new().compress_vec(b"hello").unwrap();+ let req = Request::builder()+ .method("POST")+ .uri("/i/v1/prometheus/write")+ .header("content-encoding", "snappy")+ .body(Body::from(compressed.clone()))+ .unwrap();++ let resp = app.oneshot(req).await.unwrap();+ assert!(+ resp.status().is_success(),+ "expected 2xx, got {}",+ resp.status()+ );+ let bytes = axum::body::to_bytes(resp.into_body(), 1 << 20)+ .await+ .unwrap();+ assert_eq!(&bytes[..], compressed.as_slice());+}++/// Regression guard: the layer the OTLP/logs routes use rejects snappy with 415,+/// which is exactly why the prometheus route must not pass through it.+#[tokio::test]+async fn request_decompression_layer_rejects_snappy_with_415() {+ use axum::{body::Body, http::Request, http::StatusCode, routing::post, Router};+ use bytes::Bytes;+ use tower::ServiceExt;+ use tower_http::decompression::RequestDecompressionLayer;++ async fn echo(body: Bytes) -> Bytes {+ body+ }++ let app = Router::new()+ .route("/i/v1/metrics", post(echo))+ .layer(RequestDecompressionLayer::new());++ let compressed = snap::raw::Encoder::new().compress_vec(b"hello").unwrap();+ let req = Request::builder()+ .method("POST")+ .uri("/i/v1/metrics")+ .header("content-encoding", "snappy")+ .body(Body::from(compressed))+ .unwrap();++ let resp = app.oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);+}++/// Series identity is assigned at ingest, exactly as the OTLP path does it:+/// every sample of one series carries the same fingerprint, and any identity+/// field (name, labels, inferred type) changing yields a different one.+#[test]+fn assigns_stable_series_fingerprints_at_ingest() {+ let req = WriteRequest {+ timeseries: vec![+ series(+ vec![+ label("__name__", "http_requests_total"),+ label("job", "api"),+ label("route", "/checkout"),+ ],+ vec![+ Sample {+ value: 1.0,+ timestamp: now_ms(),+ },+ Sample {+ value: 2.0,+ timestamp: now_ms() + 1,+ },+ ],+ ),+ series(+ vec![+ label("__name__", "http_requests_total"),+ label("job", "api"),+ label("route", "/cart"),+ ],+ vec![Sample {+ value: 5.0,+ timestamp: now_ms(),+ }],+ ),+ ],+ metadata: vec![],+ };++ let (rows, _) = write_request_to_kafka_rows(req);++ assert_eq!(rows.len(), 3);+ assert_ne!(+ rows[0].series_fingerprint, 0,+ "fingerprint must be assigned"+ );+ assert_eq!(+ rows[0].series_fingerprint, rows[1].series_fingerprint,+ "samples of one series share a fingerprint"+ );+ assert_ne!(+ rows[0].series_fingerprint, rows[2].series_fingerprint,+ "a different label set is a different series"+ );+}++/// A clamped timestamp adds $originalTimestamp to the row's attributes but must+/// never split the series: identity is computed before the synthetic attribute.+#[test]+fn overridden_timestamps_do_not_split_series_identity() {+ let req = WriteRequest {+ timeseries: vec![series(+ vec![+ label("__name__", "restore_lag_seconds"),+ label("job", "api"),+ ],+ vec![+ Sample {+ value: 1.0,+ timestamp: now_ms(),+ },+ Sample {+ value: 2.0,+ // Far outside the accept window: gets clamped + annotated.+ timestamp: (Utc::now() - Duration::days(30)).timestamp_millis(),+ },+ ],+ )],+ metadata: vec![],+ };++ let (rows, overridden) = write_request_to_kafka_rows(req);++ assert_eq!(rows.len(), 2);+ assert_eq!(overridden, 1);+ assert!(rows[1].attributes.contains_key("$originalTimestamp"));+ assert_eq!(+ rows[0].series_fingerprint, rows[1].series_fingerprint,+ "the synthetic $originalTimestamp attribute must not change identity"+ );+}++/// Declared metadata units must reach the row, including on decomposed+/// component series that look up their family by stripped suffix.+#[test]+fn metadata_unit_reaches_rows() {+ let req = WriteRequest {+ timeseries: vec![+ series(+ vec![label("__name__", "req_duration"), label("job", "api")],+ vec![Sample {+ value: 0.2,+ timestamp: now_ms(),+ }],+ ),+ series(+ vec![+ label("__name__", "req_duration_bucket"),+ label("job", "api"),+ label("le", "0.5"),+ ],+ vec![Sample {+ value: 3.0,+ timestamp: now_ms(),+ }],+ ),+ ],+ metadata: vec![MetricMetadata {+ r#type: MetricType::Histogram as i32,+ metric_family_name: "req_duration".to_string(),+ help: String::new(),+ unit: "seconds".to_string(),+ }],+ };++ let (rows, _) = write_request_to_kafka_rows(req);++ assert_eq!(rows.len(), 2);+ assert_eq!(rows[0].unit, "seconds");+ assert_eq!(rows[1].unit, "seconds", "suffix fallback carries the unit");+}++#[test]+fn rows_without_metadata_have_empty_unit() {+ let req = WriteRequest {+ timeseries: vec![series(+ vec![label("__name__", "up"), label("job", "api")],+ vec![Sample {+ value: 1.0,+ timestamp: now_ms(),+ }],+ )],+ metadata: vec![],+ };++ let (rows, _) = write_request_to_kafka_rows(req);++ assert_eq!(rows[0].unit, "");+}++/// A size-compliant body can still decode into a huge number of samples (a+/// zero-valued Sample is 2 wire bytes), each of which becomes a row cloning+/// the series label map — and the whole batch is one Kafka message. The+/// expansion estimate must flag such payloads before any row is built.+#[test]+fn estimates_expansion_of_many_samples_and_fat_labels() {+ use capture_logs::endpoints::prometheus::estimate_expanded_bytes;++ // A realistic vmagent-sized batch stays far under a 16x cap on a 2 MiB body.+ let realistic = WriteRequest {+ timeseries: (0..1000)+ .map(|i| {+ series(+ vec![+ label("__name__", &format!("some_metric_{i}_total")),+ label("job", "api"),+ label("instance", "10.0.0.1:9100"),+ label("route", "/checkout/step/confirm"),+ ],+ (0..10)+ .map(|_| Sample {+ value: 1.0,+ timestamp: now_ms(),+ })+ .collect(),+ )+ })+ .collect(),+ metadata: vec![],+ };+ assert!(estimate_expanded_bytes(&realistic) < 16 * 2 * 1024 * 1024);++ // One series, one million empty samples: tiny on the wire, enormous expanded.+ let sample_bomb = WriteRequest {+ timeseries: vec![series(+ vec![label("__name__", "m")],+ vec![+ Sample {+ value: 0.0,+ timestamp: 0,+ };+ 1_000_000+ ],+ )],+ metadata: vec![],+ };+ assert!(estimate_expanded_bytes(&sample_bomb) > 16 * 2 * 1024 * 1024);++ // Fat label value cloned into tens of thousands of rows.+ let label_bomb = WriteRequest {+ timeseries: vec![series(+ vec![+ label("__name__", "m"),+ label("blob", &"x".repeat(1024 * 1024)),+ ],+ vec![+ Sample {+ value: 0.0,+ timestamp: 0,+ };+ 50_000+ ],+ )],+ metadata: vec![],+ };+ assert!(estimate_expanded_bytes(&label_bomb) > 16 * 2 * 1024 * 1024);+}++/// A fat declared `MetricMetadata.unit` is cloned into every row, so it must+/// count toward the expansion estimate. Without it, ~100k compact samples plus+/// a ~1 MiB unit estimate to only ~28 MiB (under the 16x * 2 MiB cap) yet blow+/// up to hundreds of GB at row-build time.+#[test]+fn estimates_expansion_of_fat_metadata_unit() {+ use capture_logs::endpoints::prometheus::estimate_expanded_bytes;++ let compact_samples: Vec<Sample> = (0..100_000)+ .map(|_| Sample {+ value: 1.0,+ timestamp: 0,+ })+ .collect();+ let req = WriteRequest {+ timeseries: vec![series(+ vec![label("__name__", "requests_total"), label("job", "api")],+ compact_samples,+ )],+ metadata: vec![MetricMetadata {+ r#type: MetricType::Counter as i32,+ metric_family_name: "requests_total".to_string(),+ help: String::new(),+ unit: "u".repeat(1024 * 1024),+ }],+ };++ assert!(estimate_expanded_bytes(&req) > 16 * 2 * 1024 * 1024);+}++/// Pins the row builder's name resolution: its label loop reassigns on every+/// `__name__`, so the *last* one wins. The expansion estimate must agree, which+/// the next test guards.+#[test]+fn builder_resolves_unit_from_the_last_metric_name_label() {+ let req = WriteRequest {+ timeseries: vec![series(+ vec![label("__name__", "first"), label("__name__", "second")],+ vec![Sample {+ value: 1.0,+ timestamp: now_ms(),+ }],+ )],+ metadata: vec![+ MetricMetadata {+ r#type: MetricType::Gauge as i32,+ metric_family_name: "first".to_string(),+ help: String::new(),+ unit: "bytes".to_string(),+ },+ MetricMetadata {+ r#type: MetricType::Gauge as i32,+ metric_family_name: "second".to_string(),+ help: String::new(),+ unit: "seconds".to_string(),+ },+ ],+ };++ let (rows, _) = write_request_to_kafka_rows(req);++ assert_eq!(rows[0].metric_name, "second");+ assert_eq!(rows[0].unit, "seconds");+}++/// A duplicate `__name__` must not hide a fat unit from the expansion cap. The+/// builder clones the unit of the *last* name into every row, so an estimate+/// that resolves only the first name under-counts by an attacker-chosen amount+/// and lets the payload through to explode at row-build time.+/// Estimate-only on purpose: actually building these rows is the OOM.+#[test]+fn duplicate_metric_name_cannot_hide_a_fat_unit_from_the_cap() {+ use capture_logs::endpoints::prometheus::estimate_expanded_bytes;++ const SAMPLES: usize = 10_000;+ let fat_unit = "u".repeat(512 * 1024);+ let req = WriteRequest {+ timeseries: vec![series(+ vec![label("__name__", "unmatched"), label("__name__", "fat")],+ vec![+ Sample {+ value: 0.0,+ timestamp: 0,+ };+ SAMPLES+ ],+ )],+ metadata: vec![MetricMetadata {+ r#type: MetricType::Gauge as i32,+ metric_family_name: "fat".to_string(),+ help: String::new(),+ unit: fat_unit.clone(),+ }],+ };++ assert!(+ estimate_expanded_bytes(&req) >= (SAMPLES * fat_unit.len()) as u64,+ "estimate must include the unit the builder will clone per row"+ );+}diff --git a/rust/prometheus-rw-proto/Cargo.toml b/rust/prometheus-rw-proto/Cargo.tomlnew file mode 100644index 000000000000..cf7cf2da55db--- /dev/null+++ b/rust/prometheus-rw-proto/Cargo.toml@@ -0,0 +1,17 @@+[package]+name = "prometheus-rw-proto"+version = "0.1.0"+edition = "2021"+publish = false++[dependencies]+prost = { workspace = true }++[build-dependencies]+tonic-build = { workspace = true }++[package.metadata.cargo-shear]+ignored = ["prost"]++[lints]+workspace = truediff --git a/rust/prometheus-rw-proto/build.rs b/rust/prometheus-rw-proto/build.rsnew file mode 100644index 000000000000..22b96add478f--- /dev/null+++ b/rust/prometheus-rw-proto/build.rs@@ -0,0 +1,13 @@+fn main() -> Result<(), Box<dyn std::error::Error>> {+ let proto_root = std::env::var("PROTO_ROOT").unwrap_or_else(|_| "../../proto".to_string());++ // Messages only — no gRPC service in this proto, so skip server/client codegen.+ tonic_build::configure()+ .build_server(false)+ .build_client(false)+ .compile_protos(+ &[format!("{proto_root}/prometheus/v1/remote_write.proto")],+ &[proto_root],+ )?;+ Ok(())+}diff --git a/rust/prometheus-rw-proto/src/lib.rs b/rust/prometheus-rw-proto/src/lib.rsnew file mode 100644index 000000000000..798abbb915f2--- /dev/null+++ b/rust/prometheus-rw-proto/src/lib.rs@@ -0,0 +1,8 @@+pub mod prometheus {+ pub mod v1 {+ // No gRPC service in this proto, so the generated file is pure prost+ // message types with no tonic dependency — include it directly rather+ // than via tonic::include_proto!.+ include!(concat!(env!("OUT_DIR"), "/prometheus.v1.rs"));+ }+}