: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-apm): write native rows for remote histograms (#104583)
Frank Hamanddf2c6fc8818a
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex e3533d086162..c04ed6805b05 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2278,6 +2278,7 @@ dependencies = ["limiters","metrics","opentelemetry-proto 0.29.0",+ "prometheus-rw-proto","prost 0.13.5","rustls 0.23.37","serde",@@ -2288,6 +2289,7 @@ dependencies = ["tower-http 0.5.2","tracing","tracing-subscriber",+ "uuid",][[package]]diff --git a/rust/capture-apm-metrics/Cargo.toml b/rust/capture-apm-metrics/Cargo.tomlindex dbb593a5699f..1c4e7039adc5 100644--- a/rust/capture-apm-metrics/Cargo.toml+++ b/rust/capture-apm-metrics/Cargo.toml@@ -15,6 +15,7 @@ common-alloc = { path = "../common/alloc" }limiters = { path = "../common/limiters" }capture = { path = "../capture" }capture-logs = { path = "../capture-logs" }+prometheus-rw-proto = { path = "../prometheus-rw-proto" }common-compression = { path = "../common/compression" }common-redis = { path = "../common/redis" }# redis leaves the rustls provider to the binary, so `rediss://` needs one installed here.@@ -31,6 +32,7 @@ serde = { workspace = true }serde_json = { workspace = true }siphasher = { workspace = true }thiserror = { workspace = true }+uuid = { workspace = true }[lints]workspace = truediff --git a/rust/capture-apm-metrics/README.md b/rust/capture-apm-metrics/README.mdindex 377402467d4f..78bb62d5f00f 100644--- a/rust/capture-apm-metrics/README.md+++ b/rust/capture-apm-metrics/README.md@@ -30,6 +30,18 @@ Pull metrics, all with a `kind` label of `seed` or `periodic`: `capture_metrics_The cache is bounded. When the global or the per-token cap is full, a new series keeps its labels on every row and is not cached or pushed to Redis, until pruning frees a slot. `capture_metrics_series_cache_full` counts those rows.+## Classic Prometheus histograms on remote write++Prometheus sends a classic histogram as one `_bucket` series for each bucket. Each bucket has an `le` label. Prometheus also sends `_count` and `_sum` series.++The service converts these component samples to one native histogram row when a request contains `_sum` and the `+Inf` bucket for the same label set and timestamp. The native row has `histogram_bounds` and `histogram_counts`. It uses the same series fingerprint as an equivalent OTLP histogram.++Conversion requires cumulative bucket values that are non-negative integers and do not decrease. If `_count` is present, it must equal the `+Inf` bucket. The service does not convert a family that metadata defines as a summary, counter, or gauge. Other component samples stay as normal rows. This preserves data when a sender divides a histogram across requests. Queries must combine native and normal rows by label set.++The service converts `le` and `quantile` label values to Go's shortest float format on every row. For example, `1.0` becomes `1` and `1000000` becomes `1e+06`. The series fingerprint uses the converted label value.++Metrics: `capture_metrics_remote_write_histograms_assembled` counts native rows. `capture_metrics_remote_write_histogram_samples_folded` counts converted component samples. `capture_metrics_remote_write_histogram_components_passed_through` counts component samples that stay as normal rows.+## Running the service```bashdiff --git a/rust/capture-apm-metrics/src/histogram_assembly.rs b/rust/capture-apm-metrics/src/histogram_assembly.rsnew file mode 100644index 000000000000..20f53664be9a--- /dev/null+++ b/rust/capture-apm-metrics/src/histogram_assembly.rs@@ -0,0 +1,336 @@+//! Converts component rows of a classic Prometheus histogram (`_bucket`,+//! `_count`, `_sum`) to one native histogram row. The remote-write code calls+//! this module after `capture-logs` builds the rows and before the series label+//! gate.+//!+//! The module converts a histogram only when one request has its `_sum` series+//! and `+Inf` bucket for the same label set and timestamp. Bucket values must+//! be consistent. Other component rows stay unchanged. This preserves data+//! when a sender divides a histogram across requests. Query code must combine+//! native and normal rows by label set.+//!+//! The module converts `le` and `quantile` label values to Go's shortest float+//! format. Therefore, `le="1.0"` and `le="1"` identify the same series.++use std::collections::HashMap;++use capture_logs::metric_record::{compute_series_fingerprint, KafkaMetricRow};+use chrono::{DateTime, Utc};+use metrics::counter;+use prometheus_rw_proto::prometheus::v1::{metric_metadata::MetricType, MetricMetadata};+use serde_json::json;+use uuid::Uuid;++const LE_LABEL: &str = "le";+const QUANTILE_LABEL: &str = "quantile";+const ORIGINAL_TIMESTAMP_LABEL: &str = "$originalTimestamp";+const BUCKET_SUFFIX: &str = "_bucket";+const COUNT_SUFFIX: &str = "_count";+const SUM_SUFFIX: &str = "_sum";+const SUM_TYPE: &str = "sum";+const HISTOGRAM_TYPE: &str = "histogram";++/// Converts `le` and `quantile` labels, then converts complete classic+/// histograms to native rows. Native rows come first. Other rows keep their+/// original order.+pub fn fold_classic_histograms(+ mut rows: Vec<KafkaMetricRow>,+ metadata: &[MetricMetadata],+) -> Vec<KafkaMetricRow> {+ normalize_float_labels(&mut rows);+ let declared: HashMap<&str, MetricType> = metadata+ .iter()+ .filter_map(|m| {+ MetricType::try_from(m.r#type)+ .ok()+ .map(|t| (m.metric_family_name.as_str(), t))+ })+ .collect();++ let mut groups: HashMap<HistogramKey, HistogramParts> = HashMap::new();+ let mut order: Vec<HistogramKey> = Vec::new();+ let mut component_rows = 0u64;+ for (index, row) in rows.iter().enumerate() {+ let Some((base_name, component)) = histogram_component(row, &declared) else {+ continue;+ };+ component_rows += 1;+ let skip = matches!(component, HistogramComponent::Bucket(_)).then_some(LE_LABEL);+ let key = HistogramKey {+ base_name,+ service_name: row.service_name.clone(),+ resource_attributes: sorted_pairs(&row.resource_attributes, None),+ attributes: sorted_pairs(&row.attributes, skip),+ timestamp: row.timestamp,+ };+ if !groups.contains_key(&key) {+ order.push(key.clone());+ }+ let parts = groups.entry(key).or_default();+ match component {+ HistogramComponent::Bucket(le) => parts.buckets.push((le, row.value, index)),+ HistogramComponent::Count => parts.counts.push((row.value, index)),+ HistogramComponent::Sum => parts.sums.push((row.value, index)),+ }+ }++ let mut consumed = vec![false; rows.len()];+ let mut folded = Vec::new();+ for key in order {+ let parts = &groups[&key];+ let Some(histogram) = assemble_histogram(parts) else {+ continue;+ };+ let Some((_, sum_index)) = parts.sums.last() else {+ continue;+ };+ for (_, _, index) in &parts.buckets {+ consumed[*index] = true;+ }+ for (_, index) in parts.counts.iter().chain(&parts.sums) {+ consumed[*index] = true;+ }+ let sum_row = &rows[*sum_index];+ let resource_attributes: HashMap<String, String> =+ key.resource_attributes.iter().cloned().collect();+ let attributes: HashMap<String, String> = key.attributes.iter().cloned().collect();+ let series_fingerprint = compute_series_fingerprint(+ &key.base_name,+ HISTOGRAM_TYPE,+ &key.service_name,+ &resource_attributes,+ &attributes,+ );+ folded.push(KafkaMetricRow {+ uuid: Uuid::now_v7().to_string(),+ trace_id: String::new(),+ span_id: String::new(),+ trace_flags: 0,+ timestamp: key.timestamp,+ observed_timestamp: sum_row.observed_timestamp,+ service_name: key.service_name,+ metric_name: key.base_name,+ metric_type: HISTOGRAM_TYPE.to_string(),+ value: histogram.sum,+ count: histogram.total,+ histogram_bounds: histogram.bounds,+ histogram_counts: histogram.counts,+ unit: sum_row.unit.clone(),+ aggregation_temporality: "cumulative".to_string(),+ is_monotonic: false,+ resource_attributes,+ instrumentation_scope: String::new(),+ attributes,+ series_fingerprint,+ has_labels: true,+ retention_days: sum_row.retention_days,+ });+ }++ let folded_rows = consumed.iter().filter(|consumed| **consumed).count() as u64;+ if !folded.is_empty() {+ counter!("capture_metrics_remote_write_histograms_assembled")+ .increment(folded.len() as u64);+ counter!("capture_metrics_remote_write_histogram_samples_folded").increment(folded_rows);+ }+ if component_rows > folded_rows {+ counter!("capture_metrics_remote_write_histogram_components_passed_through")+ .increment(component_rows - folded_rows);+ }++ folded.extend(+ rows.into_iter()+ .zip(consumed)+ .filter_map(|(row, is_consumed)| (!is_consumed).then_some(row)),+ );+ folded+}++fn normalize_float_labels(rows: &mut [KafkaMetricRow]) {+ for row in rows {+ let mut changed = false;+ for label in [LE_LABEL, QUANTILE_LABEL] {+ let Some(value) = row.attributes.get_mut(label) else {+ continue;+ };+ let Ok(decoded) = serde_json::from_str::<String>(value) else {+ continue;+ };+ let normalized = normalize_float_label(&decoded);+ if normalized != decoded {+ *value = json!(normalized).to_string();+ changed = true;+ }+ }+ if changed {+ let mut attributes = row.attributes.clone();+ attributes.remove(ORIGINAL_TIMESTAMP_LABEL);+ row.series_fingerprint = compute_series_fingerprint(+ &row.metric_name,+ &row.metric_type,+ &row.service_name,+ &row.resource_attributes,+ &attributes,+ );+ }+ }+}++/// Formats a float as Go's `strconv.FormatFloat(v, 'g', -1, 64)` does.+/// Returns an unparseable value unchanged.+pub fn normalize_float_label(value: &str) -> String {+ let Ok(parsed) = value.trim().parse::<f64>() else {+ return value.to_string();+ };+ format_float_shortest(parsed)+}++fn format_float_shortest(value: f64) -> String {+ if value.is_nan() {+ return "NaN".to_string();+ }+ if value.is_infinite() {+ return if value > 0.0 { "+Inf" } else { "-Inf" }.to_string();+ }+ if value == 0.0 {+ return if value.is_sign_negative() { "-0" } else { "0" }.to_string();+ }+ let scientific = format!("{value:e}");+ let (mantissa, exponent) = scientific+ .split_once('e')+ .unwrap_or((scientific.as_str(), "0"));+ let exponent: i32 = exponent.parse().unwrap_or(0);+ if !(-4..=5).contains(&exponent) {+ let sign = if exponent < 0 { '-' } else { '+' };+ return format!("{mantissa}e{sign}{:02}", exponent.abs());+ }+ format!("{value}")+}++#[derive(Clone, Copy)]+enum HistogramComponent {+ Bucket(f64),+ Count,+ Sum,+}++fn histogram_component(+ row: &KafkaMetricRow,+ declared: &HashMap<&str, MetricType>,+) -> Option<(String, HistogramComponent)> {+ if row.metric_type != SUM_TYPE || row.attributes.contains_key(ORIGINAL_TIMESTAMP_LABEL) {+ return None;+ }+ let name = row.metric_name.as_str();+ let (base, component) = if let Some(base) = name.strip_suffix(BUCKET_SUFFIX) {+ let le: String = serde_json::from_str(row.attributes.get(LE_LABEL)?).ok()?;+ (base, HistogramComponent::Bucket(le.parse::<f64>().ok()?))+ } else if let Some(base) = name.strip_suffix(COUNT_SUFFIX) {+ (base, HistogramComponent::Count)+ } else {+ (name.strip_suffix(SUM_SUFFIX)?, HistogramComponent::Sum)+ };+ if base.is_empty() {+ return None;+ }+ match declared.get(base) {+ None | Some(MetricType::Histogram) => Some((base.to_string(), component)),+ Some(_) => None,+ }+}++#[derive(Clone, Hash, PartialEq, Eq)]+struct HistogramKey {+ base_name: String,+ service_name: String,+ resource_attributes: Vec<(String, String)>,+ attributes: Vec<(String, String)>,+ timestamp: DateTime<Utc>,+}++#[derive(Default)]+struct HistogramParts {+ buckets: Vec<(f64, f64, usize)>,+ counts: Vec<(f64, usize)>,+ sums: Vec<(f64, usize)>,+}++struct AssembledHistogram {+ bounds: Vec<f64>,+ counts: Vec<i64>,+ total: i64,+ sum: f64,+}++fn sorted_pairs(map: &HashMap<String, String>, skip: Option<&str>) -> Vec<(String, String)> {+ let mut pairs: Vec<(String, String)> = map+ .iter()+ .filter(|(key, _)| Some(key.as_str()) != skip)+ .map(|(key, value)| (key.clone(), value.clone()))+ .collect();+ pairs.sort_unstable();+ pairs+}++/// A histogram is converted only when it has `_sum` and `+Inf` bucket values.+/// Bucket values must be non-negative integers that do not decrease. A present+/// `_count` value must equal the `+Inf` bucket value.+fn assemble_histogram(parts: &HistogramParts) -> Option<AssembledHistogram> {+ let (sum, _) = *parts.sums.last()?;+ if parts.sums.iter().any(|(value, _)| *value != sum) {+ return None;+ }+ let mut buckets: Vec<(f64, f64)> = parts+ .buckets+ .iter()+ .map(|(le, value, _)| (*le, *value))+ .collect();+ if buckets.iter().any(|(le, _)| le.is_nan()) {+ return None;+ }+ buckets.sort_by(|a, b| a.0.total_cmp(&b.0));+ buckets.dedup_by(|a, b| a.0 == b.0 && a.1 == b.1);+ if buckets.windows(2).any(|pair| pair[0].0 == pair[1].0) {+ return None;+ }+ let (last_le, total_value) = *buckets.last()?;+ if !(last_le.is_infinite() && last_le > 0.0) {+ return None;+ }+ if parts.counts.iter().any(|(count, _)| *count != total_value) {+ return None;+ }+ let total = integral_count(total_value)?;+ let mut bounds = Vec::with_capacity(buckets.len() - 1);+ let mut counts = Vec::with_capacity(buckets.len());+ let mut previous = 0i64;+ for (le, value) in &buckets[..buckets.len() - 1] {+ if le.is_infinite() {+ return None;+ }+ let cumulative = integral_count(*value)?;+ if cumulative < previous {+ return None;+ }+ bounds.push(*le);+ counts.push(cumulative - previous);+ previous = cumulative;+ }+ if total < previous {+ return None;+ }+ counts.push(total - previous);+ Some(AssembledHistogram {+ bounds,+ counts,+ total,+ sum,+ })+}++fn integral_count(value: f64) -> Option<i64> {+ if !value.is_finite() || value < 0.0 || value.fract() != 0.0 || value > i64::MAX as f64 {+ return None;+ }+ Some(value as i64)+}diff --git a/rust/capture-apm-metrics/src/lib.rs b/rust/capture-apm-metrics/src/lib.rsindex 0aabd3547633..870b814fd03a 100644--- a/rust/capture-apm-metrics/src/lib.rs+++ b/rust/capture-apm-metrics/src/lib.rs@@ -1,4 +1,5 @@pub mod config;+pub mod histogram_assembly;pub mod management;pub mod prometheus;pub mod series_label_gate;diff --git a/rust/capture-apm-metrics/src/prometheus.rs b/rust/capture-apm-metrics/src/prometheus.rsindex 0520921ca3ac..412af1638da9 100644--- a/rust/capture-apm-metrics/src/prometheus.rs+++ b/rust/capture-apm-metrics/src/prometheus.rs@@ -10,13 +10,15 @@ use axum::Json;use bytes::Bytes;use capture_logs::authorizer::Signal;use capture_logs::endpoints::prometheus::{- decode_write_request, estimate_expanded_bytes, write_request_to_kafka_rows, RemoteWriteEncoding,+ decode_write_request, estimate_expanded_bytes, write_timeseries_to_kafka_rows,+ RemoteWriteEncoding,};use metrics::counter;use serde::Deserialize;use serde_json::json;use tracing::{debug, error, instrument};+use crate::histogram_assembly::fold_classic_histograms;use crate::service::MetricsService;/// How much larger than the (already decompression-capped) request body the@@ -142,7 +144,9 @@ pub async fn export_prometheus_remote_write_http());}- let (mut rows, timestamps_overridden) = write_request_to_kafka_rows(write_request);+ let (rows, timestamps_overridden) =+ write_timeseries_to_kafka_rows(write_request.timeseries, &write_request.metadata);+ let mut rows = fold_classic_histograms(rows, &write_request.metadata);service.series_label_gate.apply(&token, &mut rows);let row_count = rows.len();diff --git a/rust/capture-apm-metrics/tests/histogram_assembly_test.rs b/rust/capture-apm-metrics/tests/histogram_assembly_test.rsnew file mode 100644index 000000000000..2c9080ec4763--- /dev/null+++ b/rust/capture-apm-metrics/tests/histogram_assembly_test.rs@@ -0,0 +1,575 @@+use std::collections::HashMap;++use capture_apm_metrics::histogram_assembly::{fold_classic_histograms, normalize_float_label};+use capture_logs::endpoints::prometheus::write_request_to_kafka_rows;+use capture_logs::metric_record::{flatten_metric, KafkaMetricRow};+use chrono::{Duration, Utc};+use opentelemetry_proto::tonic::common::v1::{any_value, AnyValue, KeyValue};+use opentelemetry_proto::tonic::metrics::v1::{+ metric::Data, Histogram, HistogramDataPoint, Metric,+};+use opentelemetry_proto::tonic::resource::v1::Resource;+use prometheus_rw_proto::prometheus::v1::{+ metric_metadata::MetricType, Label, MetricMetadata, Sample, TimeSeries, WriteRequest,+};++fn label(name: &str, value: &str) -> Label {+ Label {+ name: name.to_string(),+ value: value.to_string(),+ }+}++fn sample(value: f64, timestamp: i64) -> Sample {+ Sample { value, timestamp }+}++fn now_ms() -> i64 {+ Utc::now().timestamp_millis()+}++fn labelled(name: &str, extra: &[(&str, &str)], samples: Vec<Sample>) -> TimeSeries {+ let mut labels = vec![label("__name__", name), label("job", "api")];+ labels.extend(extra.iter().map(|(name, value)| label(name, value)));+ TimeSeries { labels, samples }+}++fn bucket(base: &str, extra: &[(&str, &str)], le: &str, samples: Vec<Sample>) -> TimeSeries {+ let mut series = labelled(&format!("{base}_bucket"), extra, samples);+ series.labels.push(label("le", le));+ series+}++fn fold(request: WriteRequest) -> Vec<KafkaMetricRow> {+ let metadata = request.metadata.clone();+ let (rows, _) = write_request_to_kafka_rows(request);+ fold_classic_histograms(rows, &metadata)+}++/// Creates a complete classic histogram with 0.5, 1, and `+Inf` buckets,+/// plus `_count` and `_sum` samples.+fn complete_histogram_request(timestamp: i64) -> WriteRequest {+ let route = &[("route", "/checkout")];+ WriteRequest {+ timeseries: vec![+ bucket(+ "http_req_duration_seconds",+ route,+ "0.5",+ vec![sample(2.0, timestamp)],+ ),+ bucket(+ "http_req_duration_seconds",+ route,+ "1.0",+ vec![sample(5.0, timestamp)],+ ),+ bucket(+ "http_req_duration_seconds",+ route,+ "+Inf",+ vec![sample(10.0, timestamp)],+ ),+ labelled(+ "http_req_duration_seconds_count",+ route,+ vec![sample(10.0, timestamp)],+ ),+ labelled(+ "http_req_duration_seconds_sum",+ route,+ vec![sample(12.5, timestamp)],+ ),+ ],+ metadata: vec![],+ }+}++fn plain_rows(rows: &[KafkaMetricRow]) -> Vec<&KafkaMetricRow> {+ rows.iter()+ .filter(|row| row.metric_type != "histogram")+ .collect()+}++#[test]+fn folds_complete_classic_histogram_into_one_native_row() {+ let timestamp = now_ms();+ let rows = fold(complete_histogram_request(timestamp));++ assert_eq!(rows.len(), 1, "five component rows fold into one: {rows:?}");+ let row = &rows[0];+ assert_eq!(row.metric_name, "http_req_duration_seconds");+ assert_eq!(row.metric_type, "histogram");+ assert_eq!(row.aggregation_temporality, "cumulative");+ assert!(!row.is_monotonic);+ assert!(row.has_labels);+ assert_eq!(row.service_name, "api");+ assert_eq!(row.histogram_bounds, vec![0.5, 1.0]);+ assert_eq!(row.histogram_counts, vec![2, 3, 5]);+ assert_eq!(row.count, 10);+ assert_eq!(row.value, 12.5);+ assert_eq!(row.timestamp.timestamp_millis(), timestamp);+ assert_eq!(row.attributes.get("route").unwrap(), "\"/checkout\"");+ assert!(!row.attributes.contains_key("le"));+ assert_eq!(+ row.resource_attributes.get("service.name").unwrap(),+ "\"api\""+ );+}++#[test]+fn equivalent_duplicate_components_fold_into_one_native_row() {+ let timestamp = now_ms();+ let route = &[("route", "/cart")];+ let rows = fold(WriteRequest {+ timeseries: vec![+ bucket("d", route, "+Inf", vec![sample(10.0, timestamp)]),+ labelled(+ "d_count",+ route,+ vec![sample(10.0, timestamp), sample(10.0, timestamp)],+ ),+ labelled(+ "d_sum",+ route,+ vec![sample(12.5, timestamp), sample(12.5, timestamp)],+ ),+ ],+ metadata: vec![],+ });++ assert_eq!(+ rows.len(),+ 1,+ "duplicate components must not remain: {rows:?}"+ );+ assert_eq!(rows[0].metric_type, "histogram");+ assert_eq!(rows[0].count, 10);+ assert_eq!(rows[0].value, 12.5);+}++#[test]+fn folded_histogram_shares_identity_with_the_otlp_path() {+ let timestamp = now_ms();+ let mut request = complete_histogram_request(timestamp);+ for series in &mut request.timeseries {+ series.labels.push(label("instance", "10.0.0.1:9100"));+ }+ let rows = fold(request);+ assert_eq!(rows.len(), 1);++ let string_value = |value: &str| AnyValue {+ value: Some(any_value::Value::StringValue(value.to_string())),+ };+ let key_value = |key: &str, value: &str| KeyValue {+ key: key.to_string(),+ value: Some(string_value(value)),+ };+ let resource = Resource {+ attributes: vec![+ key_value("service.name", "api"),+ key_value("service.instance.id", "10.0.0.1:9100"),+ ],+ ..Default::default()+ };+ let metric = Metric {+ name: "http_req_duration_seconds".to_string(),+ description: String::new(),+ unit: String::new(),+ metadata: vec![],+ data: Some(Data::Histogram(Histogram {+ aggregation_temporality: 2,+ data_points: vec![HistogramDataPoint {+ attributes: vec![+ key_value("route", "/checkout"),+ key_value("instance", "10.0.0.1:9100"),+ ],+ start_time_unix_nano: 0,+ time_unix_nano: timestamp as u64 * 1_000_000,+ count: 10,+ sum: Some(12.5),+ bucket_counts: vec![2, 3, 5],+ explicit_bounds: vec![0.5, 1.0],+ exemplars: vec![],+ flags: 0,+ min: None,+ max: None,+ }],+ })),+ };+ let (otlp_rows, _) = flatten_metric(metric, Some(&resource), None).expect("flatten_metric ok");++ assert_eq!(otlp_rows.len(), 1);+ assert_eq!(rows[0].series_fingerprint, otlp_rows[0].series_fingerprint);+ assert_eq!(rows[0].attributes, otlp_rows[0].attributes);+ assert_eq!(+ rows[0].resource_attributes,+ otlp_rows[0].resource_attributes+ );+ assert_eq!(rows[0].histogram_bounds, otlp_rows[0].histogram_bounds);+ assert_eq!(rows[0].histogram_counts, otlp_rows[0].histogram_counts);+}++#[test]+fn folds_one_histogram_row_per_timestamp() {+ let first = now_ms();+ let second = first + 60_000;+ let route = &[("route", "/cart")];+ let rows = fold(WriteRequest {+ timeseries: vec![+ bucket(+ "d",+ route,+ "1",+ vec![sample(1.0, first), sample(4.0, second)],+ ),+ bucket(+ "d",+ route,+ "+Inf",+ vec![sample(3.0, first), sample(9.0, second)],+ ),+ labelled(+ "d_sum",+ route,+ vec![sample(1.5, first), sample(7.5, second)],+ ),+ ],+ metadata: vec![],+ });++ assert_eq!(rows.len(), 2);+ assert!(rows.iter().all(|row| row.metric_type == "histogram"));+ let by_time: HashMap<i64, &KafkaMetricRow> = rows+ .iter()+ .map(|row| (row.timestamp.timestamp_millis(), row))+ .collect();+ assert_eq!(by_time[&first].histogram_counts, vec![1, 2]);+ assert_eq!(by_time[&second].histogram_counts, vec![4, 5]);+ assert_eq!(+ by_time[&first].series_fingerprint,+ by_time[&second].series_fingerprint+ );+}++#[test]+fn folds_partial_bucket_sets_when_inf_and_sum_are_present() {+ let timestamp = now_ms();+ let route = &[("route", "/cart")];+ let rows = fold(WriteRequest {+ timeseries: vec![+ bucket("d", route, "0.5", vec![sample(2.0, timestamp)]),+ bucket("d", route, "+Inf", vec![sample(10.0, timestamp)]),+ labelled("d_sum", route, vec![sample(12.5, timestamp)]),+ ],+ metadata: vec![],+ });++ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0].histogram_bounds, vec![0.5]);+ assert_eq!(rows[0].histogram_counts, vec![2, 8]);+ assert_eq!(rows[0].count, 10);+}++#[test]+fn incomplete_histograms_stay_plain_rows() {+ let timestamp = now_ms();+ let route = &[("route", "/cart")];+ let without_inf = WriteRequest {+ timeseries: vec![+ bucket("d", route, "0.5", vec![sample(2.0, timestamp)]),+ bucket("d", route, "1", vec![sample(5.0, timestamp)]),+ labelled("d_count", route, vec![sample(10.0, timestamp)]),+ labelled("d_sum", route, vec![sample(12.5, timestamp)]),+ ],+ metadata: vec![],+ };+ let without_sum = WriteRequest {+ timeseries: vec![+ bucket("d", route, "0.5", vec![sample(2.0, timestamp)]),+ bucket("d", route, "+Inf", vec![sample(10.0, timestamp)]),+ labelled("d_count", route, vec![sample(10.0, timestamp)]),+ ],+ metadata: vec![],+ };+ for (name, request, want) in [+ ("without +Inf", without_inf, 4),+ ("without _sum", without_sum, 3),+ ] {+ let rows = fold(request);+ assert_eq!(rows.len(), want, "{name}: {rows:?}");+ assert!(rows+ .iter()+ .all(|row| row.metric_type == "sum" && row.count == 1));+ }+}++#[test]+fn inconsistent_histograms_stay_plain_rows() {+ let timestamp = now_ms();+ let route = &[("route", "/cart")];+ let count_mismatch = WriteRequest {+ timeseries: vec![+ bucket("d", route, "+Inf", vec![sample(10.0, timestamp)]),+ labelled("d_count", route, vec![sample(11.0, timestamp)]),+ labelled("d_sum", route, vec![sample(12.5, timestamp)]),+ ],+ metadata: vec![],+ };+ let decreasing = WriteRequest {+ timeseries: vec![+ bucket("d", route, "0.5", vec![sample(6.0, timestamp)]),+ bucket("d", route, "1", vec![sample(5.0, timestamp)]),+ bucket("d", route, "+Inf", vec![sample(10.0, timestamp)]),+ labelled("d_sum", route, vec![sample(12.5, timestamp)]),+ ],+ metadata: vec![],+ };+ let fractional = WriteRequest {+ timeseries: vec![+ bucket("d", route, "+Inf", vec![sample(10.5, timestamp)]),+ labelled("d_sum", route, vec![sample(12.5, timestamp)]),+ ],+ metadata: vec![],+ };+ let declared_summary = WriteRequest {+ timeseries: vec![+ labelled("latency_count", route, vec![sample(10.0, timestamp)]),+ labelled("latency_sum", route, vec![sample(12.5, timestamp)]),+ ],+ metadata: vec![MetricMetadata {+ r#type: MetricType::Summary as i32,+ metric_family_name: "latency".to_string(),+ help: String::new(),+ unit: String::new(),+ }],+ };+ for (name, request) in [+ ("count mismatch", count_mismatch),+ ("decreasing buckets", decreasing),+ ("fractional count", fractional),+ ("declared summary", declared_summary),+ ] {+ let rows = fold(request);+ assert!(!rows.is_empty(), "{name}");+ assert_eq!(plain_rows(&rows).len(), rows.len(), "{name}: {rows:?}");+ }++ for (name, count_values, sum_values) in [+ (+ "conflicting duplicate count",+ &[11.0, 10.0][..],+ &[12.5][..],+ ),+ ("conflicting duplicate sum", &[10.0][..], &[13.5, 12.5][..]),+ ] {+ let rows = fold(WriteRequest {+ timeseries: vec![+ bucket("d", route, "+Inf", vec![sample(10.0, timestamp)]),+ labelled(+ "d_count",+ route,+ count_values+ .iter()+ .map(|value| sample(*value, timestamp))+ .collect(),+ ),+ labelled(+ "d_sum",+ route,+ sum_values+ .iter()+ .map(|value| sample(*value, timestamp))+ .collect(),+ ),+ ],+ metadata: vec![],+ });++ assert_eq!(+ rows.len(),+ 1 + count_values.len() + sum_values.len(),+ "{name}: {rows:?}"+ );+ assert_eq!(plain_rows(&rows).len(), rows.len(), "{name}: {rows:?}");+ }+}++#[test]+fn different_label_sets_fold_separately() {+ let timestamp = now_ms();+ let mut request = complete_histogram_request(timestamp);+ let other = &[("route", "/cart")];+ request.timeseries.extend(vec![+ bucket(+ "http_req_duration_seconds",+ other,+ "+Inf",+ vec![sample(4.0, timestamp)],+ ),+ labelled(+ "http_req_duration_seconds_sum",+ other,+ vec![sample(1.0, timestamp)],+ ),+ ]);++ let rows = fold(request);++ assert_eq!(rows.len(), 2);+ assert!(rows.iter().all(|row| row.metric_type == "histogram"));+ assert_ne!(rows[0].series_fingerprint, rows[1].series_fingerprint);+ let cart = rows+ .iter()+ .find(|row| row.attributes.get("route").unwrap() == "\"/cart\"")+ .unwrap();+ assert!(cart.histogram_bounds.is_empty());+ assert_eq!(cart.histogram_counts, vec![4]);+}++#[test]+fn stale_component_samples_do_not_block_other_timestamps() {+ let first = now_ms();+ let second = first + 60_000;+ let route = &[("route", "/cart")];+ let rows = fold(WriteRequest {+ timeseries: vec![+ bucket(+ "d",+ route,+ "+Inf",+ vec![sample(3.0, first), sample(f64::NAN, second)],+ ),+ labelled(+ "d_sum",+ route,+ vec![sample(1.5, first), sample(2.5, second)],+ ),+ ],+ metadata: vec![],+ });++ assert_eq!(rows.len(), 2, "{rows:?}");+ assert_eq!(rows[0].metric_type, "histogram");+ assert_eq!(rows[0].timestamp.timestamp_millis(), first);+ assert_eq!(rows[1].metric_type, "sum");+ assert_eq!(rows[1].metric_name, "d_sum");+ assert_eq!(rows[1].timestamp.timestamp_millis(), second);+}++#[test]+fn clamped_timestamps_are_not_folded() {+ let old = (Utc::now() - Duration::days(30)).timestamp_millis();+ let route = &[("route", "/cart")];+ let request = WriteRequest {+ timeseries: vec![+ bucket("d", route, "0.5", vec![sample(2.0, old)]),+ bucket("d", route, "+Inf", vec![sample(10.0, old)]),+ labelled("d_sum", route, vec![sample(12.5, old)]),+ ],+ metadata: vec![],+ };+ let (library_rows, overridden) = write_request_to_kafka_rows(request.clone());+ let rows = fold(request);++ assert_eq!(overridden, 3);+ assert_eq!(rows.len(), 3);+ assert_eq!(plain_rows(&rows).len(), 3);+ assert!(rows+ .iter()+ .all(|row| row.attributes.contains_key("$originalTimestamp")));+ let fingerprints = |rows: &[KafkaMetricRow]| -> Vec<i64> {+ rows.iter().map(|row| row.series_fingerprint).collect()+ };+ assert_eq!(fingerprints(&rows), fingerprints(&library_rows));+}++#[test]+fn normalizes_le_and_quantile_labels_and_refreshes_fingerprints() {+ let timestamp = now_ms();+ let request = WriteRequest {+ timeseries: vec![+ bucket("d", &[], "1.0", vec![sample(2.0, timestamp)]),+ bucket("d", &[], "1e+06", vec![sample(2.0, timestamp)]),+ bucket("d", &[], "1000000", vec![sample(2.0, timestamp)]),+ bucket("d", &[], "+inf", vec![sample(2.0, timestamp)]),+ labelled(+ "latency",+ &[("quantile", "0.50")],+ vec![sample(2.0, timestamp)],+ ),+ bucket("e", &[], "1", vec![sample(2.0, timestamp)]),+ ],+ metadata: vec![],+ };+ let (library_rows, _) = write_request_to_kafka_rows(request.clone());+ let rows = fold(request);++ assert_eq!(rows.len(), 6);+ let le_values: Vec<&str> = rows[..4]+ .iter()+ .map(|row| row.attributes.get("le").unwrap().as_str())+ .collect();+ assert_eq!(+ le_values,+ vec!["\"1\"", "\"1e+06\"", "\"1e+06\"", "\"+Inf\""]+ );+ assert_eq!(rows[4].attributes.get("quantile").unwrap(), "\"0.5\"");+ assert_eq!(+ rows[1].series_fingerprint, rows[2].series_fingerprint,+ "normalized le values share a series"+ );+ assert_ne!(+ rows[0].series_fingerprint, library_rows[0].series_fingerprint,+ "a changed le label gets a new fingerprint"+ );+ assert_eq!(+ rows[5].series_fingerprint, library_rows[5].series_fingerprint,+ "an unchanged le label keeps its fingerprint"+ );+ let (canonical_rows, _) = write_request_to_kafka_rows(WriteRequest {+ timeseries: vec![bucket("d", &[], "1", vec![sample(2.0, timestamp)])],+ metadata: vec![],+ });+ assert_eq!(+ rows[0].series_fingerprint, canonical_rows[0].series_fingerprint,+ "le=1.0 and le=1 are one series"+ );+}++#[test]+fn float_label_normalization_matches_go_shortest_formatting() {+ for (input, want) in [+ ("0.005", "0.005"),+ ("0.5", "0.5"),+ ("1", "1"),+ ("1.0", "1"),+ ("2.5", "2.5"),+ ("10", "10"),+ ("100000", "100000"),+ ("999999.5", "999999.5"),+ ("123456.789", "123456.789"),+ ("1000000", "1e+06"),+ ("1234567.89", "1.23456789e+06"),+ ("1e7", "1e+07"),+ ("1e15", "1e+15"),+ ("1e20", "1e+20"),+ ("1e21", "1e+21"),+ ("0.0001", "0.0001"),+ ("0.00012", "0.00012"),+ ("0.00005", "5e-05"),+ ("7.5e-5", "7.5e-05"),+ ("1.5e-7", "1.5e-07"),+ ("3.0000000000000004", "3.0000000000000004"),+ ("-2.5", "-2.5"),+ ("0", "0"),+ ("+Inf", "+Inf"),+ ("inf", "+Inf"),+ ("-Inf", "-Inf"),+ ("NaN", "NaN"),+ ("not a number", "not a number"),+ ("", ""),+ ] {+ assert_eq!(normalize_float_label(input), want, "input {input:?}");+ }+}diff --git a/rust/capture-logs/src/endpoints/prometheus.rs b/rust/capture-logs/src/endpoints/prometheus.rsindex 02d62a3de236..580e208c145e 100644--- a/rust/capture-logs/src/endpoints/prometheus.rs+++ b/rust/capture-logs/src/endpoints/prometheus.rs@@ -8,7 +8,7 @@ use bytes::Bytes;use chrono::{TimeZone, Utc};use metrics::counter;use prometheus_rw_proto::prometheus::v1::{- metric_metadata::MetricType, MetricMetadata, WriteRequest,+ metric_metadata::MetricType, MetricMetadata, TimeSeries, WriteRequest,};use prost::Message;use serde::Deserialize;@@ -126,17 +126,24 @@ pub fn decode_write_request(/// 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) {+ write_timeseries_to_kafka_rows(req.timeseries, &req.metadata)+}++pub fn write_timeseries_to_kafka_rows(+ timeseries: Vec<TimeSeries>,+ metadata: &[MetricMetadata],+) -> (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 metadata = build_metadata_map(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 {+ for series in timeseries {let mut metric_name = String::new();let mut service_name = String::new();let mut resource_attributes: HashMap<String, String> = HashMap::new();diff --git a/rust/capture-logs/src/metric_record.rs b/rust/capture-logs/src/metric_record.rsindex 2bc1257b81f2..864d9619be19 100644--- a/rust/capture-logs/src/metric_record.rs+++ b/rust/capture-logs/src/metric_record.rs@@ -359,7 +359,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.-pub(crate) fn compute_series_fingerprint(+pub fn compute_series_fingerprint(metric_name: &str,metric_type: &str,service_name: &str,