: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): improve v1 observability coverage (#63353)
Eli Reismand3c74f9dc3d9
diff --git a/rust/capture/src/v1/analytics/constants.rs b/rust/capture/src/v1/analytics/constants.rsindex 57877c2212da..03088df5cc11 100644--- a/rust/capture/src/v1/analytics/constants.rs+++ b/rust/capture/src/v1/analytics/constants.rs@@ -48,9 +48,6 @@ pub(super) const CAPTURE_V1_OVERFLOW_ROUTED: &str = "capture_v1_events_rerouted_/// Counter/gauge key for the per-token global rate limiter.pub(crate) const CAPTURE_V1_RATE_LIMITER: &str = "capture_v1_rate_limiter";-/// Counter for events with an illegal distinct_id (person processing disabled).-pub(super) const CAPTURE_V1_ILLEGAL_DISTINCT_ID: &str = "capture_v1_illegal_distinct_id";-/// Detail tag for events flagged by the per-token:distinct_id rate limiter./// Matches the OpenAPI BatchEntryStatusError example for `result: warning`.pub(super) const DETAIL_PERSON_PROCESSING_DISABLED: &str = "person_processing_disabled";@@ -110,3 +107,15 @@ pub(super) const ILLEGAL_DISTINCT_IDS: &[&str] = &[/// Events whose skew-adjusted timestamp is more than 23 hours in the future/// (in milliseconds) are clamped to server `now`.pub(super) const FUTURE_EVENT_HOURS_CUTOFF_MS: i64 = 23 * 3600 * 1000;++/// Counter for adjustments applied to accepted events (label: reason).+/// Counts adjustments, NOT unique events — a single event may trigger more+/// than one reason emission.+pub(super) const CAPTURE_V1_EVENT_ADJUSTMENTS_APPLIED: &str =+ "capture_v1_event_adjustments_applied";++/// Counter for non-drop event-restriction actions applied (label: action).+pub(super) const CAPTURE_V1_EVENTS_RESTRICTED: &str = "capture_v1_events_restricted";++/// Counter for per-request batch outcome mix (labels: outcome, path).+pub(super) const CAPTURE_V1_BATCH_OUTCOMES: &str = "capture_v1_batch_outcomes";diff --git a/rust/capture/src/v1/analytics/handler.rs b/rust/capture/src/v1/analytics/handler.rsindex dc78b0aa37f1..63bb4f908947 100644--- a/rust/capture/src/v1/analytics/handler.rs+++ b/rust/capture/src/v1/analytics/handler.rs@@ -68,7 +68,7 @@ pub async fn handle_request(err})?;- metrics::histogram!(CAPTURE_V1_PAYLOAD_SIZE, "stage" => "compressed")+ metrics::histogram!(CAPTURE_V1_PAYLOAD_SIZE, "stage" => "compressed", "encoding" => v1::util::encoding_tag(context.content_encoding.as_deref())).record(raw_bytes.len() as f64);let payload = v1::util::decompress_payload(@@ -83,7 +83,7 @@ pub async fn handle_request(err})?;- metrics::histogram!(CAPTURE_V1_PAYLOAD_SIZE, "stage" => "decompressed")+ metrics::histogram!(CAPTURE_V1_PAYLOAD_SIZE, "stage" => "decompressed", "encoding" => v1::util::encoding_tag(context.content_encoding.as_deref())).record(payload.len() as f64);let batch: Batch = serde_json::from_slice(&payload).map_err(|e| {diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rsindex 7eec29c15c5a..1b4040146237 100644--- a/rust/capture/src/v1/analytics/process.rs+++ b/rust/capture/src/v1/analytics/process.rs@@ -5,10 +5,11 @@ use uuid::Uuid;use super::constants::{CAPTURE_V1_DISTINCT_ID_MAX_SIZE, CAPTURE_V1_EVENTS_DROPPED,- CAPTURE_V1_EVENTS_REROUTED_HISTORICAL, CAPTURE_V1_ILLEGAL_DISTINCT_ID,- CAPTURE_V1_MAX_EVENT_NAME_LENGTH, CAPTURE_V1_OVERFLOW_ROUTED, CAPTURE_V1_PARSED_EVENTS,- CAPTURE_V1_RATE_LIMITER, DETAIL_EVENT_RESTRICTION_DROP, DETAIL_PERSON_PROCESSING_DISABLED,- FUTURE_EVENT_HOURS_CUTOFF_MS, ILLEGAL_DISTINCT_IDS,+ CAPTURE_V1_EVENTS_REROUTED_HISTORICAL, CAPTURE_V1_EVENTS_RESTRICTED,+ CAPTURE_V1_EVENT_ADJUSTMENTS_APPLIED, CAPTURE_V1_MAX_EVENT_NAME_LENGTH,+ CAPTURE_V1_OVERFLOW_ROUTED, CAPTURE_V1_PARSED_EVENTS, CAPTURE_V1_RATE_LIMITER,+ DETAIL_EVENT_RESTRICTION_DROP, DETAIL_PERSON_PROCESSING_DISABLED, FUTURE_EVENT_HOURS_CUTOFF_MS,+ ILLEGAL_DISTINCT_IDS,};use super::response::BatchResponse;use super::types::{Batch, Event, EventResult, WrappedEvent};@@ -227,7 +228,8 @@ fn validate_events(context: &Context, batch: Batch) -> Result<Vec<WrappedEvent>,}if illegal_distinct_id_count > 0 {- metrics::counter!(CAPTURE_V1_ILLEGAL_DISTINCT_ID).increment(illegal_distinct_id_count);+ metrics::counter!(CAPTURE_V1_EVENT_ADJUSTMENTS_APPLIED, "reason" => "person_processing_disabled")+ .increment(illegal_distinct_id_count);crate::ctx_log!(Level::INFO,context,@@ -316,6 +318,8 @@ fn normalize_timestamp(let adjusted = raw_event_ts - context.clock_skew();let now = context.server_received_at;if adjusted.signed_duration_since(now).num_milliseconds() > FUTURE_EVENT_HOURS_CUTOFF_MS {+ metrics::counter!(CAPTURE_V1_EVENT_ADJUSTMENTS_APPLIED, "reason" => "future_timestamp_clamp")+ .increment(1);return now;}adjusted@@ -434,16 +438,24 @@ async fn apply_restrictions(// the explicit guard makes the invariant ordering-independent.if applied.force_overflow() && event.destination == Destination::AnalyticsMain {event.destination = Destination::Overflow;+ metrics::counter!(CAPTURE_V1_EVENTS_RESTRICTED, "action" => "force_overflow")+ .increment(1);}if let Some(topic) = applied.redirect_to_topic() {event.destination = Destination::Custom(topic.to_string());+ metrics::counter!(CAPTURE_V1_EVENTS_RESTRICTED, "action" => "redirect_to_topic")+ .increment(1);}if applied.redirect_to_dlq() {event.destination = Destination::Dlq;+ metrics::counter!(CAPTURE_V1_EVENTS_RESTRICTED, "action" => "redirect_to_dlq")+ .increment(1);}if applied.skip_person_processing() {event.force_disable_person_processing = true;+ metrics::counter!(CAPTURE_V1_EVENTS_RESTRICTED, "action" => "skip_person_processing")+ .increment(1);}}}diff --git a/rust/capture/src/v1/analytics/response.rs b/rust/capture/src/v1/analytics/response.rsindex b57d8ccc4cca..37a7eefe4b51 100644--- a/rust/capture/src/v1/analytics/response.rs+++ b/rust/capture/src/v1/analytics/response.rs@@ -4,7 +4,7 @@ use serde::ser::{SerializeMap, SerializeStruct};use serde::Serialize;use uuid::Uuid;-use super::constants::DEFAULT_RETRY_AFTER_SECS;+use super::constants::{CAPTURE_V1_BATCH_OUTCOMES, DEFAULT_RETRY_AFTER_SECS};use super::types::{EventResult, WrappedEvent};use crate::v1::context::Context;@@ -49,7 +49,6 @@ impl BatchResponse {/// Build the response from a processed batch of WrappedEvents./// Call this after sink publishing and result merging are complete.pub fn build(ctx: &Context, events: &[WrappedEvent]) -> Self {- let _ = ctx; // Context reserved for future per-response metadatalet mut has_retry = false;let entries: Vec<(Uuid, BatchEntryStatus)> = events.iter()@@ -67,6 +66,11 @@ impl BatchResponse {}).collect();+ if let Some(outcome) = classify_batch(events) {+ metrics::counter!(CAPTURE_V1_BATCH_OUTCOMES, "outcome" => outcome, "path" => ctx.path)+ .increment(1);+ }+Self { has_retry, entries }}@@ -75,6 +79,30 @@ impl BatchResponse {}}+/// Classify the outcome mix of a processed batch for the+/// `capture_v1_batch_outcomes` counter. `Warning` counts toward "all_ok"+/// (the event was still accepted). Returns `None` for an empty batch.+fn classify_batch(events: &[WrappedEvent]) -> Option<&'static str> {+ if events.is_empty() {+ return None;+ }+ let all_ok_or_warn = events+ .iter()+ .all(|e| matches!(e.result, EventResult::Ok | EventResult::Warning));+ let all_drop = events.iter().all(|e| e.result == EventResult::Drop);+ let all_retry = events.iter().all(|e| e.result == EventResult::Retry);++ Some(if all_ok_or_warn {+ "all_ok"+ } else if all_drop {+ "all_drop"+ } else if all_retry {+ "all_retry"+ } else {+ "partial_failure"+ })+}+/// Wrapper for serializing the response body as `{"results": {uuid: status, ...}}`.struct ResponseBody<'a>(&'a [(Uuid, BatchEntryStatus)]);@@ -209,6 +237,65 @@ mod tests {);}+ #[test]+ fn classify_batch_all_ok() {+ let events = vec![+ make_wrapped(EventResult::Ok, None),+ make_wrapped(EventResult::Ok, None),+ ];+ assert_eq!(classify_batch(&events), Some("all_ok"));+ }++ #[test]+ fn classify_batch_ok_and_warning_counts_as_all_ok() {+ let events = vec![+ make_wrapped(EventResult::Ok, None),+ make_wrapped(EventResult::Warning, Some("person_processing_disabled")),+ ];+ assert_eq!(classify_batch(&events), Some("all_ok"));+ }++ #[test]+ fn classify_batch_all_drop() {+ let events = vec![+ make_wrapped(EventResult::Drop, Some("billing_limit_exceeded")),+ make_wrapped(EventResult::Drop, Some("billing_limit_exceeded")),+ ];+ assert_eq!(classify_batch(&events), Some("all_drop"));+ }++ #[test]+ fn classify_batch_all_retry() {+ let events = vec![+ make_wrapped(EventResult::Retry, Some("not_persisted")),+ make_wrapped(EventResult::Retry, Some("not_persisted")),+ ];+ assert_eq!(classify_batch(&events), Some("all_retry"));+ }++ #[test]+ fn classify_batch_ok_and_drop_is_partial_failure() {+ let events = vec![+ make_wrapped(EventResult::Ok, None),+ make_wrapped(EventResult::Drop, Some("billing_limit_exceeded")),+ ];+ assert_eq!(classify_batch(&events), Some("partial_failure"));+ }++ #[test]+ fn classify_batch_drop_and_retry_is_partial_failure() {+ let events = vec![+ make_wrapped(EventResult::Drop, Some("billing_limit_exceeded")),+ make_wrapped(EventResult::Retry, Some("not_persisted")),+ ];+ assert_eq!(classify_batch(&events), Some("partial_failure"));+ }++ #[test]+ fn classify_batch_empty_is_none() {+ assert_eq!(classify_batch(&[]), None);+ }+#[test]fn batch_response_build_all_ok() {let ctx = test_utils::test_context();diff --git a/rust/capture/src/v1/constants.rs b/rust/capture/src/v1/constants.rsindex 05c8fc4350a2..d9edd2239e54 100644--- a/rust/capture/src/v1/constants.rs+++ b/rust/capture/src/v1/constants.rs@@ -52,6 +52,9 @@ pub(super) const CAPTURE_V1_WARNING_METRIC: &str = "capture_v1_analytics_warning/// Counter name for body-read timeouts during payload extraction.pub(super) const CAPTURE_V1_BODY_READ_TIMEOUT: &str = "capture_v1_body_read_timeout_total";+/// Counter for streaming decompression failures (label: encoding).+pub(super) const CAPTURE_V1_DECOMPRESSION_ERRORS: &str = "capture_v1_decompression_errors_total";+/// Histogram of events per request batch. The `_batch_size` suffix picks up/// the shared BATCH_SIZES buckets configured in prometheus.rs.pub(super) const CAPTURE_V1_EVENT_BATCH_SIZE: &str = "capture_v1_event_batch_size";diff --git a/rust/capture/src/v1/sinks/DESIGN.md b/rust/capture/src/v1/sinks/DESIGN.mdindex 9e733e6a603e..b61bfa6f3b9d 100644--- a/rust/capture/src/v1/sinks/DESIGN.md+++ b/rust/capture/src/v1/sinks/DESIGN.md@@ -884,10 +884,24 @@ request-level context (`path`, `attempt`).| Metric | Type | Labels | When ||---|---|---|---|-| `capture_v1_kafka_publish_total` | counter | `mode`, `cluster`, `outcome`, `path`, `attempt` | Every event outcome (success, error, timeout, reject) |-| `capture_v1_kafka_ack_duration_seconds` | histogram | `mode`, `cluster`, `outcome`, `path`, `attempt` | Successful ack only |+| `capture_v1_kafka_publish_total` | counter | `mode`, `cluster`, `outcome`, `path`, `attempt` (capped at "6+"), `destination` | Every event outcome (success, error, timeout, reject) |+| `capture_v1_kafka_ack_duration_seconds` | histogram | `mode`, `cluster`, `outcome`, `path`, `attempt` (capped at "6+"), `destination` | Successful ack only || `capture_v1_kafka_queue_full_retries_total` | counter | `mode`, `cluster`, `result` | QueueFull retry (`result` = `recovered` or `exhausted`) |+Cardinality note: the `destination` label is bounded at 9 values+(`Destination::as_tag()` collapses all `Custom(_)` topics to `custom`)+and the client-controlled `attempt` label is capped at `6+`, so+`capture_v1_kafka_publish_total` stays low-cardinality.++#### Related pipeline metrics (emitted upstream of the sink)++| Metric | Type | Labels | When |+|---|---|---|---|+| `capture_v1_event_adjustments_applied` | counter | `reason` (`future_timestamp_clamp`, `person_processing_disabled`) | An adjustment is applied to an accepted event. Counts adjustments, NOT unique events — one event can emit more than one reason. |+| `capture_v1_events_restricted` | counter | `action` | Non-drop event-restriction action applied |+| `capture_v1_batch_outcomes` | counter | `outcome`, `path` | One increment per request batch. `Warning` results count toward `all_ok` (the event was still accepted). |+| `capture_v1_decompression_errors_total` | counter | `encoding` | Streaming decompression failure |+#### Summary-level (post-batch)| Metric | Type | Labels | When |diff --git a/rust/capture/src/v1/sinks/kafka/sink.rs b/rust/capture/src/v1/sinks/kafka/sink.rsindex 3d5caa769727..37c34b72108f 100644--- a/rust/capture/src/v1/sinks/kafka/sink.rs+++ b/rust/capture/src/v1/sinks/kafka/sink.rs@@ -48,7 +48,22 @@ struct MetricLabels {sink: &'static str,mode: &'static str,path: &'static str,- attempt: metrics::SharedString,+ attempt: &'static str,+}++/// Map the client-controlled attempt number to a bounded static label value.+/// Attempts 0-5 map to themselves; 6 or more bucket into "6+" as a+/// cardinality defense (the label reads literally: "6 or more").+fn attempt_tag(attempt: u32) -> &'static str {+ match attempt {+ 0 => "0",+ 1 => "1",+ 2 => "2",+ 3 => "3",+ 4 => "4",+ 5 => "5",+ _ => "6+",+ }}pub struct KafkaSink<P: KafkaProducerTrait> {@@ -85,15 +100,23 @@ fn reject_publishable() -> Vec<Box<dyn SinkResult>> {let enqueued_at = Utc::now();let publishable: Vec<_> = events.iter().filter(|e| e.should_publish()).collect();- counter!(- "capture_v1_kafka_publish_total",- "mode" => labels.mode,- "cluster" => labels.sink,- "outcome" => Outcome::RetriableError.as_tag(),- "path" => labels.path,- "attempt" => labels.attempt.clone(),- )- .increment(publishable.len() as u64);+ let mut by_dest: std::collections::HashMap<&'static str, u64> =+ std::collections::HashMap::new();+ for e in &publishable {+ *by_dest.entry(e.destination().as_tag()).or_default() += 1;+ }+ for (dest_tag, count) in &by_dest {+ counter!(+ "capture_v1_kafka_publish_total",+ "mode" => labels.mode,+ "cluster" => labels.sink,+ "outcome" => Outcome::RetriableError.as_tag(),+ "path" => labels.path,+ "attempt" => labels.attempt,+ "destination" => *dest_tag,+ )+ .increment(*count);+ }publishable.into_iter().map(|e| -> Box<dyn SinkResult> {@@ -111,6 +134,7 @@ type AckFuture = Pin<dyn Future<Output = (Uuid,+ &'static str,DateTime<Utc>,Result<(), super::producer::ProduceError>,),@@ -132,7 +156,7 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {enqueued_at: DateTime<Utc>,results: &mut Vec<Box<dyn SinkResult>>,pending: &mut FuturesUnordered<AckFuture>,- enqueued_keys: &mut Vec<Uuid>,+ enqueued_keys: &mut Vec<(Uuid, &'static str)>,) {let mut payload_buf = String::with_capacity(4096);let mut key_buf = String::with_capacity(128);@@ -143,6 +167,7 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {}let uuid = event.uuid();+ let dest_tag = event.destination().as_tag();let topic = match self.config.kafka.topic_for(event.destination()) {Some(t) => t,@@ -165,7 +190,8 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {"cluster" => labels.sink,"outcome" => Outcome::FatalError.as_tag(),"path" => labels.path,- "attempt" => labels.attempt.clone(),+ "attempt" => labels.attempt,+ "destination" => dest_tag,).increment(1);results.push(Box::new(KafkaResult::err(@@ -217,10 +243,10 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {).increment(1);}- enqueued_keys.push(uuid);+ enqueued_keys.push((uuid, dest_tag));pending.push(Box::pin(async move {let result = ack_future.await;- (uuid, Utc::now(), result)+ (uuid, dest_tag, Utc::now(), result)}));break;}@@ -249,7 +275,8 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {"cluster" => labels.sink,"outcome" => outcome.as_tag(),"path" => labels.path,- "attempt" => labels.attempt.clone(),+ "attempt" => labels.attempt,+ "destination" => dest_tag,).increment(1);results.push(Box::new(KafkaResult::err(uuid, sink_err, enqueued_at)));@@ -277,7 +304,7 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {loop {match tokio::time::timeout_at(deadline, pending.next()).await {- Ok(Some((uuid, completed_at, ack))) => {+ Ok(Some((uuid, dest_tag, completed_at, ack))) => {resolved_keys.insert(uuid);let outcome_tag = match &ack {@@ -297,7 +324,8 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {"cluster" => labels.sink,"outcome" => outcome_tag,"path" => labels.path,- "attempt" => labels.attempt.clone(),+ "attempt" => labels.attempt,+ "destination" => dest_tag,).increment(1);@@ -309,7 +337,8 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {"cluster" => labels.sink,"outcome" => outcome_tag,"path" => labels.path,- "attempt" => labels.attempt.clone(),+ "attempt" => labels.attempt,+ "destination" => dest_tag,).record(secs.as_secs_f64());}@@ -336,28 +365,36 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {fn collect_timeouts(labels: &MetricLabels,enqueued_at: DateTime<Utc>,- enqueued_keys: Vec<Uuid>,+ enqueued_keys: Vec<(Uuid, &'static str)>,resolved_keys: &HashSet<Uuid>,results: &mut Vec<Box<dyn SinkResult>>,) {- let timed_out_keys: Vec<_> = enqueued_keys+ let timed_out: Vec<_> = enqueued_keys.into_iter()- .filter(|k| !resolved_keys.contains(k))+ .filter(|(k, _)| !resolved_keys.contains(k)).collect();- if timed_out_keys.is_empty() {+ if timed_out.is_empty() {return;}- counter!(- "capture_v1_kafka_publish_total",- "mode" => labels.mode,- "cluster" => labels.sink,- "outcome" => Outcome::Timeout.as_tag(),- "path" => labels.path,- "attempt" => labels.attempt.clone(),- )- .increment(timed_out_keys.len() as u64);+ let mut by_dest: std::collections::HashMap<&'static str, u64> =+ std::collections::HashMap::new();+ for (_, dest_tag) in &timed_out {+ *by_dest.entry(dest_tag).or_default() += 1;+ }+ for (dest_tag, count) in &by_dest {+ counter!(+ "capture_v1_kafka_publish_total",+ "mode" => labels.mode,+ "cluster" => labels.sink,+ "outcome" => Outcome::Timeout.as_tag(),+ "path" => labels.path,+ "attempt" => labels.attempt,+ "destination" => *dest_tag,+ )+ .increment(*count);+ }let gave_up_at = Utc::now();- for uuid in timed_out_keys {+ for (uuid, _) in timed_out {results.push(Box::new(KafkaResult::err(uuid, KafkaSinkError::Timeout, enqueued_at).with_completed_at(gave_up_at),@@ -381,7 +418,7 @@ impl<P: KafkaProducerTrait + 'static> Sink for KafkaSink<P> {sink: self.name.as_str(),mode: self.capture_mode.as_tag(),path: ctx.path,- attempt: ctx.attempt.to_string().into(),+ attempt: attempt_tag(ctx.attempt),};if !self.producer.is_ready() {@@ -398,7 +435,7 @@ impl<P: KafkaProducerTrait + 'static> Sink for KafkaSink<P> {let enqueued_at = Utc::now();let mut results: Vec<Box<dyn SinkResult>> = Vec::new();let mut pending: FuturesUnordered<AckFuture> = FuturesUnordered::new();- let mut enqueued_keys: Vec<Uuid> = Vec::new();+ let mut enqueued_keys: Vec<(Uuid, &'static str)> = Vec::new();self.enqueue_events(ctx,@@ -495,3 +532,25 @@ mod effective_partition_key_tests {assert_eq!(effective_partition_key("k", force_disable, &dest), expected);}}++#[cfg(test)]+mod attempt_tag_tests {+ use super::attempt_tag;++ #[test]+ fn maps_in_range_attempts_to_exact_values() {+ assert_eq!(attempt_tag(0), "0");+ assert_eq!(attempt_tag(1), "1");+ assert_eq!(attempt_tag(2), "2");+ assert_eq!(attempt_tag(3), "3");+ assert_eq!(attempt_tag(4), "4");+ assert_eq!(attempt_tag(5), "5");+ }++ #[test]+ fn caps_out_of_range_attempts() {+ assert_eq!(attempt_tag(6), "6+");+ assert_eq!(attempt_tag(100), "6+");+ assert_eq!(attempt_tag(u32::MAX), "6+");+ }+}diff --git a/rust/capture/src/v1/sinks/types.rs b/rust/capture/src/v1/sinks/types.rsindex 17a23086f07f..3a34a5e20401 100644--- a/rust/capture/src/v1/sinks/types.rs+++ b/rust/capture/src/v1/sinks/types.rs@@ -27,6 +27,22 @@ impl Destination {pub fn is_analytics_pipeline(&self) -> bool {matches!(self, Self::AnalyticsMain | Self::AnalyticsHistorical)}++ /// Stable, low-cardinality metric tag. `Custom(_)` collapses to "custom"+ /// so admin-configured topic names never become label values.+ pub fn as_tag(&self) -> &'static str {+ match self {+ Self::AnalyticsMain => "analytics_main",+ Self::AnalyticsHistorical => "analytics_historical",+ Self::Overflow => "overflow",+ Self::Dlq => "dlq",+ Self::Custom(_) => "custom",+ Self::Drop => "drop",+ Self::ExceptionErrorTracking => "exception_error_tracking",+ Self::HeatmapMain => "heatmap_main",+ Self::ClientIngestionWarning => "client_ingestion_warning",+ }+ }}#[cfg(test)]@@ -49,6 +65,47 @@ mod destination_tests {assert!(!Destination::Drop.is_analytics_pipeline());assert!(!Destination::Custom("foo".into()).is_analytics_pipeline());}++ /// Exhaustive: every variant's tag is non-empty, stable, and unique.+ /// Custom(_) collapses to "custom" regardless of the topic name, so two+ /// different Custom values share the same tag (cardinality defense).+ #[test]+ fn as_tag_exhaustive_stable_and_unique() {+ // One representative per variant. If a new variant is added, the+ // as_tag() match becomes non-exhaustive and this file fails to+ // compile, forcing an update here too.+ let expected: &[(Destination, &str)] = &[+ (Destination::AnalyticsMain, "analytics_main"),+ (Destination::AnalyticsHistorical, "analytics_historical"),+ (Destination::Overflow, "overflow"),+ (Destination::Dlq, "dlq"),+ (Destination::Custom("topic_a".into()), "custom"),+ (Destination::Drop, "drop"),+ (+ Destination::ExceptionErrorTracking,+ "exception_error_tracking",+ ),+ (Destination::HeatmapMain, "heatmap_main"),+ (+ Destination::ClientIngestionWarning,+ "client_ingestion_warning",+ ),+ ];++ let mut seen = std::collections::HashSet::new();+ for (dest, tag) in expected {+ assert_eq!(dest.as_tag(), *tag, "tag changed for {dest:?}");+ assert!(!tag.is_empty(), "tag for {dest:?} must be non-empty");+ assert!(seen.insert(*tag), "tag {tag} is not unique across variants");+ }++ // Two different Custom values collapse to the same "custom" tag.+ assert_eq!(Destination::Custom("topic_b".into()).as_tag(), "custom");+ assert_eq!(+ Destination::Custom("topic_a".into()).as_tag(),+ Destination::Custom("topic_b".into()).as_tag()+ );+ }}// ---------------------------------------------------------------------------diff --git a/rust/capture/src/v1/util.rs b/rust/capture/src/v1/util.rsindex 62a8e1d9a6a8..d5fd5b06f248 100644--- a/rust/capture/src/v1/util.rs+++ b/rust/capture/src/v1/util.rs@@ -6,9 +6,26 @@ use bytes::{BufMut, Bytes, BytesMut};use futures::StreamExt;use tokio::io::AsyncReadExt;-use crate::v1::constants::CAPTURE_V1_BODY_READ_TIMEOUT;+use crate::v1::constants::{CAPTURE_V1_BODY_READ_TIMEOUT, CAPTURE_V1_DECOMPRESSION_ERRORS};use crate::v1::Error;+/// Map a validated Content-Encoding value to a static metric label value.+///+/// Mirrors `SUPPORTED_ENCODINGS` (gzip, deflate, br, zstd). `None` means no+/// Content-Encoding header was sent ("identity"). `Context::new` already+/// rejects unsupported encodings, so the "other" fallback is a defensive+/// branch that is unreachable in practice.+pub fn encoding_tag(enc: Option<&str>) -> &'static str {+ match enc {+ None => "identity",+ Some("gzip") => "gzip",+ Some("deflate") => "deflate",+ Some("br") => "br",+ Some("zstd") => "zstd",+ Some(_) => "other",+ }+}+/// Extract body bytes from a streaming Body with a per-chunk timeout.////// If `chunk_timeout` is None, reads the entire body without timeout.@@ -171,6 +188,8 @@ async fn read_decompressed(let to_read = std::cmp::min(remaining, chunk_size);buf.reserve(to_read);let n = reader.read_buf(&mut buf).await.map_err(|e| {+ metrics::counter!(CAPTURE_V1_DECOMPRESSION_ERRORS, "encoding" => encoding_tag(Some(encoding)))+ .increment(1);Error::RequestDecodingError(format!("{encoding} decompression failed: {e:#}"))})?;if n == 0 {@@ -193,6 +212,20 @@ mod tests {const TEST_CHUNK_SIZE_KB: usize = 256;+ #[test]+ fn encoding_tag_covers_supported_encodings_and_identity() {+ // Keep in lockstep with SUPPORTED_ENCODINGS.+ for enc in crate::v1::analytics::constants::SUPPORTED_ENCODINGS {+ assert_eq!(+ encoding_tag(Some(enc)),+ *enc,+ "supported encoding {enc} must map to itself"+ );+ }+ assert_eq!(encoding_tag(None), "identity");+ assert_eq!(encoding_tag(Some("lz4")), "other");+ }+#[tokio::test]async fn extract_body_no_timeout() {let body = Body::from("hello world");