: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(personhog): ride out non-fatal consumer errors during warm (#80162)
Zach Brown941ae635df3f
diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rsindex 81976b962664..135a865ed961 100644--- a/rust/personhog-leader/src/main.rs+++ b/rust/personhog-leader/src/main.rs@@ -195,6 +195,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {Matcher::Full("personhog_coordination_partition_warm_ms".into()),WARM_LATENCY_BUCKETS_MS,),+ (+ Matcher::Full("personhog_leader_warm_span_ms".into()),+ WARM_LATENCY_BUCKETS_MS,+ ),],);preregister_metrics();@@ -792,4 +796,11 @@ fn preregister_metrics() {for stage in ["committed_offset", "fetch_watermarks"] {counter!("personhog_leader_warm_retries_total", "stage" => stage).increment(0);}+ // A broker blip is short enough to fall entirely between two+ // scrapes, and these fire only during one. The codes seen in dev are+ // preregistered so that burst is not swallowed; anything else stays+ // lazy, as elsewhere for dynamic labels.+ for code in ["BrokerTransportFailure", "AllBrokersDown"] {+ counter!("personhog_leader_warm_transient_errors_total", "code" => code).increment(0);+ }}diff --git a/rust/personhog-leader/src/warming.rs b/rust/personhog-leader/src/warming.rsindex 23b338e40e5c..23d177bbbc0f 100644--- a/rust/personhog-leader/src/warming.rs+++ b/rust/personhog-leader/src/warming.rs@@ -7,9 +7,10 @@ use common_kafka::config::KafkaConfig;use metrics::{counter, histogram};use prost::Message as ProtoMessage;use rdkafka::consumer::{Consumer, StreamConsumer};+use rdkafka::error::KafkaError;use rdkafka::message::Message;use rdkafka::{ClientConfig, Offset, TopicPartitionList};-use tokio::time::timeout;+use tokio::time::{sleep, timeout};use personhog_coordination::error::{Error as CoordError, Result as CoordResult};use personhog_proto::personhog::types::v1::Person;@@ -28,8 +29,10 @@ pub struct WarmingRetryPolicy {/// metadata calls that talk to Kafka brokers (fetch watermarks, committed/// offsets) so a single transient network blip doesn't cycle the pod.///-/// The consume loop itself is not retried — it holds partial progress and-/// re-seeking is its own concern; leave to a follow-up if we see flakes.+/// The consume loop is not retried and does not need to be: it rides+/// out non-fatal consumer errors in place while librdkafka handles them,+/// bounded by `recv_timeout`. A fatal client state — and a genuine+/// stall — ends it.async fn with_warm_retry<T, F, Fut>(stage: &str,partition: u32,@@ -141,11 +144,14 @@ pub(crate) fn make_consumer(/// A checkout stack of assign-only Kafka clients sharing one group id./// Clients are checked out for the duration of one operation, returned on-/// success, and dropped on error — a client that just failed is never-/// reused, so error hygiene is structural. None of these clients ever-/// joins the group protocol (no subscribe), so the group id is broker-/// bookkeeping, not membership: pooling clients in the writer's group-/// cannot affect the writer's rebalancing.+/// success, and dropped when the operation fails — a client whose+/// operation just failed is never reused, so error hygiene is structural.+/// A non-fatal error the operation rode out does not count as failure:+/// the client handled it and completed, and both the consume loop and+/// the give-back verify the client-level fatal state. None of these+/// clients ever joins the group protocol (no subscribe), so the group id+/// is broker bookkeeping, not membership: pooling clients in the+/// writer's group cannot affect the writer's rebalancing.////// The pool exists because client construction is the dominant cost of/// the operations it serves: a fresh consumer pays connection setup,@@ -195,6 +201,21 @@ impl ConsumerPool {/// the failure logged so a systematic cleanup problem surfaces as a/// visible signal rather than silent churn.pub fn give_back(&self, consumer: StreamConsumer) {+ // The unassign gate below cannot catch a fatal client —+ // librdkafka treats ops on one as successful unassigns — so the+ // contract that a dead client is never pooled is enforced here+ // by construction rather than left to the accident that+ // consumer fatals only arise from group paths these clients+ // never join.+ if let Some((code, reason)) = consumer.client().fatal_error() {+ tracing::warn!(+ pool = self.label,+ code = format!("{code:?}"),+ reason,+ "client in a fatal state; dropping instead of pooling it"+ );+ return;+ }if let Err(e) = consumer.unassign() {tracing::warn!(pool = self.label,@@ -356,6 +377,14 @@ fn resolve_start_offset(committed: Option<i64>, earliest: i64, lookback: i64) ->}}+/// One warm sub-span sample. The spans share the warm bucket ladder and+/// sum to slightly less than `warm_duration_ms`, whose remainder is the+/// dirty-index seeding and the cache install.+fn record_warm_span(span: &'static str, start: Instant) {+ histogram!("personhog_leader_warm_span_ms", "span" => span)+ .record(start.elapsed().as_secs_f64() * 1000.0);+}+/// Populate the cache from Kafka for a single partition.////// Invariants at call time (enforced by the handoff protocol). The@@ -387,7 +416,12 @@ pub async fn warm_from_kafka(// Arc because the watermark retry closure needs its own handle for// the blocking pool; sole ownership returns once the retries finish.+ // The sub-spans below decompose the warm's wall clock so a slow one+ // is attributable: client construction is lazy, so a cold client's+ // connection cost lands in the metadata span, not the checkout.+ let span_start = Instant::now();let consumer = Arc::new(pools.warming.checkout()?);+ record_warm_span("checkout", span_start);// The two offset queries are independent — the writer's committed// position comes from the offsets pool, the watermarks from this@@ -419,7 +453,9 @@ pub async fn warm_from_kafka(.map_err(|e| CoordError::invalid_state(format!("fetch_watermarks join: {e}")))?}});+ let span_start = Instant::now();let (committed_res, watermarks_res) = tokio::join!(committed_fut, watermarks_fut);+ record_warm_span("metadata", span_start);let (low, hwm) = match watermarks_res {Ok(marks) => marks,// The watermark call failed on this consumer, so the pool's@@ -468,6 +504,7 @@ pub async fn warm_from_kafka(return Ok(());}+ let span_start = Instant::now();let mut assign_tpl = TopicPartitionList::new();assign_tpl.add_partition_offset(&cfg.topic, partition_i32, Offset::Offset(start_offset))@@ -495,6 +532,62 @@ pub async fn warm_from_kafka(loop {let msg = match timeout(poll_slice, consumer.recv()).await {Ok(Ok(m)) => m,+ // A non-fatal consumer error means librdkafka is handling it:+ // a connection blip resolves by reconnecting with the fetch+ // position intact, and the stream never terminates, so the+ // answer is to keep polling — as the fleet's streaming+ // consumers do. The per-event fatal split is not the whole+ // fatality story, so the client-level fatal state (an+ // unrecoverable idempotence or authentication failure) is+ // checked first: it survives even when the event that set it+ // was consumed, and a dead client must not be re-polled while+ // reporting progress.+ //+ // The accepted trade, stated for the record: librdkafka also+ // reports record-skipping through this same non-fatal channel+ // — an unreadable message set is discarded and the fetch+ // position advances past it — and riding one out publishes a+ // cache missing the skipped records. Today that requires+ // broker-side corruption of bytes no consumer could read+ // anyway, or a record format newer than this client, which+ // does not exist. Stop-class errors (an ACL revocation, a+ // deleted topic) also ride, costing the stall budget and a+ // generic stall error instead of an immediate named one; the+ // code survives in the counter label and the warn line.+ Ok(Err(KafkaError::MessageConsumption(code))) => {+ if let Some((fatal_code, reason)) = consumer.client().fatal_error() {+ return Err(CoordError::invalid_state(format!(+ "warm consumer entered a fatal state ({fatal_code:?}): {reason}"+ )));+ }+ // An error is not progress: the stall budget keeps+ // running, so errors arriving faster than the quiet arm+ // can observe still end the warm on time.+ if quiet_since.elapsed() >= cfg.recv_timeout {+ return Err(CoordError::invalid_state(format!(+ "warm stalled on repeated consumer errors (last: {code:?}); \+ consumed {count} msgs, last_offset={last_offset}, hwm={hwm}",+ count = buffered.len()+ )));+ }+ counter!(+ // Debug renders the bare variant ("BrokerTransportFailure");+ // Display appends librdkafka's prose, which makes a+ // poor label value.+ "personhog_leader_warm_transient_errors_total",+ "code" => format!("{code:?}")+ )+ .increment(1);+ tracing::warn!(+ partition,+ error = %code,+ "non-fatal consumer error during warm; riding it out"+ );+ // A fast-failing recv would otherwise spin this loop hot+ // for the whole stall budget.+ sleep(poll_slice).await;+ continue;+ }Ok(Err(e)) => {return Err(CoordError::invalid_state(format!("warm recv: {e}")));}@@ -556,6 +649,8 @@ pub async fn warm_from_kafka(}}+ record_warm_span("consume", span_start);+// Records at or above the writer's committed offset are not yet in PG:// seed the dirty index so that, if the cache later evicts them, a miss// recovers from the changelog instead of trusting a stale PG row. Withdiff --git a/rust/personhog-leader/tests/warming_integration.rs b/rust/personhog-leader/tests/warming_integration.rsindex 597162933522..85e2f75a2844 100644--- a/rust/personhog-leader/tests/warming_integration.rs+++ b/rust/personhog-leader/tests/warming_integration.rs@@ -16,6 +16,7 @@ use rdkafka::config::ClientConfig;use rdkafka::consumer::{BaseConsumer, CommitMode, Consumer};use rdkafka::mocking::MockCluster;use rdkafka::producer::{DefaultProducerContext, FutureProducer, FutureRecord};+use rdkafka::types::{RDKafkaApiKey, RDKafkaRespErr};use rdkafka::{Offset, TopicPartitionList};/// Build a Person proto with deterministic fields — enough that the@@ -581,3 +582,88 @@ async fn warm_up_fills_every_slot() {"prewarming three slots must create three distinct clients");}++/// A broker blip inside the consume loop must not fail the warm.+/// librdkafka reports a still-reconnecting client through the same+/// channel as a dead one and marks the difference itself; treating the+/// non-fatal variant as a failed read aborted the warm, and because+/// event-triggered convergence is fatal to the run, one partition's blip+/// tore down every partition that pod was converging.+#[tokio::test]+async fn warming_tolerates_a_transient_consumer_error() {+ let (cluster, producer) = create_test_kafka().await;++ for person_id in 1..=3 {+ let person = make_person(1, person_id);+ produce_person_to_partition(&producer, 0, &person).await;+ }++ // Fail the first attempt's fetches at the transport layer, the shape+ // an MSK coordinator reload produced in dev.+ cluster.request_errors(+ RDKafkaApiKey::Fetch,+ &[+ RDKafkaRespErr::RD_KAFKA_RESP_ERR__TRANSPORT,+ RDKafkaRespErr::RD_KAFKA_RESP_ERR__TRANSPORT,+ ],+ );++ let cache = PartitionedCache::new(1 << 20);+ let (cfg, pools) = warming_config_for("warmer-transient", &cluster);++ warm_from_kafka(&cfg, &pools, &cache, &DirtyIndex::new(1_000_000), 0)+ .await+ .expect("a non-fatal consumer error must not fail the warm");++ assert!(cache.has_partition(0), "partition 0 must be marked owned");+ for person_id in 1..=3 {+ let key = PersonCacheKey {+ team_id: 1,+ person_id,+ };+ assert!(+ matches!(cache.get(0, &key), CacheLookup::Found(_)),+ "person_id={person_id} must be warmed after the blip"+ );+ }+}++/// A persistent non-connection consumer error must still end the warm+/// inside the stall budget with nothing installed. Under the ride-out+/// pattern the cause surfaces via the counter and warn logs rather than+/// the error string, but the warm must never hang past its budget or+/// publish a partial cache.+#[tokio::test]+async fn warming_still_fails_on_a_persistent_stop_class_error() {+ let (cluster, producer) = create_test_kafka().await;++ for person_id in 1..=3 {+ let person = make_person(1, person_id);+ produce_person_to_partition(&producer, 0, &person).await;+ }++ // An auth failure stops the partition's fetch rather than resolving+ // by reconnection; the warm rides the error events, goes quiet, and+ // the stall budget must end it.+ cluster.request_errors(+ RDKafkaApiKey::Fetch,+ &[RDKafkaRespErr::RD_KAFKA_RESP_ERR_TOPIC_AUTHORIZATION_FAILED; 64],+ );++ let cache = PartitionedCache::new(1 << 20);+ let (mut cfg, pools) = warming_config_for("warmer-stop-class", &cluster);+ cfg.recv_timeout = Duration::from_secs(2);++ let result = warm_from_kafka(&cfg, &pools, &cache, &DirtyIndex::new(1_000_000), 0).await;+ let err = result.expect_err("a persistent stop-class error must end the warm");+ // The stall path, not an immediate abort: riding the error out means+ // the warm ends only when the budget expires with no records read.+ assert!(+ err.to_string().contains("consumed 0 msgs"),+ "expected the stall budget to end the warm, got: {err}"+ );+ assert!(+ !cache.has_partition(0),+ "a failed warm must install nothing"+ );+}diff --git a/rust/personhog-writer/src/consumer.rs b/rust/personhog-writer/src/consumer.rsindex feee6a9d0b28..995e4243fb96 100644--- a/rust/personhog-writer/src/consumer.rs+++ b/rust/personhog-writer/src/consumer.rs@@ -188,6 +188,18 @@ impl ConsumerTask {Err(e) => {counter!("personhog_writer_kafka_errors_total").increment(1);warn!(error = %e, "Kafka recv error");+ // A non-fatal error is librdkafka riding out a+ // blip and needs nothing from us. A fatal+ // client state never recovers: left here, the+ // loop re-polls a dead client forever while+ // the pod reports healthy and its partitions'+ // records go unwritten.+ if let Some((code, reason)) = self.consumer.fatal_error() {+ self.handle.signal_failure(format!(+ "Kafka client entered a fatal state ({code:?}): {reason}"+ ));+ return;+ }}}}diff --git a/rust/personhog-writer/src/kafka.rs b/rust/personhog-writer/src/kafka.rsindex 9f53957db985..7a628b264c64 100644--- a/rust/personhog-writer/src/kafka.rs+++ b/rust/personhog-writer/src/kafka.rs@@ -15,6 +15,13 @@ pub struct PersonConsumer {}impl PersonConsumer {+ /// Client-level fatal state, queryable even after the event that+ /// set it was consumed. A fatal client never recovers, so the+ /// caller must exit rather than keep polling it.+ pub fn fatal_error(&self) -> Option<(rdkafka::error::RDKafkaErrorCode, String)> {+ self.consumer.client().fatal_error()+ }+pub fn from_config(kafka: &KafkaConfig,consumer_group: &str,