: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
fix(capture): make the warnings emitter gauge reach prometheus (#75176)
Eli Reisman9284dfb21e84
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex d6e123d7b430..0b8d48ecbf91 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2879,6 +2879,7 @@ dependencies = ["lz4","metrics","rdkafka",+ "rstest","serde","serde_json","thiserror 2.0.18",diff --git a/rust/capture/src/router.rs b/rust/capture/src/router.rsindex 0aaf39412f7a..5dcbc45feb35 100644--- a/rust/capture/src/router.rs+++ b/rust/capture/src/router.rs@@ -29,8 +29,8 @@ use limiters::token_dropper::TokenDropper;use crate::config::{AiRouting, CaptureMode};use crate::metrics_middleware::track_metrics;-use crate::prometheus::setup_metrics_recorder;use crate::quota_limiters::CaptureQuotaLimiter;+use metrics_exporter_prometheus::PrometheusHandle;const EVENT_BODY_SIZE: usize = 2 * 1024 * 1024; // 2MBpub const BATCH_BODY_SIZE: usize = 20 * 1024 * 1024; // 20MB, up from the default 2MB used for normal event payloads@@ -164,9 +164,8 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +quota_limiter: CaptureQuotaLimiter,token_dropper: TokenDropper,event_restriction_service: Option<EventRestrictionService>,- metrics: bool,+ recorder_handle: Option<PrometheusHandle>,capture_mode: CaptureMode,- deploy_role: String,concurrency_limit: Option<usize>,event_payload_size_limit: usize,enable_historical_rerouting: bool,@@ -454,11 +453,10 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +.layer(axum::middleware::from_fn(track_metrics)).with_state(state);- // Don't install metrics unless asked to- // Installing a global recorder when capture is used as a library (during tests etc)- // does not work well.- if metrics {- let recorder_handle = setup_metrics_recorder(deploy_role, capture_mode.as_tag());+ // The caller installs the recorder, before anything can emit; here we only+ // expose its output. `None` for tests and library use, which have no+ // recorder of their own.+ if let Some(recorder_handle) = recorder_handle {router.route("/metrics", get(move || ready(recorder_handle.render())))} else {routerdiff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rsindex e66407af8013..e5ccefeadbed 100644--- a/rust/capture/src/setup.rs+++ b/rust/capture/src/setup.rs@@ -17,6 +17,7 @@ use crate::ai_s3::AiBlobStorage;use crate::config::{AiRouting, AiSinkMode, CaptureMode, Config, KafkaConfig};use crate::event_restrictions::{EventRestrictionService, Pipeline, RedisRestrictionsRepository};use crate::global_rate_limiter::GlobalRateLimiter;+use crate::prometheus::setup_metrics_recorder;use crate::quota_limiters::{is_exception_event, is_llm_event, is_survey_event, CaptureQuotaLimiter,};@@ -161,6 +162,15 @@ pub async fn build_components(liveness,} = handles;+ // Must come first: metrics emitted before the global recorder exists are+ // silently dropped, and its `role`/`capture_mode` labels are fixed here.+ let recorder_handle = config.export_prometheus.then(|| {+ setup_metrics_recorder(+ config.otel_service_name.clone(),+ config.capture_mode.as_tag(),+ )+ });+let redis_client = Arc::new(RedisClient::with_config(config.redis_url.clone(),@@ -480,9 +490,8 @@ pub async fn build_components(quota_limiter,token_dropper,event_restriction_service,- config.export_prometheus,+ recorder_handle,config.capture_mode,- config.otel_service_name.clone(),config.concurrency_limit,event_payload_max_bytes,config.enable_historical_rerouting,@@ -750,9 +759,11 @@ async fn create_ingestion_warning_emitter(}// Past this point the operator asked for warnings, so every exit reports- // through the gauge. Leaving it unset above keeps "disabled" distinct from- // "enabled but broken".- let report_disabled = || gauge!(INGESTION_WARNINGS_EMITTER_ENABLED).set(0.0);+ // through the gauge with the reason it bailed. Leaving it unset above keeps+ // "disabled" distinct from "enabled but broken".+ let report_disabled = |reason: &'static str| {+ gauge!(INGESTION_WARNINGS_EMITTER_ENABLED, "reason" => reason).set(0.0)+ };let hosts = config.capture_ingestion_warnings_kafka_hosts.clone();let topic = config.capture_ingestion_warnings_kafka_topic.clone();@@ -763,7 +774,7 @@ async fn create_ingestion_warning_emitter("ingestion warnings enabled but CAPTURE_INGESTION_WARNINGS_KAFKA_HOSTS is unset; \emitter disabled");- report_disabled();+ report_disabled("hosts_unset");return None;}@@ -772,7 +783,7 @@ async fn create_ingestion_warning_emitter("ingestion warnings enabled but CAPTURE_INGESTION_WARNINGS_KAFKA_TOPIC is unset; \emitter disabled");- report_disabled();+ report_disabled("topic_unset");return None;}@@ -780,7 +791,7 @@ async fn create_ingestion_warning_emitter(warn!("ingestion warnings enabled but no lifecycle handle was registered; emitter disabled");- report_disabled();+ report_disabled("no_handle");return None;};@@ -801,7 +812,7 @@ async fn create_ingestion_warning_emitter(tracing::error!("failed to create ingestion warnings producer, emitter disabled: {e:#}");- report_disabled();+ report_disabled("producer_create_failed");return None;}};@@ -830,7 +841,7 @@ async fn create_ingestion_warning_emitter(}});- gauge!(INGESTION_WARNINGS_EMITTER_ENABLED).set(1.0);+ gauge!(INGESTION_WARNINGS_EMITTER_ENABLED, "reason" => "ok").set(1.0);info!(topic = topic.as_str(), "ingestion warnings emitter enabled");Some(emitter)}@@ -907,8 +918,66 @@ fn create_event_restriction_service(#[cfg(test)]mod tests {use super::*;+ use metrics_util::debugging::{DebugValue, DebuggingRecorder, Snapshotter};+ use rstest::rstest;use std::collections::HashMap;+ fn warnings_config(enabled: bool, hosts: &str, topic: &str) -> Config {+ let cfg_env: HashMap<String, String> = [+ ("REDIS_URL", "redis://localhost:6379/"),+ ("CAPTURE_MODE", "events"),+ ("KAFKA_HOSTS", "v0-broker:9092"),+ ("KAFKA_TOPIC", "events_plugin_ingestion"),+ (+ "CAPTURE_INGESTION_WARNINGS_ENABLED",+ if enabled { "true" } else { "false" },+ ),+ ("CAPTURE_INGESTION_WARNINGS_KAFKA_HOSTS", hosts),+ ("CAPTURE_INGESTION_WARNINGS_KAFKA_TOPIC", topic),+ ]+ .into_iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect();+ envconfig::Envconfig::init_from_hashmap(&cfg_env).expect("test config")+ }++ /// The emitter gauge as `(reason, value)`, or `None` if never emitted.+ fn emitter_enabled_gauge(snapshotter: &Snapshotter) -> Option<(String, f64)> {+ snapshotter+ .snapshot()+ .into_vec()+ .into_iter()+ .find(|(ckey, _, _, _)| ckey.key().name() == INGESTION_WARNINGS_EMITTER_ENABLED)+ .map(|(ckey, _, _, value)| {+ let reason = ckey+ .key()+ .labels()+ .find(|label| label.key() == "reason")+ .map(|label| label.value().to_string())+ .expect("every emission must carry a reason label");+ match value {+ DebugValue::Gauge(v) => (reason, v.into_inner()),+ other => panic!("expected a gauge, got {other:?}"),+ }+ })+ }++ /// Run `f` with metrics captured locally. The recorder is thread-scoped, so+ /// callers drive futures on this thread via `current_thread_runtime`.+ fn capture_metrics<T>(f: impl FnOnce() -> T) -> (T, Snapshotter) {+ let recorder = DebuggingRecorder::new();+ let snapshotter = recorder.snapshotter();+ let out = metrics::with_local_recorder(&recorder, f);+ (out, snapshotter)+ }++ fn current_thread_runtime() -> tokio::runtime::Runtime {+ tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .expect("runtime")+ }+#[test]fn create_v1_sink_router_fails_on_invalid_config() {let cfg_env: HashMap<String, String> = [@@ -1112,4 +1181,66 @@ mod tests {assert!(super::parse_token_allowlist(" , , ").is_empty());}++ /// Absent gauge means warnings are off on purpose; `0` means an operator+ /// asked for them and we could not build them. `reason` says which.+ #[rstest]+ #[case::off_on_purpose(false, "", "", None)]+ #[case::hosts_unset(true, "", "", Some("hosts_unset"))]+ #[case::topic_unset(true, "broker:9092", "", Some("topic_unset"))]+ #[case::no_handle(true, "broker:9092", "client_ingestion_warning", Some("no_handle"))]+ fn emitter_gauge_reports_why_warnings_are_off(+ #[case] enabled: bool,+ #[case] hosts: &str,+ #[case] topic: &str,+ #[case] expected_reason: Option<&str>,+ ) {+ let config = warnings_config(enabled, hosts, topic);+ let runtime = current_thread_runtime();++ let (emitter, snapshotter) =+ capture_metrics(|| runtime.block_on(create_ingestion_warning_emitter(&config, None)));++ assert!(emitter.is_none(), "no case here can build an emitter");+ match expected_reason {+ Some(reason) => assert_eq!(+ emitter_enabled_gauge(&snapshotter),+ Some((reason.to_string(), 0.0)),+ ),+ None => assert!(+ emitter_enabled_gauge(&snapshotter).is_none(),+ "disabled must stay unset, or it looks misconfigured",+ ),+ }+ }++ #[test]+ fn healthy_emitter_reports_ok() {+ // TEST-NET-1 host: the no-ping constructor never dials it, so the real+ // success path runs offline.+ let config = warnings_config(true, "192.0.2.1:9092", "client_ingestion_warning");+ let mut manager = lifecycle::Manager::builder("test")+ .with_trap_signals(false)+ .with_prestop_check(false)+ .build();+ // Mirrors the registration in `register_components`.+ let handle = manager.register(+ "ingestion-warnings",+ lifecycle::ComponentOptions::new()+ .with_liveness_deadline(Duration::from_secs(30))+ .is_advisory(true),+ );+ let runtime = current_thread_runtime();++ let (emitter, snapshotter) = capture_metrics(|| {+ runtime.block_on(create_ingestion_warning_emitter(&config, Some(handle)))+ });++ assert!(emitter.is_some(), "emitter must be built");+ assert_eq!(+ emitter_enabled_gauge(&snapshotter),+ Some(("ok".to_string(), 1.0)),+ "healthy and failed emissions must share a label set",+ );+ }}diff --git a/rust/capture/src/v1/sinks/DESIGN.md b/rust/capture/src/v1/sinks/DESIGN.mdindex a2e905a5e37d..01debb91a451 100644--- a/rust/capture/src/v1/sinks/DESIGN.md+++ b/rust/capture/src/v1/sinks/DESIGN.md@@ -1057,7 +1057,9 @@ and the client-controlled `attempt` label is capped at `6+`, soAll error-related metrics use stable, low-cardinality tags derived from:- `error_code_tag()` — maps `RDKafkaErrorCode` variants to snake_case strings- (e.g. `queue_full`, `message_size_too_large`, `all_brokers_down`)+ (e.g. `queue_full`, `message_size_too_large`, `all_brokers_down`). Defined in+ `common_kafka::error` and re-exported from `kafka/types.rs`, so producers+ outside the sink share the same vocabulary- `KafkaSinkError::as_tag()` — sink-level tags(e.g. `sink_unavailable`, `timeout`, `task_panicked`)- `ProduceError::as_tag()` — producer-level tagsdiff --git a/rust/capture/src/v1/sinks/kafka/types.rs b/rust/capture/src/v1/sinks/kafka/types.rsindex cbc2f30a1311..b77a32d8118b 100644--- a/rust/capture/src/v1/sinks/kafka/types.rs+++ b/rust/capture/src/v1/sinks/kafka/types.rs@@ -1,7 +1,6 @@use std::borrow::Cow;use chrono::{DateTime, Utc};-use rdkafka::error::RDKafkaErrorCode;use uuid::Uuid;use super::producer::ProduceError;@@ -11,38 +10,10 @@ use crate::v1::sinks::types::{Outcome, SinkResult};// error_code_tag// ----------------------------------------------------------------------------/// Stable, low-cardinality snake_case tag for an RDKafkaErrorCode.-/// Usable anywhere -- producer, sink, handler, logging.-pub fn error_code_tag(code: RDKafkaErrorCode) -> &'static str {- match code {- RDKafkaErrorCode::QueueFull => "queue_full",- RDKafkaErrorCode::MessageSizeTooLarge => "message_size_too_large",- RDKafkaErrorCode::MessageTimedOut => "message_timed_out",- RDKafkaErrorCode::UnknownTopicOrPartition => "unknown_topic_or_partition",- RDKafkaErrorCode::TopicAuthorizationFailed => "topic_authorization_failed",- RDKafkaErrorCode::ClusterAuthorizationFailed => "cluster_authorization_failed",- RDKafkaErrorCode::InvalidMessage => "invalid_message",- RDKafkaErrorCode::InvalidMessageSize => "invalid_message_size",- RDKafkaErrorCode::NotLeaderForPartition => "not_leader_for_partition",- RDKafkaErrorCode::RequestTimedOut => "request_timed_out",- // Broker/idempotent-producer codes from delivery reports- RDKafkaErrorCode::NotEnoughReplicas => "not_enough_replicas",- RDKafkaErrorCode::NotEnoughReplicasAfterAppend => "not_enough_replicas_after_append",- RDKafkaErrorCode::OperationNotAttempted => "operation_not_attempted",- RDKafkaErrorCode::OutOfOrderSequenceNumber => "out_of_order_sequence_number",- RDKafkaErrorCode::DuplicateSequenceNumber => "duplicate_sequence_number",- RDKafkaErrorCode::NetworkException => "network_exception",- RDKafkaErrorCode::CoordinatorLoadInProgress => "coordinator_load_in_progress",- RDKafkaErrorCode::CoordinatorNotAvailable => "coordinator_not_available",- // Transport/infra codes surfaced by ClientContext::error() callback- RDKafkaErrorCode::BrokerTransportFailure => "broker_transport_failure",- RDKafkaErrorCode::AllBrokersDown => "all_brokers_down",- RDKafkaErrorCode::Resolve => "resolve",- RDKafkaErrorCode::Authentication => "authentication",- RDKafkaErrorCode::SaslAuthenticationFailed => "sasl_authentication_failed",- _ => "rdkafka_other",- }-}+/// Lives in `common_kafka::error` so producers outside capture share one error+/// label vocabulary. Re-exported here because this is the path the sink's+/// callers and DESIGN.md know it by.+pub use common_kafka::error::error_code_tag;// ---------------------------------------------------------------------------// KafkaSinkError@@ -166,65 +137,3 @@ impl SinkResult for KafkaResult {.and_then(|t| t.signed_duration_since(self.enqueued_at).to_std().ok())}}--#[cfg(test)]-mod tests {- use super::*;-- #[rstest::rstest]- #[case(RDKafkaErrorCode::QueueFull, "queue_full")]- #[case(RDKafkaErrorCode::MessageSizeTooLarge, "message_size_too_large")]- #[case(RDKafkaErrorCode::MessageTimedOut, "message_timed_out")]- #[case(- RDKafkaErrorCode::UnknownTopicOrPartition,- "unknown_topic_or_partition"- )]- #[case(- RDKafkaErrorCode::TopicAuthorizationFailed,- "topic_authorization_failed"- )]- #[case(- RDKafkaErrorCode::ClusterAuthorizationFailed,- "cluster_authorization_failed"- )]- #[case(RDKafkaErrorCode::InvalidMessage, "invalid_message")]- #[case(RDKafkaErrorCode::InvalidMessageSize, "invalid_message_size")]- #[case(RDKafkaErrorCode::NotLeaderForPartition, "not_leader_for_partition")]- #[case(RDKafkaErrorCode::RequestTimedOut, "request_timed_out")]- #[case(RDKafkaErrorCode::NotEnoughReplicas, "not_enough_replicas")]- #[case(- RDKafkaErrorCode::NotEnoughReplicasAfterAppend,- "not_enough_replicas_after_append"- )]- #[case(RDKafkaErrorCode::OperationNotAttempted, "operation_not_attempted")]- #[case(- RDKafkaErrorCode::OutOfOrderSequenceNumber,- "out_of_order_sequence_number"- )]- #[case(RDKafkaErrorCode::DuplicateSequenceNumber, "duplicate_sequence_number")]- #[case(RDKafkaErrorCode::NetworkException, "network_exception")]- #[case(- RDKafkaErrorCode::CoordinatorLoadInProgress,- "coordinator_load_in_progress"- )]- #[case(RDKafkaErrorCode::CoordinatorNotAvailable, "coordinator_not_available")]- #[case(RDKafkaErrorCode::BrokerTransportFailure, "broker_transport_failure")]- #[case(RDKafkaErrorCode::AllBrokersDown, "all_brokers_down")]- #[case(RDKafkaErrorCode::Resolve, "resolve")]- #[case(RDKafkaErrorCode::Authentication, "authentication")]- #[case(- RDKafkaErrorCode::SaslAuthenticationFailed,- "sasl_authentication_failed"- )]- fn error_code_tag_named_variants(#[case] code: RDKafkaErrorCode, #[case] expected: &str) {- assert_eq!(error_code_tag(code), expected);- }-- #[rstest::rstest]- #[case(RDKafkaErrorCode::Unknown)]- #[case(RDKafkaErrorCode::OffsetOutOfRange)]- #[case(RDKafkaErrorCode::GroupAuthorizationFailed)]- fn error_code_tag_unlisted_codes_fall_through(#[case] code: RDKafkaErrorCode) {- assert_eq!(error_code_tag(code), "rdkafka_other");- }-}diff --git a/rust/capture/tests/common/integration_utils.rs b/rust/capture/tests/common/integration_utils.rsindex abb6d91aa952..a3e44ca1fdf2 100644--- a/rust/capture/tests/common/integration_utils.rs+++ b/rust/capture/tests/common/integration_utils.rs@@ -1101,9 +1101,8 @@ fn build_router_for_mode_at(mode: CaptureMode, fixed_time: &str) -> (Router, Memquota_limiter,TokenDropper::default(),None, // event_restriction_service- false,+ None, // recorder_handlemode,- String::from("capture"),None,25 * 1024 * 1024,enable_historical_rerouting,diff --git a/rust/capture/tests/integration_ai_endpoint.rs b/rust/capture/tests/integration_ai_endpoint.rsindex e97a912499ea..4fe2196299e0 100644--- a/rust/capture/tests/integration_ai_endpoint.rs+++ b/rust/capture/tests/integration_ai_endpoint.rs@@ -177,9 +177,8 @@ fn setup_ai_test_router() -> Router {quota_limiter,TokenDropper::default(),None, // event_restriction_service- false,+ None, // recorder_handleCaptureMode::Events,- String::from("capture-ai"),None,25 * 1024 * 1024,false,@@ -1644,9 +1643,8 @@ fn setup_ai_test_router_with_capturing_sink() -> (Router, CapturingSink) {quota_limiter,TokenDropper::default(),None, // event_restriction_service- false,+ None, // recorder_handleCaptureMode::Events,- String::from("capture-ai"),None,25 * 1024 * 1024,false,@@ -2562,10 +2560,9 @@ fn setup_ai_test_router_with_token_dropper(token_dropper: TokenDropper) -> (RoutNone,quota_limiter,token_dropper,- None, // event_restriction_service- false, // metrics+ None, // event_restriction_service+ None, // recorder_handleCaptureMode::Events,- String::from("capture-ai"),None, // concurrency_limit25 * 1024 * 1024, // event_size_limitfalse, // enable_historical_rerouting@@ -2777,9 +2774,8 @@ fn setup_ai_test_router_with_llm_quota_limited(token: &str) -> (Router, Capturinquota_limiter,TokenDropper::default(),None, // event_restriction_service- false,+ None, // recorder_handleCaptureMode::Events,- String::from("capture-ai"),None,25 * 1024 * 1024,false,@@ -2936,9 +2932,8 @@ fn setup_ai_test_router_with_overflow_limiter(quota_limiter,TokenDropper::default(),None, // event_restriction_service- false,+ None, // recorder_handleCaptureMode::Events,- String::from("capture-ai"),None,25 * 1024 * 1024,false,@@ -3079,9 +3074,8 @@ fn ai_router(quota_limiter,TokenDropper::default(),None,- false,+ None, // recorder_handleCaptureMode::Events,- String::from("capture-ai"),None,25 * 1024 * 1024,false,diff --git a/rust/capture/tests/integration_ai_restrictions.rs b/rust/capture/tests/integration_ai_restrictions.rsindex 0cb576fde5e6..d009b678bd1f 100644--- a/rust/capture/tests/integration_ai_restrictions.rs+++ b/rust/capture/tests/integration_ai_restrictions.rs@@ -175,9 +175,8 @@ async fn setup_ai_router_with_restriction(quota_limiter,TokenDropper::default(),Some(service),- false,+ None, // recorder_handleCaptureMode::Events,- String::from("capture-ai"),None,25 * 1024 * 1024,false,@@ -498,9 +497,8 @@ async fn setup_ai_router_with_redirect_to_topic(quota_limiter,TokenDropper::default(),Some(service),- false,+ None, // recorder_handleCaptureMode::Events,- String::from("capture-ai"),None,25 * 1024 * 1024,false,@@ -580,9 +578,8 @@ async fn setup_ai_router_with_force_overflow_and_limiter(quota_limiter,TokenDropper::default(),Some(service),- false,+ None, // recorder_handleCaptureMode::Events,- String::from("capture-ai"),None,25 * 1024 * 1024,false,diff --git a/rust/capture/tests/integration_analytics_ai_routing.rs b/rust/capture/tests/integration_analytics_ai_routing.rsindex 6d0f3fb027bf..ff85b8756fc4 100644--- a/rust/capture/tests/integration_analytics_ai_routing.rs+++ b/rust/capture/tests/integration_analytics_ai_routing.rs@@ -123,9 +123,8 @@ fn setup_router_for_mode(quota_limiter,TokenDropper::default(),None, // event_restriction_service- false,+ None, // recorder_handlecapture_mode,- String::from("capture-analytics"),None,25 * 1024 * 1024,false,diff --git a/rust/capture/tests/integration_analytics_restrictions.rs b/rust/capture/tests/integration_analytics_restrictions.rsindex 255de067afe9..74af84e5372b 100644--- a/rust/capture/tests/integration_analytics_restrictions.rs+++ b/rust/capture/tests/integration_analytics_restrictions.rs@@ -115,9 +115,8 @@ async fn setup_analytics_router_with_restriction(quota_limiter,TokenDropper::default(),Some(service),- false,+ None, // recorder_handleCaptureMode::Events,- String::from("capture-analytics"),None,25 * 1024 * 1024,false,@@ -549,9 +548,8 @@ async fn setup_analytics_router_with_redirect_to_topic(quota_limiter,TokenDropper::default(),Some(service),- false,+ None, // recorder_handleCaptureMode::Events,- String::from("capture-analytics"),None,25 * 1024 * 1024,false,diff --git a/rust/capture/tests/integration_otel_endpoint.rs b/rust/capture/tests/integration_otel_endpoint.rsindex b8231ca00098..c70f0c9f2428 100644--- a/rust/capture/tests/integration_otel_endpoint.rs+++ b/rust/capture/tests/integration_otel_endpoint.rs@@ -164,9 +164,8 @@ fn make_test_client_with_options(sink: &CapturingSink, options: TestClientOptionquota_limiter,TokenDropper::default(),options.event_restriction_service,- false, // metrics+ None, // recorder_handleCaptureMode::Events,- String::from("capture-otel-test"),None, // concurrency_limit25 * 1024 * 1024, // event_payload_size_limitfalse, // enable_historical_reroutingdiff --git a/rust/capture/tests/integration_replay_restrictions.rs b/rust/capture/tests/integration_replay_restrictions.rsindex d32755e19ce5..22add8397adf 100644--- a/rust/capture/tests/integration_replay_restrictions.rs+++ b/rust/capture/tests/integration_replay_restrictions.rs@@ -111,9 +111,8 @@ async fn setup_recordings_router_with_restriction(quota_limiter,TokenDropper::default(),Some(service),- false,+ None, // recorder_handleCaptureMode::Recordings,- String::from("capture-recordings"),None,25 * 1024 * 1024,false,@@ -485,9 +484,8 @@ async fn setup_recordings_router_with_redirect_to_topic(quota_limiter,TokenDropper::default(),Some(service),- false,+ None, // recorder_handleCaptureMode::Recordings,- String::from("capture-recordings"),None,25 * 1024 * 1024,false,diff --git a/rust/capture/tests/metrics_startup.rs b/rust/capture/tests/metrics_startup.rsnew file mode 100644index 000000000000..25089289a5a6--- /dev/null+++ b/rust/capture/tests/metrics_startup.rs@@ -0,0 +1,53 @@+//! Metrics emitted during `build_components` must reach `/metrics`. Whether+//! they do depends on the global recorder being installed first, which only the+//! real startup path exercises: a unit test's local recorder always exists.+//!+//! One test per binary, since the recorder installs once per process.++use std::time::Duration;++#[path = "common/utils.rs"]+mod test_utils;+use test_utils::{setup_tracing, ServerHandle, DEFAULT_CONFIG};++#[tokio::test]+async fn startup_gauge_reaches_the_scrape_endpoint() {+ setup_tracing();++ let mut config = DEFAULT_CONFIG.clone();+ config.export_prometheus = true;+ // Warnings enabled but no hosts, so the emitter reports `0` during startup.+ config.capture_ingestion_warnings_enabled = true;+ config.capture_ingestion_warnings_kafka_hosts = String::new();++ let server = ServerHandle::for_config(config).await;++ let body = reqwest::Client::builder()+ .timeout(Duration::from_secs(5))+ .build()+ .expect("http client")+ .get(format!("http://{}/metrics", server.addr))+ .send()+ .await+ .expect("scrape /metrics")+ .text()+ .await+ .expect("read scrape body");++ let line = body+ .lines()+ .find(|line| line.starts_with("ingestion_warnings_emitter_enabled{"))+ .unwrap_or_else(|| panic!("gauge missing, startup metrics are being dropped"));++ assert!(+ line.contains(r#"reason="hosts_unset""#),+ "gauge must name the misconfiguration: {line}"+ );+ assert!(line.ends_with(" 0"), "emitter is down, expected 0: {line}");+ // The recorder's global labels only land if it was installed before the+ // emission, so checking them also pins the ordering.+ assert!(+ line.contains(r#"capture_mode="events""#) && line.contains(r#"role="capture-testing""#),+ "gauge must carry the recorder's global labels: {line}"+ );+}diff --git a/rust/capture/tests/quota_limiters.rs b/rust/capture/tests/quota_limiters.rsindex 9519d0b0e6d4..a67a26e41740 100644--- a/rust/capture/tests/quota_limiters.rs+++ b/rust/capture/tests/quota_limiters.rs@@ -132,10 +132,9 @@ async fn setup_router_with_limits(None,quota_limiter,TokenDropper::default(),- None, // event_restriction_service- false, // metrics+ None, // event_restriction_service+ None, // recorder_handleCaptureMode::Events,- String::from("capture"),None, // concurrency_limit1024 * 1024, // event_payload_size_limitfalse, // enable_historical_rerouting@@ -1189,9 +1188,8 @@ async fn test_survey_quota_cross_batch_first_submission_allowed() {quota_limiter,TokenDropper::default(),None, // event_restriction_service- false,+ None, // recorder_handleCaptureMode::Events,- String::from("capture"),None,1024 * 1024,false,@@ -1283,9 +1281,8 @@ async fn test_survey_quota_cross_batch_duplicate_submission_dropped() {quota_limiter,TokenDropper::default(),None, // event_restriction_service- false,+ None, // recorder_handleCaptureMode::Events,- String::from("capture"),None,1024 * 1024,false,@@ -1381,9 +1378,8 @@ async fn test_survey_quota_cross_batch_redis_error_fail_open() {quota_limiter,TokenDropper::default(),None, // event_restriction_service- false,+ None, // recorder_handleCaptureMode::Events,- String::from("capture"),None,1024 * 1024,false,@@ -1816,9 +1812,8 @@ async fn test_ai_quota_cross_batch_redis_error_fail_open() {quota_limiter,TokenDropper::default(),None, // event_restriction_service- false,+ None, // recorder_handleCaptureMode::Events,- String::from("capture"),None,1024 * 1024,false,diff --git a/rust/common/ingestion_warnings/src/lib.rs b/rust/common/ingestion_warnings/src/lib.rsindex 62fa6c5beca4..72b652ccb12e 100644--- a/rust/common/ingestion_warnings/src/lib.rs+++ b/rust/common/ingestion_warnings/src/lib.rs@@ -43,6 +43,7 @@ pub mod throttle;use std::time::Duration;+use common_kafka::error::error_code_tag;use common_kafka::kafka_producer::ThreadedKafkaContext;use metrics::{counter, gauge};use rdkafka::error::KafkaError;@@ -63,8 +64,23 @@ pub use throttle::{ThrottleDecision, WarningThrottle};/// cardinality_capped | queue_full | serialize_error | enqueue_error`./// Delivery-time outcomes (reported asynchronously for each `emitted`/// message): `delivered | delivery_failed`.+///+/// The Node.js `clientwarnings` consumer exports this same name for the rows it+/// writes, at a later stage and far higher volume. Only this side carries+/// `source`, so queries must scope by it (or by namespace) to avoid summing+/// both stages.pub const INGESTION_WARNINGS_TOTAL: &str = "ingestion_warnings_total";+/// Counter of delivery failures by cause: labels `source`, `path`, and `error`+/// (a [`common_kafka::error::error_code_tag`] tag, shared with capture's sink+/// metrics so the two can be queried together). Separates a bad topic from an+/// unreachable broker, which `delivery_failed` alone cannot.+///+/// Its own metric because an `error` label on only one outcome of+/// [`INGESTION_WARNINGS_TOTAL`] would break aggregations over the rest.+pub const INGESTION_WARNINGS_DELIVERY_ERRORS_TOTAL: &str =+ "ingestion_warnings_delivery_errors_total";+/// Gauge of `(token, type)` keys currently tracked by the throttle, updated/// on each sweep. The early-warning signal for the cardinality cap.pub const INGESTION_WARNINGS_THROTTLE_KEYS: &str = "ingestion_warnings_throttle_keys";@@ -75,6 +91,14 @@ pub const INGESTION_WARNINGS_THROTTLE_KEYS: &str = "ingestion_warnings_throttle_/// indistinguishable from an intentionally quiet one. Absence means "off",/// `0` means "broken".///+/// Every emission carries a `reason` label naming the cause: `ok` when healthy,+/// otherwise the misconfiguration (capture uses `hosts_unset`, `topic_unset`,+/// `no_handle`, `producer_create_failed`). Labelling both states keeps their+/// label sets identical, so `min(...) == 0` works without aggregating it away.+///+/// Emit only after the process installs its global metrics recorder; earlier+/// `gauge!` calls are silently dropped.+////// `1` means the emitter was built, not that its cluster is reachable:/// construction deliberately skips the broker ping, so a producer pointed at a/// dead cluster still reports `1` and recovers on its own once the cluster@@ -317,17 +341,38 @@ pub struct WarningDelivery {pub source: WarningSource,}+/// Metric label for a delivery failure: capture's shared [`error_code_tag`]+/// vocabulary, or `unknown` when the error carries no rdkafka code (a cancel or+/// purge during flush, for one). `&'static str`, so the poll thread never+/// allocates to label a failure.+fn delivery_error_tag(err: &KafkaError) -> &'static str {+ err.rdkafka_error_code()+ .map(error_code_tag)+ .unwrap_or("unknown")+}+/// Delivery-report callback for the warnings `ThreadedProducer`. Runs on/// rdkafka's poll thread for every produced message and ticks the/// `delivered`/`delivery_failed` outcome — the async half of the `emitted`/// counter, which alone only proves the message entered the local queue./// Without this, a broken topic or broker at rollout looks healthy while-/// nothing lands. Metric-only (no per-message log) since a broken topic at-/// rollout would otherwise flood logs at post-throttle volume.+/// nothing lands. Failures also tick+/// [`INGESTION_WARNINGS_DELIVERY_ERRORS_TOTAL`] with the error code.+/// Metric-only (no per-message log) since a broken topic at rollout would+/// otherwise flood logs at post-throttle volume.pub fn observe_delivery(result: &DeliveryResult, delivery: WarningDelivery) {let outcome = match result {Ok(_) => "delivered",- Err(_) => "delivery_failed",+ Err((err, _message)) => {+ counter!(+ INGESTION_WARNINGS_DELIVERY_ERRORS_TOTAL,+ "source" => delivery.source.service,+ "path" => delivery.source.path,+ "error" => delivery_error_tag(err),+ )+ .increment(1);+ "delivery_failed"+ }};counter!(INGESTION_WARNINGS_TOTAL,@@ -344,6 +389,7 @@ mod tests {use common_kafka::config::KafkaConfig;use common_kafka::kafka_producer::create_threaded_kafka_producer_no_ping;use common_liveness::SyncLivenessReporter;+ use rstest::rstest;use super::*;@@ -377,6 +423,22 @@ mod tests {.expect("client config is valid, so creation cannot fail without a broker round-trip")}+ // Errors reaching a delivery report don't all carry an rdkafka code. Without+ // the fallback they'd land as an empty label, merging every one of them into+ // a single anonymous series.+ #[rstest]+ #[case::has_code(+ KafkaError::MessageProduction(RDKafkaErrorCode::MessageTimedOut),+ "message_timed_out"+ )]+ #[case::carries_no_code(KafkaError::Canceled, "unknown")]+ fn delivery_error_tag_names_the_code_or_falls_back(+ #[case] err: KafkaError,+ #[case] expected: &str,+ ) {+ assert_eq!(delivery_error_tag(&err), expected);+ }+#[test]fn kafka_emitter_throttles_repeats_and_never_blocks() {// Unreachable broker (TEST-NET-1): emit must return instantly whetherdiff --git a/rust/common/kafka/Cargo.toml b/rust/common/kafka/Cargo.tomlindex 85c5e738b4a4..6d72b0bc7210 100644--- a/rust/common/kafka/Cargo.toml+++ b/rust/common/kafka/Cargo.toml@@ -21,3 +21,6 @@ tracing = { workspace = true }uuid = { workspace = true }thiserror = { workspace = true }tokio = { workspace = true }++[dev-dependencies]+rstest = "0.26"diff --git a/rust/common/kafka/src/error.rs b/rust/common/kafka/src/error.rsnew file mode 100644index 000000000000..59c759e0476f--- /dev/null+++ b/rust/common/kafka/src/error.rs@@ -0,0 +1,102 @@+use rdkafka::error::RDKafkaErrorCode;++/// Stable, low-cardinality snake_case tag for an RDKafkaErrorCode.+/// Usable anywhere -- producer, sink, handler, logging.+///+/// Deliberately a curated set rather than the full ~170-variant enum: every+/// producer that tags errors shares this vocabulary, so codes stay comparable+/// across metrics and unlisted ones collapse to `rdkafka_other` instead of+/// growing label cardinality unbounded. Add a code here when it starts+/// mattering and every caller gains it at once.+pub fn error_code_tag(code: RDKafkaErrorCode) -> &'static str {+ match code {+ RDKafkaErrorCode::QueueFull => "queue_full",+ RDKafkaErrorCode::MessageSizeTooLarge => "message_size_too_large",+ RDKafkaErrorCode::MessageTimedOut => "message_timed_out",+ RDKafkaErrorCode::UnknownTopicOrPartition => "unknown_topic_or_partition",+ RDKafkaErrorCode::TopicAuthorizationFailed => "topic_authorization_failed",+ RDKafkaErrorCode::ClusterAuthorizationFailed => "cluster_authorization_failed",+ RDKafkaErrorCode::InvalidMessage => "invalid_message",+ RDKafkaErrorCode::InvalidMessageSize => "invalid_message_size",+ RDKafkaErrorCode::NotLeaderForPartition => "not_leader_for_partition",+ RDKafkaErrorCode::RequestTimedOut => "request_timed_out",+ // Broker/idempotent-producer codes from delivery reports+ RDKafkaErrorCode::NotEnoughReplicas => "not_enough_replicas",+ RDKafkaErrorCode::NotEnoughReplicasAfterAppend => "not_enough_replicas_after_append",+ RDKafkaErrorCode::OperationNotAttempted => "operation_not_attempted",+ RDKafkaErrorCode::OutOfOrderSequenceNumber => "out_of_order_sequence_number",+ RDKafkaErrorCode::DuplicateSequenceNumber => "duplicate_sequence_number",+ RDKafkaErrorCode::NetworkException => "network_exception",+ RDKafkaErrorCode::CoordinatorLoadInProgress => "coordinator_load_in_progress",+ RDKafkaErrorCode::CoordinatorNotAvailable => "coordinator_not_available",+ // Transport/infra codes surfaced by ClientContext::error() callback+ RDKafkaErrorCode::BrokerTransportFailure => "broker_transport_failure",+ RDKafkaErrorCode::AllBrokersDown => "all_brokers_down",+ RDKafkaErrorCode::Resolve => "resolve",+ RDKafkaErrorCode::Authentication => "authentication",+ RDKafkaErrorCode::SaslAuthenticationFailed => "sasl_authentication_failed",+ _ => "rdkafka_other",+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[rstest::rstest]+ #[case(RDKafkaErrorCode::QueueFull, "queue_full")]+ #[case(RDKafkaErrorCode::MessageSizeTooLarge, "message_size_too_large")]+ #[case(RDKafkaErrorCode::MessageTimedOut, "message_timed_out")]+ #[case(+ RDKafkaErrorCode::UnknownTopicOrPartition,+ "unknown_topic_or_partition"+ )]+ #[case(+ RDKafkaErrorCode::TopicAuthorizationFailed,+ "topic_authorization_failed"+ )]+ #[case(+ RDKafkaErrorCode::ClusterAuthorizationFailed,+ "cluster_authorization_failed"+ )]+ #[case(RDKafkaErrorCode::InvalidMessage, "invalid_message")]+ #[case(RDKafkaErrorCode::InvalidMessageSize, "invalid_message_size")]+ #[case(RDKafkaErrorCode::NotLeaderForPartition, "not_leader_for_partition")]+ #[case(RDKafkaErrorCode::RequestTimedOut, "request_timed_out")]+ #[case(RDKafkaErrorCode::NotEnoughReplicas, "not_enough_replicas")]+ #[case(+ RDKafkaErrorCode::NotEnoughReplicasAfterAppend,+ "not_enough_replicas_after_append"+ )]+ #[case(RDKafkaErrorCode::OperationNotAttempted, "operation_not_attempted")]+ #[case(+ RDKafkaErrorCode::OutOfOrderSequenceNumber,+ "out_of_order_sequence_number"+ )]+ #[case(RDKafkaErrorCode::DuplicateSequenceNumber, "duplicate_sequence_number")]+ #[case(RDKafkaErrorCode::NetworkException, "network_exception")]+ #[case(+ RDKafkaErrorCode::CoordinatorLoadInProgress,+ "coordinator_load_in_progress"+ )]+ #[case(RDKafkaErrorCode::CoordinatorNotAvailable, "coordinator_not_available")]+ #[case(RDKafkaErrorCode::BrokerTransportFailure, "broker_transport_failure")]+ #[case(RDKafkaErrorCode::AllBrokersDown, "all_brokers_down")]+ #[case(RDKafkaErrorCode::Resolve, "resolve")]+ #[case(RDKafkaErrorCode::Authentication, "authentication")]+ #[case(+ RDKafkaErrorCode::SaslAuthenticationFailed,+ "sasl_authentication_failed"+ )]+ fn error_code_tag_named_variants(#[case] code: RDKafkaErrorCode, #[case] expected: &str) {+ assert_eq!(error_code_tag(code), expected);+ }++ #[rstest::rstest]+ #[case(RDKafkaErrorCode::Unknown)]+ #[case(RDKafkaErrorCode::OffsetOutOfRange)]+ #[case(RDKafkaErrorCode::GroupAuthorizationFailed)]+ fn error_code_tag_unlisted_codes_fall_through(#[case] code: RDKafkaErrorCode) {+ assert_eq!(error_code_tag(code), "rdkafka_other");+ }+}diff --git a/rust/common/kafka/src/lib.rs b/rust/common/kafka/src/lib.rsindex cc652ae1b944..0d21d783e41b 100644--- a/rust/common/kafka/src/lib.rs+++ b/rust/common/kafka/src/lib.rs@@ -1,4 +1,5 @@pub mod config;+pub mod error;pub mod kafka_consumer;pub mod kafka_messages;pub mod kafka_producer;