: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(lifecycle): advisory component death must not trigger global shutdown (#75038)
Eli Reisman78ceb2b34e7c
diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rsindex d267a4515532..245739a40ee0 100644--- a/rust/capture/src/setup.rs+++ b/rust/capture/src/setup.rs@@ -8,7 +8,7 @@ use common_ingestion_warnings::{observe_delivery, KafkaWarningEmitter, WarningEmitter, INGESTION_WARNINGS_EMITTER_ENABLED,};use common_kafka::config::KafkaConfig as WarningsKafkaConfig;-use common_kafka::kafka_producer::create_threaded_kafka_producer;+use common_kafka::kafka_producer::create_threaded_kafka_producer_no_ping;use common_redis::RedisClient;use metrics::gauge;use tracing::{info, warn};@@ -725,7 +725,7 @@ fn build_warnings_kafka_config(/// any misconfiguration or producer-creation failure logs and returns `None`/// (capture runs without warnings) instead of failing startup. The producer/// is a `common_kafka` `ThreadedProducer`, built via-/// `common_kafka::kafka_producer::create_threaded_kafka_producer` from a+/// `common_kafka::kafka_producer::create_threaded_kafka_producer_no_ping` from a/// dedicated, warnings-only `common_kafka::config::KafkaConfig` (fire-and-forget/// acks/retries, a small queue) with `observe_delivery` as its delivery/// callback — by default it shares only the destination cluster (hosts/TLS) and@@ -735,10 +735,12 @@ fn build_warnings_kafka_config(/// task heartbeats the advisory lifecycle handle, sweeps the throttle's per-key/// state, and flushes the producer once at shutdown.///-/// Fail-open note: unlike the previous bespoke producer (which never pinged-/// brokers at startup), `create_threaded_kafka_producer` does a one-time-/// metadata fetch. If brokers are unreachable at boot, the emitter stays-/// disabled for the pod's life rather than retrying.+/// Uses the no-ping constructor so an unreachable warnings cluster costs+/// capture nothing at boot: no 15s metadata fetch on the startup path, and no+/// pod that serves events for hours with warnings permanently off because the+/// cluster happened to be down the moment it started. librdkafka reconnects on+/// its own, so read `delivered`/`delivery_failed` to judge whether warnings are+/// landing — the enabled gauge only reports that the emitter exists.async fn create_ingestion_warning_emitter(config: &Config,handle: Option<lifecycle::Handle>,@@ -798,13 +800,11 @@ async fn create_ingestion_warning_emitter(config.capture_ingestion_warnings_kafka_message_max_bytes,);- let producer = match create_threaded_kafka_producer(+ let producer = match create_threaded_kafka_producer_no_ping(&warnings_kafka_config,handle.clone(),observe_delivery,- )- .await- {+ ) {Ok(producer) => producer,Err(e) => {tracing::error!(diff --git a/rust/common/ingestion_warnings/src/lib.rs b/rust/common/ingestion_warnings/src/lib.rsindex e2e2038af635..d8bdc088e8cd 100644--- a/rust/common/ingestion_warnings/src/lib.rs+++ b/rust/common/ingestion_warnings/src/lib.rs@@ -17,11 +17,14 @@//! counted and dropped — the caller's hot path is never blocked or failed.//!//! The producer is a `common_kafka` `ThreadedProducer` (built by-//! [`common_kafka::kafka_producer::create_threaded_kafka_producer`]) rather-//! than a bespoke client: callers supply their own dedicated, warnings-tuned-//! [`common_kafka::config::KafkaConfig`] (fire-and-forget acks/retries, a-//! small queue) so warnings never share tuning or a connection with a-//! caller's main event producer. Delivery reports are observed on the+//! [`common_kafka::kafka_producer::create_threaded_kafka_producer_no_ping`])+//! rather than a bespoke client: callers supply their own dedicated,+//! warnings-tuned [`common_kafka::config::KafkaConfig`] (fire-and-forget+//! acks/retries, a small queue) so warnings never share tuning or a connection+//! with a caller's main event producer. The no-ping constructor is the one that+//! matches this crate's contract — an unreachable cluster at boot must not+//! disable warnings for the process's life, let alone block the caller's+//! startup on a metadata fetch. Delivery reports are observed on the//! producer's own poll thread via [`observe_delivery`] (no per-message task);//! `emit` attaches the warning type/source as the delivery opaque so the//! async `delivered`/`delivery_failed` metric is attributed correctly.@@ -70,10 +73,16 @@ pub const INGESTION_WARNINGS_THROTTLE_KEYS: &str = "ingestion_warnings_throttle_/// indistinguishable from an intentionally quiet one. Absence means "off",/// `0` means "broken".///-/// Emitter construction is one-shot (`create_threaded_kafka_producer` fetches-/// metadata once, with no retry), so a broker blip at boot mutes that process-/// for its entire life. The only other symptom is lower-than-expected warning-/// volume, which is unobservable without a baseline. Alert on `min() == 0`.+/// `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+/// comes back. Only a genuinely unusable configuration reports `0`.+///+/// Whether warnings are actually landing is therefore a delivery question, not+/// a construction one — read the `delivered` and `delivery_failed` outcomes of+/// [`INGESTION_WARNINGS_TOTAL`] for that. Alert on `min() == 0` here to catch+/// misconfiguration, and on a sustained `delivery_failed` rate to catch a+/// broken destination.pub const INGESTION_WARNINGS_EMITTER_ENABLED: &str = "ingestion_warnings_emitter_enabled";/// Identifies which service — and which code path within it — produced a@@ -130,10 +139,10 @@ pub trait WarningEmitter: Send + Sync {/// Production emitter: per-(token, type) throttle in front of a/// `common_kafka` `ThreadedProducer`. Callers build the producer themselves-/// (via `common_kafka::kafka_producer::create_threaded_kafka_producer` with a-/// dedicated, fire-and-forget-tuned `KafkaConfig` and [`observe_delivery`] as-/// the delivery callback) and hand it in — this type never constructs its own-/// client. The producer's opaque is [`WarningDelivery`], so each message's+/// (via `common_kafka::kafka_producer::create_threaded_kafka_producer_no_ping`+/// with a dedicated, fire-and-forget-tuned `KafkaConfig` and+/// [`observe_delivery`] as the delivery callback) and hand it in — this type+/// never constructs its own client. The producer's opaque is [`WarningDelivery`], so each message's/// delivery report carries the type/source needed to label the async outcome/// metric.pub struct KafkaWarningEmitter {@@ -312,14 +321,14 @@ pub fn observe_delivery(result: &DeliveryResult, delivery: WarningDelivery) {#[cfg(test)]mod tests {+ use common_kafka::config::KafkaConfig;+ use common_kafka::kafka_producer::create_threaded_kafka_producer_no_ping;use common_liveness::SyncLivenessReporter;- use rdkafka::ClientConfig;use super::*;- /// No-op liveness sink: these tests build a producer directly (not via- /// `create_kafka_producer`) specifically to skip its 15s broker-metadata- /// ping, so there is no real health signal to report.+ /// No-op liveness sink: nothing in these tests polls a broker, so there is+ /// no real health signal to report.#[derive(Clone, Copy)]struct AlwaysHealthy;@@ -329,22 +338,22 @@ mod tests {}/// Build a threaded producer against an unreachable broker (TEST-NET-1)- /// without `create_threaded_kafka_producer`'s startup metadata fetch, so- /// tests stay fast and offline while still exercising the exact- /// `ThreadedProducer<ThreadedKafkaContext<WarningDelivery>>` type- /// `KafkaWarningEmitter` holds in production. `observe_delivery` is wired- /// as the callback, matching the production path.+ /// through the same constructor production uses, so these tests exercise+ /// the real construction path and not just the right type. It returns+ /// without a broker round-trip, which is what keeps them fast and offline.fn unreachable_producer(message_timeout_ms: u32,linger_ms: u32,) -> ThreadedProducer<ThreadedKafkaContext<WarningDelivery>> {- ClientConfig::new()- .set("bootstrap.servers", "192.0.2.1:9092")- .set("message.timeout.ms", message_timeout_ms.to_string())- .set("linger.ms", linger_ms.to_string())- .set("queue.buffering.max.messages", "10")- .set("retries", "0")- .create_with_context(ThreadedKafkaContext::new(AlwaysHealthy, observe_delivery))+ let config = KafkaConfig {+ kafka_hosts: "192.0.2.1:9092".to_string(),+ kafka_message_timeout_ms: message_timeout_ms,+ kafka_producer_linger_ms: linger_ms,+ kafka_producer_queue_messages: 10,+ kafka_producer_retries: Some(0),+ ..Default::default()+ };+ create_threaded_kafka_producer_no_ping(&config, AlwaysHealthy, observe_delivery).expect("client config is valid, so creation cannot fail without a broker round-trip")}diff --git a/rust/common/kafka/src/kafka_producer.rs b/rust/common/kafka/src/kafka_producer.rsindex 9a96a8e836b5..8e54607b0711 100644--- a/rust/common/kafka/src/kafka_producer.rs+++ b/rust/common/kafka/src/kafka_producer.rs@@ -239,6 +239,12 @@ impl<K: Send + Sync + 'static> ProducerContext for ThreadedKafkaContext<K> {/// the opt-in path for fire-and-forget producers that want delivery/// observability without a per-message task; existing `FutureProducer` callers/// are unaffected.+///+/// Pings the brokers before returning, so an unreachable cluster fails here+/// rather than silently later. That costs up to 15s at startup and makes an+/// unreachable cluster fatal to construction: appropriate when the producer+/// carries data the service exists to deliver. Best-effort producers should+/// use [`create_threaded_kafka_producer_no_ping`] instead.pub async fn create_threaded_kafka_producer<K, L, F>(config: &KafkaConfig,liveness: L,@@ -249,16 +255,45 @@ whereL: SyncLivenessReporter + Clone + 'static,F: Fn(&DeliveryResult, K) + Send + Sync + 'static,{- let client_config = build_client_config(config);- debug!("rdkafka configuration (threaded): {:?}", client_config);- let producer: ThreadedProducer<ThreadedKafkaContext<K>> =- client_config.create_with_context(ThreadedKafkaContext::new(liveness, on_delivery))?;+ let producer = create_threaded_kafka_producer_no_ping(config, liveness, on_delivery)?;ping_brokers(&producer)?;Ok(producer)}+/// Same as [`create_threaded_kafka_producer`] but returns as soon as the client+/// is built, with no startup broker ping.+///+/// librdkafka connects and fetches metadata lazily on its own refresh+/// schedule, so a producer built this way recovers by itself once the cluster+/// becomes reachable. The ping only converts that transient state into an+/// immediate error, which is the wrong trade for a best-effort producer: a+/// broker blip at boot would disable the feature for the process's whole life,+/// and the 15s fetch runs while the caller is still assembling itself.+///+/// Because construction no longer proves the cluster is reachable, judge these+/// producers by their delivery reports (see [`ThreadedKafkaContext`]) rather+/// than by whether they were built.+///+/// Synchronous by design: there is nothing to await once the ping is gone, and+/// callers building a producer outside an async context (including tests)+/// shouldn't need a runtime for it.+pub fn create_threaded_kafka_producer_no_ping<K, L, F>(+ config: &KafkaConfig,+ liveness: L,+ on_delivery: F,+) -> Result<ThreadedProducer<ThreadedKafkaContext<K>>, KafkaError>+where+ K: Send + Sync + 'static,+ L: SyncLivenessReporter + Clone + 'static,+ F: Fn(&DeliveryResult, K) + Send + Sync + 'static,+{+ let client_config = build_client_config(config);+ debug!("rdkafka configuration (threaded): {:?}", client_config);+ client_config.create_with_context(ThreadedKafkaContext::new(liveness, on_delivery))+}+#[derive(Error, Debug)]pub enum KafkaProduceError {#[error("failed to serialize: {error}")]@@ -493,12 +528,53 @@ mod tests {use lz4::Decoder;+ use common_liveness::SyncLivenessReporter;+ use rdkafka::producer::DeliveryResult;+use super::{- build_client_config, compress_lz4_frame, maybe_compress_lz4_frame, EnvelopeEncoding,+ build_client_config, compress_lz4_frame, create_threaded_kafka_producer_no_ping,+ maybe_compress_lz4_frame, EnvelopeEncoding,};use crate::config::KafkaConfig;use crate::kafka_consumer::LZ4_FRAME_MAGIC;+ #[derive(Clone, Copy)]+ struct AlwaysHealthy;++ impl SyncLivenessReporter for AlwaysHealthy {+ fn report_healthy(&self) {}+ fn report_unhealthy(&self) {}+ }++ /// The no-ping builder must return promptly against an unreachable cluster+ /// (TEST-NET-1) instead of failing after the 15s metadata fetch its pinging+ /// sibling performs. That is the whole reason best-effort producers use it,+ /// and this is also what keeps it callable without a tokio runtime.+ #[test]+ fn no_ping_producer_builds_promptly_against_unreachable_broker() {+ let config = KafkaConfig {+ kafka_hosts: "192.0.2.1:9092".to_string(),+ ..Default::default()+ };++ let start = std::time::Instant::now();+ let producer = create_threaded_kafka_producer_no_ping(+ &config,+ AlwaysHealthy,+ |_: &DeliveryResult, ()| {},+ );+ let elapsed = start.elapsed();++ assert!(+ producer.is_ok(),+ "an unreachable cluster must not fail construction"+ );+ assert!(+ elapsed < std::time::Duration::from_secs(2),+ "took {elapsed:?}, so a broker round-trip is still happening"+ );+ }+#[test]fn client_id_is_set_only_when_non_empty() {// Empty client_id (every existing caller today) must leave the keydiff --git a/rust/common/lifecycle/README.md b/rust/common/lifecycle/README.mdindex 476a6d62f228..6259bb211fad 100644--- a/rust/common/lifecycle/README.md+++ b/rust/common/lifecycle/README.md@@ -118,7 +118,7 @@ All options except `name` have sensible defaults.| ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ || `ComponentOptions::new()` | Base options with defaults for all fields. | — || `.is_observability(bool)` | Mark as an observability handle (e.g. metrics server). Shut down *after* all standard components finish. Cannot combine with `with_liveness_deadline`. (see test `observability_handle_shuts_down_after_standard_handles`) | `false` |-| `.is_advisory(bool)` | Mark as advisory. Participates in health monitoring (gauge, `is_healthy()`) but stalls do NOT trigger shutdown. Monitor does not wait for advisory handles during shutdown. Requires `with_liveness_deadline`. Cannot combine with `is_observability`. (see test `advisory_handle_stall_does_not_trigger_shutdown`) | `false` |+| `.is_advisory(bool)` | Mark as advisory. Participates in health monitoring (gauge, `is_healthy()`) but neither stalls nor death trigger shutdown. Monitor does not wait for advisory handles during shutdown. Requires `with_liveness_deadline`. Cannot combine with `is_observability`. (see test `advisory_handle_stall_does_not_trigger_shutdown`) | `false` || `.with_graceful_shutdown(duration)` | Max time for this component to clean up after shutdown begins. Exceeded = marked timed out. (see test `component_timeout_then_late_drop_preserves_timeout`) | `None` — waits indefinitely (bounded by `global_shutdown_timeout`). Observability handles default to `1s` if unset. || `.with_liveness_deadline(duration)` | Component must call `report_healthy()` within this interval or the health monitor considers it stalled. After `stall_threshold` consecutive stalled checks, the manager triggers global shutdown. (see test `stall_triggers_shutdown`) | `None` — no health monitoring || `.with_stall_threshold(n)` | Number of consecutive stalled health checks before the manager triggers global shutdown. Set higher for tolerance of transient hiccups. Only meaningful with `with_liveness_deadline`. (see test `stall_threshold_allows_recovery`) | `1` — immediate shutdown on first stall |@@ -366,7 +366,7 @@ guard.wait().await?;## Advisory handles-Advisory handles (`is_advisory(true)`) participate in health monitoring — the health poll task updates their `lifecycle_component_healthy` gauge and their `is_healthy()` flag — but stalls do **not** trigger global shutdown.+Advisory handles (`is_advisory(true)`) participate in health monitoring — the health poll task updates their `lifecycle_component_healthy` gauge and their `is_healthy()` flag — but neither a stall nor the component's death triggers global shutdown.The monitor does not wait for advisory handles during shutdown.### When to use@@ -378,10 +378,10 @@ The canonical example is `FallbackSink`: it needs to know if the primary Kafka s- **Health gauge updates**: The poll task still writes `lifecycle_component_healthy` for advisory handles — dashboards see the same metrics as standard handles.- **`is_healthy()` works**: Returns the poll task's latest health assessment via a shared `AtomicBool` (~1ns read). Starts `true` (Starting state is healthy). Flips to `false` after `stall_threshold` consecutive stalled/unhealthy polls. Flips back on recovery. Lags behind `report_healthy()` by up to `health_poll_interval`.-- **Stall counting without shutdown**: Stall counts are tracked the same as standard handles — `stall_threshold` gates when `is_healthy()` flips to `false`. The only difference is that advisory handles never send `ComponentEvent::Failure`, so they never trigger global shutdown.+- **Stall counting without shutdown**: Stall counts are tracked the same as standard handles — `stall_threshold` gates when `is_healthy()` flips to `false`. The health poll task never sends `ComponentEvent::Failure` for an advisory handle, so a stall alone never triggers global shutdown. Note that `signal_failure()` remains callable and *does* trigger shutdown — it is an explicit act by the component author, not a health signal.- **Not waited on during shutdown**: Advisory handles are not in the component maps, so the monitor's drain phases ignore them. The app shuts down as soon as all standard (and observability) components finish.- **Standard shutdown token**: Advisory handles receive the standard `shutdown_token`, so `shutdown_recv()` and `is_shutting_down()` work normally for cooperative cleanup.-- **Drop guard**: Events from advisory handle drops are sent to the monitor channel but harmlessly ignored (no entry in component maps).+- **Drop guard**: Dropping an advisory handle during normal operation sends `ComponentEvent::Died`, which the monitor logs and ignores rather than shutting down. This covers a best-effort component that fails to construct, returns early, or whose task panics. (see tests `advisory_handle_drop_during_normal_operation_does_not_trigger_shutdown`, `panic_in_advisory_task_does_not_trigger_shutdown`)- **Requires `with_liveness_deadline`**: The health poll task needs a deadline to evaluate. Registration panics without it.- **Cannot combine with `is_observability`**: Advisory and observability are mutually exclusive.- **Cannot use `with_graceful_shutdown`**: Advisory handles are not in the component maps, so graceful shutdown timeouts would be silently ignored. Registration panics if both are set.diff --git a/rust/common/lifecycle/src/manager.rs b/rust/common/lifecycle/src/manager.rsindex 7c94d5e8afea..50796eda16fe 100644--- a/rust/common/lifecycle/src/manager.rs+++ b/rust/common/lifecycle/src/manager.rs@@ -466,6 +466,16 @@ impl Manager {self.observability_components.contains_key(tag)}+ /// Advisory components are deliberately absent from `components` and+ /// `observability_components`, so `liveness_components` is the only record+ /// of them. Registration requires a liveness deadline for advisory handles,+ /// which guarantees every one of them is present here.+ fn is_advisory_tag(&self, tag: &str) -> bool {+ self.liveness_components+ .iter()+ .any(|c| c.tag == tag && c.advisory)+ }+async fn run_monitor_loop(mut self,mut event_rx: mpsc::Receiver<ComponentEvent>,@@ -597,6 +607,17 @@ impl Manager {break;}ComponentEvent::Died { tag } => {+ // Advisory components are best-effort by contract: their+ // death is informational, so it must not take the process+ // with it. Health stalls are already exempt in the poll+ // task; without this the exemption is trivially bypassed+ // by dropping the handle, which is what a failed+ // construction or a panicking task does.+ if self.is_advisory_tag(&tag) {+ info!(component = %tag,+ "Lifecycle: advisory component died, continuing");+ continue;+ }metrics::emit_shutdown_initiated(&name, &tag, "died");warn!(trigger_component = %tag, trigger_reason = "died","Lifecycle: shutdown initiated, component died unexpectedly");diff --git a/rust/common/lifecycle/tests/lifecycle_tests.rs b/rust/common/lifecycle/tests/lifecycle_tests.rsindex 877a5b7762d2..5b60c11724af 100644--- a/rust/common/lifecycle/tests/lifecycle_tests.rs+++ b/rust/common/lifecycle/tests/lifecycle_tests.rs@@ -1387,6 +1387,94 @@ async fn advisory_rejects_graceful_shutdown() {);}+/// Advisory handle dropped during normal operation — the app keeps running.+/// The existing stall tests only drop advisory handles after shutdown has+/// begun, where any drop is treated as completion; this covers the drop that+/// actually produces a Died event. A best-effort component that fails to+/// build, or whose task exits early, must not take the process down with it.+#[tokio::test]+async fn advisory_handle_drop_during_normal_operation_does_not_trigger_shutdown() {+ let mut manager = fast_poll_manager(50);+ let std_handle = manager.register("worker", ComponentOptions::new());+ let advisory_handle = manager.register("kafka-health", advisory_opts());+ let guard = manager.monitor_background();++ drop(advisory_handle);++ // Several poll intervals, so a Died-driven cancel would have landed.+ tokio::time::sleep(Duration::from_millis(300)).await;+ assert!(+ !std_handle.is_shutting_down(),+ "advisory handle drop must not initiate global shutdown"+ );++ std_handle.request_shutdown();+ drop(std_handle);++ let result = tokio::time::timeout(Duration::from_secs(10), guard.wait())+ .await+ .expect("timed out");+ assert!(+ result.is_ok(),+ "advisory drop must not surface as a lifecycle error, got {result:?}"+ );+}++/// A panic in the task owning an advisory handle unwinds and drops the handle+/// during normal operation. This is the production shape of the case above:+/// the warnings emitter's background task panicking must not shut capture down.+#[tokio::test]+async fn panic_in_advisory_task_does_not_trigger_shutdown() {+ let mut manager = fast_poll_manager(50);+ let std_handle = manager.register("worker", ComponentOptions::new());+ let advisory_handle = manager.register("kafka-health", advisory_opts());+ let guard = manager.monitor_background();++ let panicked = tokio::spawn(async move {+ advisory_handle.report_healthy();+ panic!("boom");+ })+ .await;+ assert!(panicked.is_err(), "task was expected to panic");++ tokio::time::sleep(Duration::from_millis(300)).await;+ assert!(+ !std_handle.is_shutting_down(),+ "advisory task panic must not initiate global shutdown"+ );++ std_handle.request_shutdown();+ drop(std_handle);++ let result = tokio::time::timeout(Duration::from_secs(10), guard.wait())+ .await+ .expect("timed out");+ assert!(result.is_ok(), "expected clean shutdown, got {result:?}");+}++/// Regression guard for the advisory exemption: a standard handle dropped+/// during normal operation must still trigger shutdown even when an advisory+/// component is registered alongside it. Catches an exemption predicate that+/// matches too broadly.+#[tokio::test]+async fn standard_handle_drop_still_triggers_shutdown_when_advisory_registered() {+ let mut manager = fast_poll_manager(50);+ let std_handle = manager.register("worker", ComponentOptions::new());+ let advisory_handle = manager.register("kafka-health", advisory_opts());+ let guard = manager.monitor_background();++ advisory_handle.report_healthy();+ drop(std_handle);++ let result = tokio::time::timeout(Duration::from_secs(10), guard.wait())+ .await+ .expect("timed out");+ assert!(+ matches!(&result, Err(LifecycleError::ComponentDied { tag }) if tag == "worker"),+ "expected ComponentDied for the standard component, got {result:?}"+ );+}+// ---------------------------------------------------------------------------// Section 9: is_healthy() on non-liveness handles//