: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): heal condemned fences on condemnation (#80826)
Zach Brown6e7729025c6c
diff --git a/rust/personhog-coordination/src/pod.rs b/rust/personhog-coordination/src/pod.rsindex ca239a2ef97a..77767336cd08 100644--- a/rust/personhog-coordination/src/pod.rs+++ b/rust/personhog-coordination/src/pod.rs@@ -273,6 +273,11 @@ pub struct PodHandle {authority: Arc<AuthorityClock>,/// Optional K8s awareness for departure classification during shutdown.k8s_awareness: Option<Arc<K8sAwareness>>,+ /// Nudged when serving state broke in a way only a convergence can+ /// mend (the leader nudges when a changelog producer is condemned).+ /// The watch loop answers with an early reconcile pass, so repair+ /// happens now rather than on the next tick.+ repair_nudge: Option<Arc<Notify>>,}impl PodHandle {@@ -306,9 +311,20 @@ impl PodHandle {fence_poisoned: AtomicBool::new(false),authority,k8s_awareness,+ repair_nudge: None,}}+ /// Run a reconcile pass whenever `nudge` fires, in addition to the+ /// periodic tick. The nudging end announces breakage the protocol+ /// has no event for — the leader's condemned changelog producer —+ /// and this is what turns its repair latency from one reconcile+ /// interval into one convergence.+ pub fn with_repair_nudge(mut self, nudge: Arc<Notify>) -> Self {+ self.repair_nudge = Some(nudge);+ self+ }+/// This pod's claim to serve, for the data plane to consult on the/// request path. Invalid until the first lease is granted.pub fn authority(&self) -> Arc<AuthorityClock> {@@ -1243,6 +1259,24 @@ impl PodHandle {let mut in_flight: HashSet<u32> = HashSet::new();let mut pending: HashMap<u32, Trigger> = HashMap::new();+ // One nudge-driven pass per reconcile interval at most. A+ // producer that condemns again right after every heal would+ // otherwise drive passes at broker speed — and each successful+ // heal counts as applied work, resetting the budgets that exist+ // to catch exactly that wedge. A suppressed nudge falls back to+ // the tick, so a flap degrades to tick-rate healing, the+ // pre-nudge shape.+ let mut last_repair_pass: Option<tokio::time::Instant> = None;++ /// Resolves when the repair nudge fires, or never when none is+ /// wired, leaving the other arms in charge.+ async fn nudged(nudge: &Option<Arc<Notify>>) {+ match nudge {+ Some(nudge) => nudge.notified().await,+ None => std::future::pending().await,+ }+ }+fn dispatch<'s>(handle: &'s PodHandle,partition: u32,@@ -1362,6 +1396,56 @@ impl PodHandle {}}}+ _ = nudged(&self.repair_nudge) => {+ let now = tokio::time::Instant::now();+ let cooling = last_repair_pass.is_some_and(|last| {+ now.duration_since(last) < self.config.reconcile_interval+ });+ if cooling {+ counter!("personhog_coordination_repair_passes_total", "outcome" => "suppressed")+ .increment(1);+ tracing::warn!(+ pod = %self.config.pod_name,+ "repair nudged again inside the cooldown; leaving it to the reconcile tick"+ );+ } else {+ last_repair_pass = Some(now);+ counter!("personhog_coordination_repair_passes_total", "outcome" => "run")+ .increment(1);+ tracing::info!(+ pod = %self.config.pod_name,+ "data-plane repair nudge; converging involved partitions"+ );+ // The same derivation the tick runs: the nudge+ // carries no payload, and `verify_serving`+ // repairs exactly the partitions that need it+ // while the rest converge as no-ops. Reconcile+ // severity throughout; a failed snapshot leaves+ // repair to the tick, whose budget owns+ // sustained failure.+ match self.involved_partitions().await {+ Ok((partitions, _)) => {+ for partition in partitions {+ dispatch(+ self,+ partition,+ Trigger::Reconcile,+ &mut in_flight,+ &mut pending,+ &mut lanes,+ );+ }+ }+ Err(e) => {+ tracing::warn!(+ pod = %self.config.pod_name,+ error = %e,+ "repair-pass snapshot failed; leaving repair to the reconcile tick"+ );+ }+ }+ }+ }msg = stream.message() => {let resp = msg?.ok_or_else(|| Error::invalid_state("handoff watch stream ended".to_string()))?;for event in resp.events() {diff --git a/rust/personhog-coordination/tests/protocol_hardening.rs b/rust/personhog-coordination/tests/protocol_hardening.rsindex a5ee44d7c5e5..93fc414a0bc2 100644--- a/rust/personhog-coordination/tests/protocol_hardening.rs+++ b/rust/personhog-coordination/tests/protocol_hardening.rs@@ -16,7 +16,7 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::sync::Arc;use std::time::Duration;-use tokio::sync::{Mutex, RwLock};+use tokio::sync::{Mutex, Notify, RwLock};use tokio_util::sync::CancellationToken;use assignment_coordination::store::parse_watch_value;@@ -4086,3 +4086,138 @@ async fn phase_advance_refuses_a_handoff_that_was_replaced() {"a replaced handoff must not be advanced by its predecessor's quorum");}++/// Records `verify_serving` calls — the repair a data-plane repair+/// request exists to trigger.+struct RepairProbeHandler {+ events: Arc<Mutex<Vec<HandoffEvent>>>,+ verified: Arc<AtomicUsize>,+}++#[async_trait]+impl personhog_coordination::pod::HandoffHandler for RepairProbeHandler {+ async fn drain_partition_inflight(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Drained(partition));+ Ok(())+ }++ async fn warm_partition(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Warmed(partition));+ Ok(())+ }++ async fn verify_serving(&self, _partition: u32) -> Result<bool> {+ self.verified.fetch_add(1, Ordering::SeqCst);+ Ok(false)+ }++ async fn release_partition(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Released(partition));+ Ok(())+ }++ async fn resume_partition(&self, partition: u32) -> Result<()> {+ self.events+ .lock()+ .await+ .push(HandoffEvent::Resumed(partition));+ Ok(())+ }+}++/// A data-plane repair nudge must converge immediately. The+/// condemned-producer incident this pins: every write on the partition+/// bounces until `verify_serving` re-takes the fence, and with the+/// reconcile tick as the only trigger that wait is a whole interval.+/// Here reconcile is parked at a day and no etcd event fires, so the+/// only thing that can drive the second `verify_serving` is the nudge+/// arm itself.+#[tokio::test]+async fn a_repair_nudge_converges_without_waiting_for_reconcile() {+ let store = test_store("repair-request-converges").await;+ let cancel = CancellationToken::new();++ store+ .put_assignments(&[PartitionAssignment {+ partition: 0,+ owner: "repair-pod".to_string(),+ status: AssignmentStatus::Active,+ advertise_address: None,+ }])+ .await+ .expect("write assignment");++ let events: Arc<Mutex<Vec<HandoffEvent>>> = Arc::new(Mutex::new(Vec::new()));+ let verified = Arc::new(AtomicUsize::new(0));+ let handler = RepairProbeHandler {+ events: Arc::clone(&events),+ verified: Arc::clone(&verified),+ };+ let nudge = Arc::new(Notify::new());+ let pod = personhog_coordination::pod::PodHandle::new(+ Arc::clone(&store),+ personhog_coordination::pod::PodConfig {+ pod_name: "repair-pod".to_string(),+ // A session restart re-runs the seed convergence, which also+ // bumps `verified`; a 30s lease keeps restarts out of this+ // test's window so only the repair arm can move the counter.+ lease_ttl: 30,+ heartbeat_interval: Duration::from_secs(10),+ reconcile_interval: Duration::from_secs(86_400),+ ..Default::default()+ },+ Arc::new(handler),+ None,+ Arc::new(AuthorityClock::unclaimed()),+ )+ .with_repair_nudge(Arc::clone(&nudge));+ let token = cancel.child_token();+ tokio::spawn(async move { pod.run(token).await });++ // The seed convergence serves the partition and runs the first+ // verification on its way.+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {+ let verified = Arc::clone(&verified);+ async move { verified.load(Ordering::SeqCst) >= 1 }+ })+ .await;+ let baseline = verified.load(Ordering::SeqCst);++ nudge.notify_one();++ wait_for_condition_named(+ WAIT_TIMEOUT,+ POLL_INTERVAL,+ "repair nudge drives a convergence",+ || {+ let verified = Arc::clone(&verified);+ async move { verified.load(Ordering::SeqCst) > baseline }+ },+ )+ .await;++ // A second nudge inside the cooldown must not run another pass: the+ // condemn-heal-condemn flap would otherwise drive passes at broker+ // speed, resetting the budgets that exist to catch it. The cooldown+ // is the reconcile interval, parked at a day here, so nothing but+ // the suppression can be holding the counter still.+ let after_first = verified.load(Ordering::SeqCst);+ nudge.notify_one();+ tokio::time::sleep(Duration::from_millis(1_500)).await;+ assert_eq!(+ verified.load(Ordering::SeqCst),+ after_first,+ "a nudge inside the cooldown must fall to the reconcile tick"+ );++ cancel.cancel();+}diff --git a/rust/personhog-leader/src/fencing.rs b/rust/personhog-leader/src/fencing.rsindex 07bc963dc716..2d66f29c4a2d 100644--- a/rust/personhog-leader/src/fencing.rs+++ b/rust/personhog-leader/src/fencing.rs@@ -166,6 +166,9 @@ struct PartitionFence {/// epoch once the pod's claim is confirmed.unusable: AtomicBool,commit_timeout: Duration,+ /// Clone of the map's repair nudge; a condemnation must be able to+ /// announce itself from wherever the commit task discovers it.+ repair_nudge: Option<Arc<Notify>>,}impl PartitionFence {@@ -182,6 +185,15 @@ impl PartitionFence {partition,reason, "changelog producer left unusable; awaiting re-acquisition");+ // The only way back is a heal on a convergence to Serving, and+ // the reconcile tick that would otherwise carry it is seconds+ // away — writes bounce for that whole gap. The nudge lets the+ // coordination loop run its repair pass now; Notify stores+ // the permit, so a nudge landing before the loop listens is+ // not lost.+ if let Some(nudge) = &self.repair_nudge {+ nudge.notify_one();+ }}}@@ -416,6 +428,11 @@ pub struct FencedChangelogProducers {/// and report a failed drain.settle_budget: Duration,partitions: DashMap<u32, Arc<PartitionFence>>,+ /// Nudged on condemnation, so the coordination loop can run a+ /// repair pass now instead of on its next reconcile tick. Carries no+ /// payload: the pass re-derives what needs converging, the same way+ /// the tick does. `None` leaves repair to the tick alone.+ repair_nudge: Option<Arc<Notify>>,/// Outcomes a test stages for the next produce on a partition.////// The uncertain outcomes need a broker fault landing inside a@@ -461,11 +478,21 @@ impl FencedChangelogProducers {window,settle_budget,partitions: DashMap::new(),+ repair_nudge: None,#[cfg(any(test, feature = "test-support"))]staged_failures: DashMap::new(),}}+ /// Announce condemnations on `nudge`, so the coordination loop can+ /// run a repair pass immediately instead of on its next reconcile+ /// tick. The listening end is [`PodHandle::+ /// with_repair_nudge`](personhog_coordination::pod::PodHandle).+ pub fn with_repair_nudge(mut self, nudge: Arc<Notify>) -> Self {+ self.repair_nudge = Some(nudge);+ self+ }+/// Take the partition's fence: create the transactional producer and/// initialize transactions, which fences every previous owner of the/// partition's transactional id. Runs on the blocking pool — init is@@ -502,8 +529,16 @@ impl FencedChangelogProducers {panic_next_commit: AtomicBool::new(false),unusable: AtomicBool::new(false),commit_timeout: self.commit_timeout,+ repair_nudge: self.repair_nudge.clone(),});- self.partitions.insert(partition, Arc::clone(&installed));+ if let Some(replaced) = self.partitions.insert(partition, Arc::clone(&installed)) {+ // The heal path installs over a still-present condemned+ // fence, and by then the commit task has usually dropped its+ // clones — making this insert the last reference and its+ // drop a blocking librdkafka destroy. Send it to the+ // blocking pool like every other eviction site.+ drop_fence_off_worker(replaced);+ }Ok(installed)}@@ -1014,16 +1049,42 @@ enum WindowVerdict {/// record at the same number behind one that may be committed. Reporting/// it as merely indeterminate throws away the ownership answer the router/// bounces on. `FencedUncertain` is both.+/// Every reason production code passes to `condemn`, in one place so the+/// preregistration below cannot drift from the call sites: a reason+/// missing here first appears as a brand-new series mid-incident instead+/// of rising from zero.+const CONDEMN_REASONS: [&str; 6] = [+ "abort_fenced",+ "abort_failed",+ "commit_fenced",+ "commit_indeterminate",+ "commit_task_lost",+ "committer_unwound",+];+/// Why a window's outcome leaves the producer unusable, if it does.////// Extracted so the arrow *into* the condemned state is reachable: the/// tests could reach the aftermath through a staging hook, but the branch/// that decides it could be deleted outright with the suite still green,/// and it is the only path in production that ever sets the flag.-fn condemn_reason(outcome: CommitOutcome) -> Option<&'static str> {+///+/// A dead producer carries two very different stories, split by+/// `fenced`: a producer fenced by a newer owner's init lost the epoch (a+/// handoff, a heal, a zombie being cut off — coordination working), while+/// an abort that failed on a producer nobody fenced means the broker+/// could not be reached in time (an infrastructure excursion). The panel+/// reading this label has to tell those apart without the logs.+fn condemn_reason(outcome: CommitOutcome, fenced: bool) -> Option<&'static str> {match outcome {CommitOutcome::Aborted => None,+ CommitOutcome::AbortedProducerDead if fenced => Some("abort_fenced"),CommitOutcome::AbortedProducerDead => Some("abort_failed"),+ // A commit killed by a newer owner's init reports librdkafka's+ // fatal class and lands here, not in AbortedProducerDead — the+ // fenced split must cover this arm or every deploy-shaped+ // condemnation reads as a broker excursion.+ CommitOutcome::Unknown if fenced => Some("commit_fenced"),CommitOutcome::Unknown => Some("commit_indeterminate"),}}@@ -1213,10 +1274,10 @@ async fn commit_window_after(Ok(Err((e, outcome))) => {histogram!("personhog_leader_fence_commit_ms", "outcome" => "failed").record(commit_start.elapsed().as_secs_f64() * 1000.0);- if let Some(reason) = condemn_reason(outcome) {+ let fenced_now = is_fenced(&e) || producer_fenced(fence.producer.inner());+ if let Some(reason) = condemn_reason(outcome, fenced_now) {fence.condemn(partition, reason);}- let fenced_now = is_fenced(&e) || producer_fenced(fence.producer.inner());let verdict = window_verdict(outcome, fenced_now);if verdict == WindowVerdict::FencedUncertain {counter!(@@ -1320,10 +1381,16 @@ pub fn preregister_fencing_metrics(partitions: u32) {// can swallow the first burst between scrapes.counter!("personhog_leader_fence_healed_total").increment(0);counter!("personhog_leader_fence_heal_abandoned_total").increment(0);- for reason in ["abort_failed", "commit_indeterminate", "commit_task_lost"] {+ for reason in CONDEMN_REASONS {counter!("personhog_leader_fence_condemned_total", "reason" => reason).increment(0);}counter!("personhog_leader_fence_commit_retries_total").increment(0);+ // The coordination loop's repair-pass counter fires exclusively+ // mid-incident, exactly when a first-increment series would be+ // swallowed between scrapes.+ for outcome in ["run", "suppressed"] {+ counter!("personhog_coordination_repair_passes_total", "outcome" => outcome).increment(0);+ }counter!("personhog_leader_kafka_produce_errors_total").increment(0);for partition in 0..partitions {let p = partition.to_string();@@ -1338,6 +1405,7 @@ pub fn preregister_fencing_metrics(partitions: u32) {"partition" => p.clone()).increment(0);+counter!("personhog_leader_fence_commit_indeterminate_total","partition" => p.clone()@@ -1484,15 +1552,55 @@ mod tests {/// that cannot serve one, for the life of the process.#[test]fn a_producer_that_cannot_begin_another_window_is_condemned() {- assert_eq!(condemn_reason(CommitOutcome::Aborted), None);+ for fenced in [false, true] {+ assert_eq!(condemn_reason(CommitOutcome::Aborted, fenced), None);+ }assert_eq!(- condemn_reason(CommitOutcome::AbortedProducerDead),- Some("abort_failed")+ condemn_reason(CommitOutcome::Unknown, true),+ Some("commit_fenced"));assert_eq!(- condemn_reason(CommitOutcome::Unknown),+ condemn_reason(CommitOutcome::Unknown, false),Some("commit_indeterminate"));+ // The same dead producer, split by what killed it: an epoch lost+ // to a newer owner is coordination working, an abort nobody+ // fenced failing is the broker unreachable — the operator's first+ // question, answered from the series alone.+ assert_eq!(+ condemn_reason(CommitOutcome::AbortedProducerDead, true),+ Some("abort_fenced")+ );+ assert_eq!(+ condemn_reason(CommitOutcome::AbortedProducerDead, false),+ Some("abort_failed")+ );+ }++ /// A condemn reason absent from the preregistration list first+ /// appears as a new series mid-incident instead of rising from zero.+ #[test]+ fn every_condemn_reason_is_preregistered() {+ for outcome in [+ CommitOutcome::Aborted,+ CommitOutcome::AbortedProducerDead,+ CommitOutcome::Unknown,+ ] {+ for fenced in [false, true] {+ if let Some(reason) = condemn_reason(outcome, fenced) {+ assert!(+ CONDEMN_REASONS.contains(&reason),+ "condemn_reason produced {reason:?}, missing from CONDEMN_REASONS"+ );+ }+ }+ }+ for direct in ["commit_task_lost", "committer_unwound"] {+ assert!(+ CONDEMN_REASONS.contains(&direct),+ "direct condemn call site uses {direct:?}, missing from CONDEMN_REASONS"+ );+ }}#[test]diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rsindex 135a865ed961..acbf5bab8caa 100644--- a/rust/personhog-leader/src/main.rs+++ b/rust/personhog-leader/src/main.rs@@ -17,6 +17,7 @@ use personhog_coordination::authority::AuthorityClock;use personhog_coordination::pod::{PodConfig, PodHandle};use personhog_coordination::store::PersonhogStore;use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeaderServer;+use tokio::sync::Notify;use tokio::time::timeout;use tokio_util::sync::CancellationToken;use tonic::codec::CompressionEncoding;@@ -322,6 +323,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {config.ingestion_warnings_topic.clone(),);let fence_scan_pool = fallback.as_ref().map(|f| f.pool.clone());+ let mut fence_repair_nudge: Option<Arc<Notify>> = None;let fenced = if config.kafka_transactional_fencing {// Every one of these is derived from LEASE_TTL rather than set// directly, so an operator debugging a fenced-write timeout has@@ -336,6 +338,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {"broker-enforced epoch fencing enabled for the changelog");preregister_fencing_metrics(num_partitions);+ // A condemned producer's repair otherwise waits for the next+ // reconcile tick; this nudge lets the condemnation itself+ // trigger the repair pass that heals it.+ let repair_nudge = Arc::new(Notify::new());+ fence_repair_nudge = Some(Arc::clone(&repair_nudge));// The fenced producer runs on a tighter message timeout than the// shared one: its writes must resolve inside the lease runway.let fencing_kafka = common_kafka::config::KafkaConfig {@@ -347,8 +354,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {kafka_producer_queue_messages: config.fencing_queue_messages(num_partitions),..config.kafka.clone()};- Some(Arc::new(FencedChangelogProducers::new(- FencedProducerConfig {+ Some(Arc::new(+ FencedChangelogProducers::new(FencedProducerConfig {kafka: fencing_kafka,topic: config.kafka_person_state_topic.clone(),init_timeout: config.fencing_init_timeout(),@@ -356,8 +363,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {broker_txn_timeout: config.fencing_broker_txn_timeout(),window: Duration::from_millis(config.fencing_window_ms),settle_budget: config.fencing_settle_budget(),- },- )))+ })+ .with_repair_nudge(repair_nudge),+ ))} else {None};@@ -564,13 +572,16 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {}}- let pod = PodHandle::new(+ let mut pod = PodHandle::new(store,pod_config,Arc::new(handler),k8s_awareness,Arc::clone(&authority),);+ if let Some(nudge) = fence_repair_nudge.take() {+ pod = pod.with_repair_nudge(nudge);+ }tokio::spawn(async move {let _guard = coordination_handle.process_scope();diff --git a/rust/personhog-leader/tests/fencing_integration.rs b/rust/personhog-leader/tests/fencing_integration.rsindex 6bfa63ad5bbb..5a7709e1e0e7 100644--- a/rust/personhog-leader/tests/fencing_integration.rs+++ b/rust/personhog-leader/tests/fencing_integration.rs@@ -18,6 +18,7 @@ use personhog_leader::fencing::{};use personhog_leader::inflight::InflightTracker;use personhog_proto::personhog::types::v1::Person;+use tokio::sync::Notify;use tokio::time::sleep;use common::{test_kafka_config, KAFKA_BOOTSTRAP};@@ -374,6 +375,34 @@ async fn a_completed_warm_keeps_its_fence() {.expect("a completed warm keeps a usable fence");}+/// A condemnation must nudge its own repair: the fix for a condemned+/// producer is a convergence-driven heal, and without the nudge that+/// convergence waits for the next reconcile tick while every write on+/// the partition bounces. Once per producer: the unusable swap, not the+/// notify, bounds the nudges.+#[tokio::test]+async fn a_condemnation_nudges_repair_once() {+ let topic = format!("fence_repair_{}", uuid::Uuid::new_v4().simple());+ let nudge = Arc::new(Notify::new());+ let producers = fenced_producers(&topic).with_repair_nudge(Arc::clone(&nudge));+ producers.acquire(3).await.expect("acquire the fence");++ producers.condemn_for_test(3);+ tokio::time::timeout(Duration::from_secs(5), nudge.notified())+ .await+ .expect("a condemnation must nudge the repair pass");++ // The permit was consumed above; a second condemnation of the same+ // producer takes the unusable-swap early exit and stores no new one.+ producers.condemn_for_test(3);+ assert!(+ tokio::time::timeout(Duration::from_millis(250), nudge.notified())+ .await+ .is_err(),+ "a second condemnation of the same producer must not nudge again"+ );+}+/// A producer whose abort exhausted its retries, or whose commit outcome/// stayed unknown, is left in a transaction state it cannot begin another/// window from. It is still installed, so nothing that checks for the