:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(personhog): measure handoff time per phase and person-lock waits (#74069)
Zach Brown9cfa0042bbba
diff --git a/rust/common/assignment-coordination/src/util.rs b/rust/common/assignment-coordination/src/util.rsindex c8c6332491e8..d0287fe80d01 100644--- a/rust/common/assignment-coordination/src/util.rs+++ b/rust/common/assignment-coordination/src/util.rs@@ -32,6 +32,13 @@ pub fn now_seconds() -> i64 {.as_secs() as i64}+pub fn now_millis() -> i64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_millis() as i64+}+/// Compare current and desired assignments to find partitions that need to move.////// Returns `(partition, old_owner, new_owner)` for each partition whose ownerdiff --git a/rust/personhog-coordination/src/coordinator.rs b/rust/personhog-coordination/src/coordinator.rsindex e7455f441e62..89ef3849d0c8 100644--- a/rust/personhog-coordination/src/coordinator.rs+++ b/rust/personhog-coordination/src/coordinator.rs@@ -731,6 +731,7 @@ impl Coordinator {.collect();let now = util::now_seconds();+ let now_ms = util::now_millis();let handoff_objects: Vec<HandoffState> = plan.handoffs.iter()@@ -746,6 +747,8 @@ impl Coordinator {started_at: now,handoff_id: util::new_handoff_id(),freeze_quorum: Some(freeze_quorum.clone()),+ created_at_ms: now_ms,+ phase_entered_at_ms: now_ms,}).collect();@@ -1011,30 +1014,97 @@ fn phase_label(phase: HandoffPhase) -> &'static str {/// the pod side's warm and drain histograms carry the precise/// per-operation cost.fn record_phase_advance(handoff: &HandoffState, to: HandoffPhase) {+ // Moves drain and warm; fresh assignments only warm — two different+ // duration distributions, split rather than muddled.+ let kind = if handoff.old_owner.is_some() {+ "move"+ } else {+ "fresh"+ };counter!("personhog_coordination_handoff_transitions_total","from" => phase_label(handoff.phase),"to" => phase_label(to),).increment(1);- let elapsed = util::now_seconds().saturating_sub(handoff.started_at);- histogram!(- "personhog_coordination_handoff_phase_reached_ms",- "phase" => phase_label(to),- )- .record((elapsed * 1000) as f64);+ let now_ms = util::now_millis();+ // Cumulative creation→phase, millisecond-precise when the record+ // carries `created_at_ms`; pre-upgrade records fall back to the+ // second-resolution `started_at`.+ // Clamped at zero: a phase stamped by one coordinator can be+ // observed by its successor, and millisecond resolution makes even+ // small clock skew visible — a negative observation would distort+ // the histogram, incrementing every bucket.+ let reached_ms = if handoff.created_at_ms > 0 {+ Some(now_ms.saturating_sub(handoff.created_at_ms).max(0))+ } else if handoff.started_at > 0 {+ Some(util::now_seconds().saturating_sub(handoff.started_at) * 1000)+ } else {+ None+ };+ if let Some(reached_ms) = reached_ms {+ histogram!(+ "personhog_coordination_handoff_phase_reached_ms",+ "phase" => phase_label(to),+ "kind" => kind,+ )+ .record(reached_ms as f64);+ }+ // Time spent in the phase being exited. Phases are sequential and+ // non-overlapping, so these are additive components of the total —+ // the handoff waterfall. Zero means a pre-upgrade record with no+ // phase clock; recording an epoch-sized value would be worse than+ // recording nothing.+ if handoff.phase_entered_at_ms > 0 {+ histogram!(+ "personhog_coordination_handoff_phase_duration_ms",+ "phase" => phase_label(handoff.phase),+ "kind" => kind,+ )+ .record(now_ms.saturating_sub(handoff.phase_entered_at_ms).max(0) as f64);+ }}/// Refresh the coordinator's view-of-the-cluster gauges. Driven from the/// reconcile tick, so only the elected coordinator exports live values;/// `reset_coordinator_gauges` zeroes them when leadership ends.fn record_cluster_gauges(handoffs: &[HandoffState], pods: &[RegisteredPod], routers: usize) {+ let now_ms = util::now_millis();+ let now_s = util::now_seconds();for phase in [HandoffPhase::Freezing,HandoffPhase::Draining,HandoffPhase::Warming,HandoffPhase::Complete,] {+ // Oldest time-in-current-phase: the stuck-handoff signal,+ // phase-localized. `phase_reached`/`phase_duration` sample only+ // handoffs that advance, so a wedged one is invisible there —+ // this gauge is its complement, and the one to alert on (age+ // approaching the cancellation deadline means a participant is+ // not acking). Falls back to total age for pre-upgrade records;+ // zero when the phase is empty, which also resets it when+ // leadership ends.+ let max_age_secs = handoffs+ .iter()+ .filter(|h| h.phase == phase)+ .map(|h| {+ if h.phase_entered_at_ms > 0 {+ now_ms.saturating_sub(h.phase_entered_at_ms) / 1000+ } else if h.started_at > 0 {+ now_s.saturating_sub(h.started_at)+ } else {+ 0+ }+ })+ .max()+ .unwrap_or(0)+ .max(0);+ gauge!(+ "personhog_coordination_handoff_phase_age_seconds",+ "phase" => phase_label(phase),+ )+ .set(max_age_secs as f64);let count = handoffs.iter().filter(|h| h.phase == phase).count();gauge!("personhog_coordination_handoffs_in_flight", "phase" => phase_label(phase)).set(count as f64);diff --git a/rust/personhog-coordination/src/pod.rs b/rust/personhog-coordination/src/pod.rsindex 69b5d37d2716..b0810f95036d 100644--- a/rust/personhog-coordination/src/pod.rs+++ b/rust/personhog-coordination/src/pod.rs@@ -652,6 +652,8 @@ mod tests {started_at: 0,handoff_id: "h-test".to_string(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,}}diff --git a/rust/personhog-coordination/src/protocol.rs b/rust/personhog-coordination/src/protocol.rsindex 1ab669c1f8c5..463c311ea302 100644--- a/rust/personhog-coordination/src/protocol.rs+++ b/rust/personhog-coordination/src/protocol.rs@@ -219,6 +219,8 @@ mod tests {started_at: 0,handoff_id: String::new(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,}}diff --git a/rust/personhog-coordination/src/store.rs b/rust/personhog-coordination/src/store.rsindex baab0d6a2ea5..f4127da4f313 100644--- a/rust/personhog-coordination/src/store.rs+++ b/rust/personhog-coordination/src/store.rs@@ -269,6 +269,9 @@ impl PersonhogStore {return Ok(false);}handoff.phase = new_phase;+ // The phase clock restarts with the phase: duration metrics and+ // the per-phase age gauge read this stamp.+ handoff.phase_entered_at_ms = assignment_coordination::util::now_millis();let txn = Txn::new().when(vec![Compare::mod_revision(handoff_key.clone(),@@ -529,6 +532,7 @@ impl PersonhogStore {.ok_or_else(|| Error::NotFound(format!("handoff for partition {partition}")))?;handoff.phase = crate::types::HandoffPhase::Complete;+ handoff.phase_entered_at_ms = assignment_coordination::util::now_millis();let assignment = PartitionAssignment {partition,diff --git a/rust/personhog-coordination/src/types.rs b/rust/personhog-coordination/src/types.rsindex be10e591cbcb..7e921ef9e428 100644--- a/rust/personhog-coordination/src/types.rs+++ b/rust/personhog-coordination/src/types.rs@@ -143,6 +143,23 @@ pub struct HandoffState {/// requires nobody.#[serde(default, skip_serializing_if = "Option::is_none")]pub freeze_quorum: Option<Vec<String>>,+ /// Millisecond creation time. `started_at` (seconds) predates it and+ /// stays authoritative for the cancellation deadline — changing that+ /// field's units mid-roll would make old records' ages read as+ /// garbage — while this feeds the latency metrics, whose healthy+ /// values are sub-second and invisible at second resolution. Zero+ /// means the record predates the field; consumers skip rather than+ /// treat it as an epoch-zero time.+ #[serde(default)]+ pub created_at_ms: i64,+ /// When the handoff entered its current phase, stamped at creation+ /// and refreshed by the coordinator's CAS on every advance. Time+ /// spent per phase is measured from it directly — per-phase+ /// durations cannot be recovered from cumulative reached-times+ /// (differences of quantiles are not quantiles of differences).+ /// Zero means the record predates the field.+ #[serde(default)]+ pub phase_entered_at_ms: i64,}/// State machine for partition handoffs:@@ -245,6 +262,27 @@ pub struct LeaderInfo {mod tests {use super::*;+ /// A record written before the snapshot and millisecond-timestamp+ /// fields existed must deserialize with the safe defaults: `None`+ /// quorum (fall back to all live routers) and zero clocks (metrics+ /// and the age gauge skip rather than measure from the epoch).+ /// Catches anyone removing a `serde(default)` during a refactor.+ #[test]+ fn pre_upgrade_handoff_record_deserializes_with_safe_defaults() {+ let legacy = r#"{+ "partition": 3,+ "old_owner": "p-old",+ "new_owner": "p-new",+ "phase": "Freezing",+ "started_at": 1700000000+ }"#;+ let h: HandoffState = serde_json::from_str(legacy).unwrap();+ assert_eq!(h.handoff_id, "");+ assert!(h.freeze_quorum.is_none());+ assert_eq!(h.created_at_ms, 0);+ assert_eq!(h.phase_entered_at_ms, 0);+ }+#[test]fn registered_pod_roundtrip() {let pod = RegisteredPod {@@ -312,6 +350,8 @@ mod tests {started_at: 1700000000,handoff_id: "1700000000000-0".to_string(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,};let json = serde_json::to_string(&handoff).unwrap();@@ -329,6 +369,8 @@ mod tests {started_at: 1700000000,handoff_id: "1700000000000-0".to_string(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,};let json = serde_json::to_string(&handoff).unwrap();diff --git a/rust/personhog-coordination/src/util.rs b/rust/personhog-coordination/src/util.rsindex bcd93319a51b..4ecd3bb5f903 100644--- a/rust/personhog-coordination/src/util.rs+++ b/rust/personhog-coordination/src/util.rs@@ -4,7 +4,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH};use tokio_util::sync::CancellationToken;use uuid::Uuid;-pub use assignment_coordination::util::now_seconds;+pub use assignment_coordination::util::{now_millis, now_seconds};use crate::error::{Error, Result};use crate::store::PersonhogStore;diff --git a/rust/personhog-coordination/tests/integration.rs b/rust/personhog-coordination/tests/integration.rsindex cf8dccb64978..2e96ffd2ee0e 100644--- a/rust/personhog-coordination/tests/integration.rs+++ b/rust/personhog-coordination/tests/integration.rs@@ -1418,6 +1418,8 @@ async fn handoff_delete_drains_stash_to_current_owner() {started_at: 0,handoff_id: String::new(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,};store.put_handoff(&stuck_handoff).await.unwrap();@@ -1544,6 +1546,8 @@ async fn stale_handoff_address_never_overwrites_a_fresher_registration() {started_at: 0,handoff_id: "h-stale-addr".to_string(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,}).await.unwrap();@@ -1766,6 +1770,8 @@ async fn late_joining_router_during_warming_begins_stash() {started_at: 0,handoff_id: String::new(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,};store.put_handoff(&warming_handoff).await.unwrap();@@ -1831,6 +1837,8 @@ async fn dead_old_owner_in_freezing_advances_to_completion() {started_at: 0,handoff_id: String::new(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,};store.put_handoff(&stale).await.unwrap();@@ -1884,6 +1892,8 @@ async fn late_joining_router_during_freezing_acks_and_stashes() {started_at: 0,handoff_id: String::new(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,};store.put_handoff(&freezing_handoff).await.unwrap();@@ -1964,6 +1974,8 @@ async fn handoff_delete_during_warming_drains_to_current_owner() {started_at: 0,handoff_id: String::new(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,};store.put_handoff(&stuck).await.unwrap();@@ -2063,6 +2075,8 @@ async fn reconcile_advances_warming_with_pre_staged_warmed_ack() {started_at: 0,handoff_id: String::new(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,};store.put_handoff(&warming).await.unwrap();@@ -2143,6 +2157,8 @@ async fn draining_old_owner_blocks_phase_advance() {started_at: 0,handoff_id: String::new(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,};store.put_handoff(&handoff).await.unwrap();@@ -2245,6 +2261,8 @@ async fn draining_old_owner_does_not_trigger_cleanup() {started_at: 0,handoff_id: String::new(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,};store.put_handoff(&handoff).await.unwrap();@@ -2353,6 +2371,8 @@ async fn a_handoff_that_can_never_reach_quorum_is_cancelled() {.as_secs() as i64,handoff_id: "wedged-handoff".to_string(),freeze_quorum: Some(vec!["silent-router".to_string()]),+ created_at_ms: 0,+ phase_entered_at_ms: 0,}).await.unwrap();@@ -2436,6 +2456,8 @@ async fn freezing_blocks_until_routers_ack_before_draining() {started_at: 0,handoff_id: String::new(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,};store.put_handoff(&handoff).await.unwrap();@@ -2477,6 +2499,15 @@ async fn freezing_blocks_until_routers_ack_before_draining() {}).await;+ // The advance restarts the phase clock: the injected record carried+ // no stamp, so a nonzero value proves the CAS wrote one — what the+ // phase-duration metrics and the per-phase age gauge depend on.+ let advanced = store.get_handoff(1).await.unwrap().unwrap();+ assert!(+ advanced.phase_entered_at_ms > 0,+ "phase advance must stamp phase_entered_at_ms"+ );+cancel.cancel();}@@ -2524,6 +2555,8 @@ async fn initial_assignment_skips_draining_phase() {started_at: 0,handoff_id: String::new(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,};store.put_handoff(&handoff).await.unwrap();@@ -2584,6 +2617,8 @@ async fn dead_old_owner_in_draining_recovers() {started_at: 0,handoff_id: String::new(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,};store.put_handoff(&handoff).await.unwrap();@@ -2684,6 +2719,8 @@ async fn reconcile_advances_draining_with_pre_staged_drained_ack() {started_at: 0,handoff_id: String::new(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,};store.put_handoff(&handoff).await.unwrap();@@ -2744,6 +2781,8 @@ async fn late_joining_router_during_draining_begins_stash_no_ack() {started_at: 0,handoff_id: String::new(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,};store.put_handoff(&draining_handoff).await.unwrap();@@ -2829,6 +2868,8 @@ async fn handoff_delete_during_draining_drains_to_current_owner() {started_at: 0,handoff_id: String::new(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,};store.put_handoff(&stuck).await.unwrap();@@ -3076,6 +3117,8 @@ async fn conflicting_plan_cannot_replace_an_in_flight_handoff() {started_at: 0,handoff_id: "first".to_string(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,};assert!(store@@ -3093,6 +3136,8 @@ async fn conflicting_plan_cannot_replace_an_in_flight_handoff() {started_at: 0,handoff_id: "second".to_string(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,};let stable = PartitionAssignment {@@ -3142,6 +3187,8 @@ async fn stale_plan_is_rejected_when_the_assignment_moved() {started_at: 0,handoff_id: id.to_string(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,};@@ -3220,6 +3267,8 @@ async fn fresh_plan_is_rejected_when_an_assignment_appeared() {started_at: 0,handoff_id: id.to_string(),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,};diff --git a/rust/personhog-coordination/tests/protocol_hardening.rs b/rust/personhog-coordination/tests/protocol_hardening.rsindex 679a6bf108ab..f5cecd50005c 100644--- a/rust/personhog-coordination/tests/protocol_hardening.rs+++ b/rust/personhog-coordination/tests/protocol_hardening.rs@@ -49,6 +49,8 @@ async fn put_handoff(started_at: 0,handoff_id: format!("test-handoff-{partition}"),freeze_quorum: None,+ created_at_ms: 0,+ phase_entered_at_ms: 0,new_owner_address: None,};// Raw put on purpose: fixtures force arbitrary handoff states,diff --git a/rust/personhog-leader/src/service.rs b/rust/personhog-leader/src/service.rsindex 2fceaa100877..7b131aa80b66 100644--- a/rust/personhog-leader/src/service.rs+++ b/rust/personhog-leader/src/service.rs@@ -502,14 +502,22 @@ impl PersonHogLeader for PersonHogLeaderService {.map(|k| k.replace('\u{0000}', "\u{FFFD}")).collect();- // Per-key lock serializes concurrent updates for the same person+ // Per-key lock serializes concurrent updates for the same person.+ // The wait is measured because it is the queueing component of+ // handler latency: with every acked write holding the lock+ // through its acks=all produce, per-person throughput is capped+ // near 1/produce-latency, and contending updates spend their+ // time here — invisible in the produce histogram.let mutex = self.locks.entry(cache_key.clone()).or_default().value().clone();+ let lock_wait = std::time::Instant::now();let _guard = mutex.lock().await;+ histogram!("personhog_leader_person_lock_wait_ms")+ .record(lock_wait.elapsed().as_secs_f64() * 1000.0);// Admission check before any work: if the dirty index is at// capacity and this person is not already marked, acking the writediff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rsindex 810fd90c86bf..1a36abcc3be6 100644--- a/rust/personhog-router/src/main.rs+++ b/rust/personhog-router/src/main.rs@@ -201,14 +201,26 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {.unwrap()// Handoff phase timings are a stall detector: healthy phases// complete in seconds, and the interesting tail is minutes.- // The default buckets cap at 10s, which would collapse every- // stall into +Inf.+ // Sub-second buckets at the bottom because the source is+ // millisecond-precise; the top still reaches far past the+ // handoff deadline so a stall is never collapsed into +Inf..set_buckets_for_metric(metrics_exporter_prometheus::Matcher::Full("personhog_coordination_handoff_phase_reached_ms".into(),),&[- 1000.0, 2000.0, 5000.0, 10000.0, 30000.0, 60000.0, 120000.0, 300000.0, 600000.0,+ 50.0, 250.0, 1000.0, 2000.0, 5000.0, 10000.0, 30000.0, 60000.0, 120000.0,+ 300000.0, 600000.0,+ ],+ )+ .unwrap()+ .set_buckets_for_metric(+ metrics_exporter_prometheus::Matcher::Full(+ "personhog_coordination_handoff_phase_duration_ms".into(),+ ),+ &[+ 50.0, 250.0, 1000.0, 2000.0, 5000.0, 10000.0, 30000.0, 60000.0, 120000.0,+ 300000.0, 600000.0,],).unwrap()diff --git a/rust/personhog-stateright/src/model.rs b/rust/personhog-stateright/src/model.rsindex 4c98509d8f78..c8b2e83f2932 100644--- a/rust/personhog-stateright/src/model.rs+++ b/rust/personhog-stateright/src/model.rs@@ -56,6 +56,8 @@ fn production_handoff(p: Partition, h: &Handoff) -> HandoffState {// the live registry, and the production quorum predicate below// is exercised on exactly that divergence.freeze_quorum: Some(h.quorum.iter().map(|r| router_name(*r)).collect()),+ created_at_ms: 0,+ phase_entered_at_ms: 0,}}