Skip to content

: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.

feat(personhog): warm-phase latency levers and handoff span metrics (#76034)

Zach Browna87ead8e0c85
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 60c47c794d1f..bd7c8b13ea14 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -506,6 +506,7 @@ name = "assignment-coordination"
version = "0.1.0"
dependencies = [
"etcd-client",
+ "metrics",
"serde",
"serde_json",
"thiserror 2.0.18",
diff --git a/rust/common/assignment-coordination/Cargo.toml b/rust/common/assignment-coordination/Cargo.toml
index bf14f0b8159b..e3a5aa8e0930 100644
--- a/rust/common/assignment-coordination/Cargo.toml
+++ b/rust/common/assignment-coordination/Cargo.toml
@@ -6,6 +6,7 @@ publish = false
[dependencies]
etcd-client = "0.18"
+metrics = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
diff --git a/rust/common/assignment-coordination/src/store.rs b/rust/common/assignment-coordination/src/store.rs
index 6956524c0630..1188c256e044 100644
--- a/rust/common/assignment-coordination/src/store.rs
+++ b/rust/common/assignment-coordination/src/store.rs
@@ -29,6 +29,30 @@ pub struct EtcdStore {
config: StoreConfig,
}
+/// Records one etcd operation's wall time on drop, so every return path
+/// (including errors) lands in the histogram. Includes this layer's
+/// (de)serialization, which is negligible next to the etcd round trip.
+struct OpTimer {
+ op: &'static str,
+ start: std::time::Instant,
+}
+
+impl OpTimer {
+ fn new(op: &'static str) -> Self {
+ Self {
+ op,
+ start: std::time::Instant::now(),
+ }
+ }
+}
+
+impl Drop for OpTimer {
+ fn drop(&mut self) {
+ metrics::histogram!("assignment_coordination_etcd_op_ms", "op" => self.op)
+ .record(self.start.elapsed().as_secs_f64() * 1000.0);
+ }
+}
+
impl EtcdStore {
pub async fn connect(config: StoreConfig) -> Result<Self> {
// Transport-level liveness so a silent network partition fails
@@ -71,11 +95,13 @@ impl EtcdStore {
// ── Raw (non-JSON) helpers ────────────────────────────────────
pub async fn get_raw(&self, key: &str) -> Result<Option<Vec<u8>>> {
+ let _t = OpTimer::new("get_raw");
let resp = self.client.clone().get(key, None).await?;
Ok(resp.kvs().first().map(|kv| kv.value().to_vec()))
}
pub async fn put_raw(&self, key: &str, value: impl Into<Vec<u8>>) -> Result<()> {
+ let _t = OpTimer::new("put_raw");
self.client.clone().put(key, value, None).await?;
Ok(())
}
@@ -83,6 +109,7 @@ impl EtcdStore {
// ── JSON helpers ─────────────────────────────────────────────
pub async fn get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
+ let _t = OpTimer::new("get");
let resp = self.client.clone().get(key, None).await?;
match resp.kvs().first() {
Some(kv) => Ok(Some(serde_json::from_slice(kv.value())?)),
@@ -91,6 +118,7 @@ impl EtcdStore {
}
pub async fn get_versioned<T: DeserializeOwned>(&self, key: &str) -> Result<Option<(T, i64)>> {
+ let _t = OpTimer::new("get_versioned");
let resp = self.client.clone().get(key, None).await?;
match resp.kvs().first() {
Some(kv) => {
@@ -111,6 +139,7 @@ impl EtcdStore {
&self,
key: &str,
) -> Result<Option<(T, i64)>> {
+ let _t = OpTimer::new("get_with_mod_revision");
let resp = self.client.clone().get(key, None).await?;
match resp.kvs().first() {
Some(kv) => {
@@ -134,6 +163,7 @@ impl EtcdStore {
&self,
prefix: &str,
) -> Result<(Vec<T>, i64)> {
+ let _t = OpTimer::new("list_with_revision");
let options = GetOptions::new().with_prefix();
let resp = self.client.clone().get(prefix, Some(options)).await?;
let revision = resp.header().map(|h| h.revision()).unwrap_or(0);
@@ -152,6 +182,7 @@ impl EtcdStore {
&self,
prefix: &str,
) -> Result<Vec<(T, i64)>> {
+ let _t = OpTimer::new("list_with_mod_revisions");
let options = GetOptions::new().with_prefix();
let resp = self.client.clone().get(prefix, Some(options)).await?;
resp.kvs()
@@ -163,6 +194,7 @@ impl EtcdStore {
/// The current etcd store revision, for anchoring watches when no
/// snapshot read is involved.
pub async fn current_revision(&self) -> Result<i64> {
+ let _t = OpTimer::new("current_revision");
let options = GetOptions::new().with_prefix().with_count_only();
let resp = self
.client
@@ -178,6 +210,7 @@ impl EtcdStore {
value: &T,
lease_id: Option<i64>,
) -> Result<()> {
+ let _t = OpTimer::new("put");
let value = serde_json::to_string(value)?;
let options = lease_id.map(|id| PutOptions::new().with_lease(id));
self.client.clone().put(key, value, options).await?;
@@ -185,17 +218,20 @@ impl EtcdStore {
}
pub async fn delete(&self, key: &str) -> Result<()> {
+ let _t = OpTimer::new("delete");
self.client.clone().delete(key, None).await?;
Ok(())
}
pub async fn delete_prefix(&self, prefix: &str) -> Result<()> {
+ let _t = OpTimer::new("delete_prefix");
let options = DeleteOptions::new().with_prefix();
self.client.clone().delete(prefix, Some(options)).await?;
Ok(())
}
pub async fn watch(&self, prefix: &str) -> Result<WatchStream> {
+ let _t = OpTimer::new("watch");
let options = WatchOptions::new().with_prefix();
let stream = self.client.clone().watch(prefix, Some(options)).await?;
Ok(stream)
@@ -209,6 +245,7 @@ impl EtcdStore {
/// caller's watch loop treats that as fatal and the component restarts
/// with a fresh snapshot.
pub async fn watch_from(&self, prefix: &str, start_revision: i64) -> Result<WatchStream> {
+ let _t = OpTimer::new("watch_from");
let options = WatchOptions::new()
.with_prefix()
.with_start_revision(start_revision);
@@ -219,12 +256,14 @@ impl EtcdStore {
// ── Transactions ─────────────────────────────────────────────
pub async fn txn(&self, txn: Txn) -> Result<TxnResponse> {
+ let _t = OpTimer::new("txn");
Ok(self.client.clone().txn(txn).await?)
}
// ── Lease operations ─────────────────────────────────────────
pub async fn grant_lease(&self, ttl: i64) -> Result<i64> {
+ let _t = OpTimer::new("grant_lease");
let resp = self.client.clone().lease_grant(ttl, None).await?;
Ok(resp.id())
}
diff --git a/rust/personhog-coordination/src/coordinator.rs b/rust/personhog-coordination/src/coordinator.rs
index 8ae223a53668..745c0d3c9fce 100644
--- a/rust/personhog-coordination/src/coordinator.rs
+++ b/rust/personhog-coordination/src/coordinator.rs
@@ -122,6 +122,16 @@ pub struct Coordinator {
k8s_awareness: Option<Arc<K8sAwareness>>,
}
+/// What prompted a phase-advance evaluation. Only ack-triggered
+/// evaluations record the ack-to-advance span: a departure or tick can
+/// legitimately advance a handoff on acks that arrived long before, and
+/// that elapsed time measures the blocker, not coordinator reaction.
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum AdvanceTrigger {
+ Ack,
+ Other,
+}
+
impl Coordinator {
pub fn new(
store: Arc<PersonhogStore>,
@@ -141,6 +151,7 @@ impl Coordinator {
/// when elected, runs the coordination loop until leadership is lost
/// or cancellation is requested.
pub async fn run(&self, cancel: CancellationToken) -> Result<()> {
+ util::preregister_coordinator_metrics();
loop {
if cancel.is_cancelled() {
return Ok(());
@@ -472,7 +483,7 @@ impl Coordinator {
// Nudge advancement here so they don't
// stall waiting for an ack event that
// will never arrive.
- Self::check_phase_advance(&store, handoff.partition).await?;
+ Self::check_phase_advance(&store, handoff.partition, AdvanceTrigger::Other).await?;
}
Err(e) => {
tracing::error!(error = %e, "failed to parse handoff event");
@@ -521,7 +532,7 @@ impl Coordinator {
});
if let Some(partition) = partition {
- Self::check_phase_advance(store, partition).await?;
+ Self::check_phase_advance(store, partition, AdvanceTrigger::Ack).await?;
}
}
}
@@ -557,7 +568,7 @@ impl Coordinator {
.any(|e| e.event_type() == EventType::Delete);
if departed {
for handoff in store.list_handoffs().await? {
- Self::check_phase_advance(store, handoff.partition).await?;
+ Self::check_phase_advance(store, handoff.partition, AdvanceTrigger::Other).await?;
}
}
}
@@ -585,7 +596,7 @@ impl Coordinator {
let handoffs = store.list_handoffs().await?;
for handoff in &handoffs {
Self::handle_handoff_update_static(&store, handoff).await?;
- Self::check_phase_advance(&store, handoff.partition).await?;
+ Self::check_phase_advance(&store, handoff.partition, AdvanceTrigger::Other).await?;
}
// Advancement first, planning second: a handoff that
// can still progress gets every chance to before the
@@ -633,7 +644,11 @@ impl Coordinator {
///
/// Called whenever an ack key is observed. Safe to call spuriously: reads
/// are idempotent and transitions use CAS.
- async fn check_phase_advance(store: &PersonhogStore, partition: u32) -> Result<()> {
+ async fn check_phase_advance(
+ store: &PersonhogStore,
+ partition: u32,
+ trigger: AdvanceTrigger,
+ ) -> Result<()> {
let handoff = match store.get_handoff(partition).await? {
Some(h) => h,
None => return Ok(()),
@@ -659,6 +674,12 @@ impl Coordinator {
.await?;
if advanced {
record_phase_advance(&handoff, target);
+ if trigger == AdvanceTrigger::Ack {
+ util::record_ack_to_advance(
+ "freezing",
+ freeze_acks.iter().map(|a| a.acked_at_ms),
+ );
+ }
tracing::info!(
partition,
freeze_acks = freeze_acks.len(),
@@ -693,6 +714,12 @@ impl Coordinator {
.await?;
if advanced {
record_phase_advance(&handoff, HandoffPhase::Warming);
+ if trigger == AdvanceTrigger::Ack {
+ util::record_ack_to_advance(
+ "draining",
+ drained_acks.iter().map(|a| a.acked_at_ms),
+ );
+ }
tracing::info!(
partition,
old_owner = ?handoff.old_owner,
@@ -712,6 +739,12 @@ impl Coordinator {
match store.complete_handoff(partition).await {
Ok(true) => {
record_phase_advance(&handoff, HandoffPhase::Complete);
+ if trigger == AdvanceTrigger::Ack {
+ util::record_ack_to_advance(
+ "warming",
+ warmed.iter().map(|a| a.acked_at_ms),
+ );
+ }
}
Ok(false) => {
tracing::warn!(partition, "handoff modified concurrently, skipping");
@@ -754,7 +787,8 @@ impl Coordinator {
// watch_handoffs_loop's Put-driven path won't replay them.
Self::handle_handoff_update_static(&self.store, handoff).await?;
// Non-terminal handoffs may have their preconditions already met.
- Self::check_phase_advance(&self.store, handoff.partition).await?;
+ Self::check_phase_advance(&self.store, handoff.partition, AdvanceTrigger::Other)
+ .await?;
}
Ok(())
@@ -1057,7 +1091,7 @@ impl Coordinator {
.iter()
.chain(replacements.iter().map(|r| &r.handoff))
{
- Self::check_phase_advance(store, handoff.partition).await?;
+ Self::check_phase_advance(store, handoff.partition, AdvanceTrigger::Other).await?;
}
Ok(())
diff --git a/rust/personhog-coordination/src/lib.rs b/rust/personhog-coordination/src/lib.rs
index 91ec551f4ddf..a40ab89cbd1e 100644
--- a/rust/personhog-coordination/src/lib.rs
+++ b/rust/personhog-coordination/src/lib.rs
@@ -8,3 +8,4 @@ pub mod store;
pub mod strategy;
pub mod types;
pub(crate) mod util;
+pub use util::preregister_router_coordination_metrics;
diff --git a/rust/personhog-coordination/src/pod.rs b/rust/personhog-coordination/src/pod.rs
index ffaf1423f969..de0139a45bff 100644
--- a/rust/personhog-coordination/src/pod.rs
+++ b/rust/personhog-coordination/src/pod.rs
@@ -936,6 +936,7 @@ impl PodHandle {
pod_name: pod.clone(),
partition,
acked_at: util::now_seconds(),
+ acked_at_ms: 0,
handoff_id: handoff.handoff_id.clone(),
})
.await?;
@@ -991,6 +992,7 @@ impl PodHandle {
pod_name: pod.clone(),
partition,
acked_at: util::now_seconds(),
+ acked_at_ms: 0,
handoff_id: handoff.handoff_id.clone(),
})
.await?;
@@ -1178,7 +1180,14 @@ impl PodHandle {
for event in resp.events() {
let partition = match event.event_type() {
EventType::Put => match parse_watch_value::<HandoffState>(event) {
- Ok(handoff) => Some(handoff.partition),
+ Ok(handoff) => {
+ util::record_phase_watch_delivery(
+ "pod",
+ handoff.phase,
+ handoff.phase_entered_at_ms,
+ );
+ Some(handoff.partition)
+ }
Err(e) => {
tracing::error!(pod = %self.config.pod_name, error = %e, "failed to parse handoff");
None
diff --git a/rust/personhog-coordination/src/protocol.rs b/rust/personhog-coordination/src/protocol.rs
index e710e60417eb..b3e8c5d1b845 100644
--- a/rust/personhog-coordination/src/protocol.rs
+++ b/rust/personhog-coordination/src/protocol.rs
@@ -303,6 +303,7 @@ mod tests {
router_name: router.to_string(),
partition: handoff.partition,
acked_at: 0,
+ acked_at_ms: 0,
handoff_id: handoff.handoff_id.clone(),
}
}
diff --git a/rust/personhog-coordination/src/routing_table.rs b/rust/personhog-coordination/src/routing_table.rs
index 2e2b4577219f..1a46abe5f02c 100644
--- a/rust/personhog-coordination/src/routing_table.rs
+++ b/rust/personhog-coordination/src/routing_table.rs
@@ -689,6 +689,7 @@ impl RoutingTable {
router_name: self.config.router_name.clone(),
partition: handoff.partition,
acked_at: util::now_seconds(),
+ acked_at_ms: 0,
handoff_id: handoff.handoff_id.clone(),
};
self.store.put_freeze_ack(&ack).await?;
@@ -959,6 +960,7 @@ impl RoutingTable {
router_name: router_name.to_string(),
partition: handoff.partition,
acked_at: util::now_seconds(),
+ acked_at_ms: 0,
handoff_id: handoff.handoff_id.clone(),
};
store.put_freeze_ack(&ack).await?;
@@ -1044,6 +1046,7 @@ impl RoutingTable {
return Ok(false);
}
};
+ util::record_phase_watch_delivery("router", handoff.phase, handoff.phase_entered_at_ms);
match handoff.phase {
HandoffPhase::Freezing | HandoffPhase::Draining | HandoffPhase::Warming => {
@@ -1073,6 +1076,7 @@ impl RoutingTable {
router_name: router_name.to_string(),
partition: handoff.partition,
acked_at: util::now_seconds(),
+ acked_at_ms: 0,
handoff_id: handoff.handoff_id.clone(),
};
store.put_freeze_ack(&ack).await?;
diff --git a/rust/personhog-coordination/src/store.rs b/rust/personhog-coordination/src/store.rs
index c2c754c38069..f4b4402540da 100644
--- a/rust/personhog-coordination/src/store.rs
+++ b/rust/personhog-coordination/src/store.rs
@@ -377,7 +377,11 @@ impl PersonhogStore {
partition: ack.partition,
router: &ack.router_name,
});
- Ok(self.inner.put(&key, ack, None).await?)
+ // The store stamps the millisecond clock so span metrics never
+ // depend on each writer remembering to.
+ let mut stamped = ack.clone();
+ stamped.acked_at_ms = assignment_coordination::util::now_millis();
+ Ok(self.inner.put(&key, &stamped, None).await?)
}
pub async fn list_freeze_acks(&self, partition: u32) -> Result<Vec<RouterFreezeAck>> {
@@ -407,7 +411,11 @@ impl PersonhogStore {
partition: ack.partition,
pod: &ack.pod_name,
});
- Ok(self.inner.put(&key, ack, None).await?)
+ // The store stamps the millisecond clock so span metrics never
+ // depend on each writer remembering to.
+ let mut stamped = ack.clone();
+ stamped.acked_at_ms = assignment_coordination::util::now_millis();
+ Ok(self.inner.put(&key, &stamped, None).await?)
}
pub async fn list_drained_acks(&self, partition: u32) -> Result<Vec<PodDrainedAck>> {
@@ -437,7 +445,11 @@ impl PersonhogStore {
partition: ack.partition,
pod: &ack.pod_name,
});
- Ok(self.inner.put(&key, ack, None).await?)
+ // The store stamps the millisecond clock so span metrics never
+ // depend on each writer remembering to.
+ let mut stamped = ack.clone();
+ stamped.acked_at_ms = assignment_coordination::util::now_millis();
+ Ok(self.inner.put(&key, &stamped, None).await?)
}
pub async fn list_warmed_acks(&self, partition: u32) -> Result<Vec<PodWarmedAck>> {
diff --git a/rust/personhog-coordination/src/types.rs b/rust/personhog-coordination/src/types.rs
index 8e275b076e29..de33c738b5ec 100644
--- a/rust/personhog-coordination/src/types.rs
+++ b/rust/personhog-coordination/src/types.rs
@@ -229,6 +229,12 @@ pub struct RouterFreezeAck {
/// this ack toward the handoff whose id it names.
#[serde(default)]
pub handoff_id: String,
+ /// Millisecond stamp written by the store at put time, for span
+ /// metrics (`acked_at` above keeps second resolution for protocol
+ /// visibility). Zero in records written by earlier builds; span
+ /// consumers skip zeros.
+ #[serde(default)]
+ pub acked_at_ms: i64,
}
/// The old owner's acknowledgment that all inflight request handlers for a
@@ -246,6 +252,12 @@ pub struct PodDrainedAck {
/// this ack toward the handoff whose id it names.
#[serde(default)]
pub handoff_id: String,
+ /// Millisecond stamp written by the store at put time, for span
+ /// metrics (`acked_at` above keeps second resolution for protocol
+ /// visibility). Zero in records written by earlier builds; span
+ /// consumers skip zeros.
+ #[serde(default)]
+ pub acked_at_ms: i64,
}
/// The new owner's acknowledgment that it has consumed Kafka up to the stable
@@ -260,6 +272,12 @@ pub struct PodWarmedAck {
/// this ack toward the handoff whose id it names.
#[serde(default)]
pub handoff_id: String,
+ /// Millisecond stamp written by the store at put time, for span
+ /// metrics (`acked_at` above keeps second resolution for protocol
+ /// visibility). Zero in records written by earlier builds; span
+ /// consumers skip zeros.
+ #[serde(default)]
+ pub acked_at_ms: i64,
}
/// Written to `{prefix}coordinator/leader` by the coordinator that wins
@@ -396,6 +414,7 @@ mod tests {
router_name: "router-0".to_string(),
partition: 42,
acked_at: 1700000000,
+ acked_at_ms: 0,
handoff_id: "1700000000000-0".to_string(),
};
let json = serde_json::to_string(&ack).unwrap();
@@ -409,6 +428,7 @@ mod tests {
pod_name: "leader-0".to_string(),
partition: 42,
acked_at: 1700000000,
+ acked_at_ms: 0,
handoff_id: "1700000000000-0".to_string(),
};
let json = serde_json::to_string(&ack).unwrap();
@@ -422,6 +442,7 @@ mod tests {
pod_name: "leader-1".to_string(),
partition: 42,
acked_at: 1700000000,
+ acked_at_ms: 0,
handoff_id: "1700000000000-0".to_string(),
};
let json = serde_json::to_string(&ack).unwrap();
diff --git a/rust/personhog-coordination/src/util.rs b/rust/personhog-coordination/src/util.rs
index 331f370f54cf..679101619c57 100644
--- a/rust/personhog-coordination/src/util.rs
+++ b/rust/personhog-coordination/src/util.rs
@@ -214,6 +214,70 @@ pub async fn run_lease_keepalive(
}
}
+/// Records how long a handoff phase write took to reach this observer's
+/// watch stream. Only the non-terminal phases are recorded — those are
+/// the writes whose propagation gates protocol progress, while Complete
+/// puts (including cancellation reaffirms) arrive in floods that would
+/// drown the signal. Same-cluster clocks make millisecond skew
+/// negligible for the diagnostic purpose; records stamped by
+/// pre-instrumentation writers (zero) are skipped.
+pub fn record_phase_watch_delivery(
+ observer: &'static str,
+ phase: crate::types::HandoffPhase,
+ phase_entered_at_ms: i64,
+) {
+ if phase == crate::types::HandoffPhase::Complete || phase_entered_at_ms <= 0 {
+ return;
+ }
+ let lag = now_millis().saturating_sub(phase_entered_at_ms).max(0);
+ metrics::histogram!(
+ "personhog_coordination_phase_watch_delivery_ms",
+ "observer" => observer
+ )
+ .record(lag as f64);
+}
+
+/// Records the coordinator's reaction lag: from the newest ack that
+/// satisfied a quorum to the phase advance it triggered. Zero-stamped
+/// acks (pre-instrumentation writers) are excluded.
+pub fn record_ack_to_advance(phase: &'static str, ack_stamps_ms: impl Iterator<Item = i64>) {
+ let Some(latest) = ack_stamps_ms.filter(|&t| t > 0).max() else {
+ return;
+ };
+ let lag = now_millis().saturating_sub(latest).max(0);
+ metrics::histogram!(
+ "personhog_coordination_ack_to_advance_ms",
+ "phase" => phase
+ )
+ .record(lag as f64);
+}
+
+/// Touch the coordinator's deploy-burst counters so their series exist
+/// with zero samples before any burst. metrics registration is lazy: a
+/// counter that first fires between two scrapes materializes with the
+/// burst already inside it, and no rate function can recover a delta
+/// that precedes a series' first sample.
+pub fn preregister_coordinator_metrics() {
+ for kind in ["fresh", "move"] {
+ metrics::counter!("personhog_coordination_handoffs_created_total", "kind" => kind)
+ .increment(0);
+ }
+ metrics::counter!("personhog_coordination_elections_won_total").increment(0);
+ metrics::counter!("personhog_coordination_partition_releases_total").increment(0);
+}
+
+/// Same as [`preregister_coordinator_metrics`], for the counters the
+/// router's coordination layer emits.
+pub fn preregister_router_coordination_metrics() {
+ for outcome in ["revoked", "revoke_failed"] {
+ metrics::counter!(
+ "personhog_coordination_router_deregistered_total",
+ "outcome" => outcome
+ )
+ .increment(0);
+ }
+}
+
#[cfg(test)]
mod tests {
use std::collections::HashSet;
diff --git a/rust/personhog-coordination/tests/integration.rs b/rust/personhog-coordination/tests/integration.rs
index 1cf2db89a602..f1e8b862eaaa 100644
--- a/rust/personhog-coordination/tests/integration.rs
+++ b/rust/personhog-coordination/tests/integration.rs
@@ -2087,6 +2087,7 @@ async fn reconcile_advances_warming_with_pre_staged_warmed_ack() {
pod_name: "writer-1".to_string(),
partition: 6,
acked_at: 0,
+ acked_at_ms: 0,
handoff_id: String::new(),
})
.await
@@ -2206,6 +2207,7 @@ async fn draining_old_owner_blocks_phase_advance() {
pod_name: "writer-draining".to_string(),
partition: 7,
acked_at: 0,
+ acked_at_ms: 0,
handoff_id: String::new(),
})
.await
@@ -2484,6 +2486,7 @@ async fn freezing_blocks_until_routers_ack_before_draining() {
router_name: "slow-router".to_string(),
partition: 1,
acked_at: 0,
+ acked_at_ms: 0,
handoff_id: String::new(),
})
.await
@@ -2732,6 +2735,7 @@ async fn reconcile_advances_draining_with_pre_staged_drained_ack() {
pod_name: "writer-old".to_string(),
partition: 5,
acked_at: 0,
+ acked_at_ms: 0,
handoff_id: String::new(),
})
.await
@@ -3383,3 +3387,26 @@ async fn rebalance_never_writes_assignment_records() {
}
}
}
+
+/// The store stamps `acked_at_ms` at put time so span metrics can measure
+/// ack-to-advance lag; writers all pass zero and must get a real stamp back.
+#[tokio::test]
+async fn store_stamps_ack_millis_on_put() {
+ let store = test_store("ack-ms-stamp").await;
+ store
+ .put_freeze_ack(&personhog_coordination::types::RouterFreezeAck {
+ router_name: "router-0".to_string(),
+ partition: 3,
+ acked_at: 1_700_000_000,
+ acked_at_ms: 0,
+ handoff_id: "h-1".to_string(),
+ })
+ .await
+ .expect("put freeze ack");
+ let acks = store.list_freeze_acks(3).await.expect("list freeze acks");
+ assert_eq!(acks.len(), 1);
+ assert!(
+ acks[0].acked_at_ms > 0,
+ "store must stamp the millisecond clock on ack writes"
+ );
+}
diff --git a/rust/personhog-coordination/tests/protocol_hardening.rs b/rust/personhog-coordination/tests/protocol_hardening.rs
index 231ef2fcc8f6..97a69a74270b 100644
--- a/rust/personhog-coordination/tests/protocol_hardening.rs
+++ b/rust/personhog-coordination/tests/protocol_hardening.rs
@@ -605,6 +605,7 @@ async fn guarded_handoff_delete_skips_recreated_handoff() {
router_name: "router-0".to_string(),
partition: 0,
acked_at: 0,
+ acked_at_ms: 0,
handoff_id: "test-handoff-0".to_string(),
})
.await
@@ -677,6 +678,7 @@ async fn ack_for_previous_handoff_does_not_satisfy_quorum() {
router_name: "r-live".to_string(),
partition: 0,
acked_at: 0,
+ acked_at_ms: 0,
handoff_id: "a-previous-handoff".to_string(),
})
.await
@@ -716,6 +718,7 @@ async fn ack_for_previous_handoff_does_not_satisfy_quorum() {
router_name: "r-live".to_string(),
partition: 0,
acked_at: 0,
+ acked_at_ms: 0,
handoff_id: "test-handoff-0".to_string(),
})
.await
@@ -795,6 +798,7 @@ async fn router_departure_advances_a_waiting_freeze() {
router_name: "r-live".to_string(),
partition: 0,
acked_at: 0,
+ acked_at_ms: 0,
handoff_id: "test-handoff-0".to_string(),
})
.await
@@ -911,6 +915,7 @@ async fn legacy_ack_without_handoff_id_does_not_satisfy_quorum() {
router_name: "r-legacy".to_string(),
partition: 0,
acked_at: 0,
+ acked_at_ms: 0,
handoff_id: "test-handoff-0".to_string(),
})
.await
@@ -1229,6 +1234,7 @@ async fn freezing_handoff_advances_when_unacked_router_departs() {
router_name: "router-acked".to_string(),
partition: 0,
acked_at: 0,
+ acked_at_ms: 0,
handoff_id: "test-handoff-0".to_string(),
})
.await
@@ -1371,6 +1377,7 @@ async fn stale_freeze_ack_does_not_satisfy_quorum_for_live_router() {
router_name: "router-departed".to_string(),
partition: 0,
acked_at: 0,
+ acked_at_ms: 0,
handoff_id: "test-handoff-0".to_string(),
})
.await
@@ -1428,6 +1435,7 @@ async fn stale_freeze_ack_does_not_satisfy_quorum_for_live_router() {
router_name: "router-silent".to_string(),
partition: 0,
acked_at: 0,
+ acked_at_ms: 0,
handoff_id: "test-handoff-0".to_string(),
})
.await
diff --git a/rust/personhog-leader/src/cache/partitioned.rs b/rust/personhog-leader/src/cache/partitioned.rs
index a604260f05b3..1c519cfe6bfe 100644
--- a/rust/personhog-leader/src/cache/partitioned.rs
+++ b/rust/personhog-leader/src/cache/partitioned.rs
@@ -61,6 +61,11 @@ impl PartitionedCache {
self.partitions.remove(&partition);
}
+ /// Total resident weight in bytes across all owned partitions.
+ pub fn usage_bytes(&self) -> usize {
+ self.partitions.iter().map(|c| c.usage_bytes()).sum()
+ }
+
/// Check if a partition cache exists (i.e., the partition is owned).
pub fn has_partition(&self, partition: u32) -> bool {
self.partitions.contains_key(&partition)
diff --git a/rust/personhog-leader/src/cache/persons.rs b/rust/personhog-leader/src/cache/persons.rs
index 023fa62bea74..5288e0d0ddda 100644
--- a/rust/personhog-leader/src/cache/persons.rs
+++ b/rust/personhog-leader/src/cache/persons.rs
@@ -133,6 +133,12 @@ impl PersonCache {
pub fn remove(&self, key: &PersonCacheKey) {
self.inner.remove(key);
}
+
+ /// Resident weight in bytes — the sum of entries' `approx_bytes` as
+ /// foyer accounts it against the capacity.
+ pub fn usage_bytes(&self) -> usize {
+ self.inner.usage()
+ }
}
#[cfg(test)]
diff --git a/rust/personhog-leader/src/config.rs b/rust/personhog-leader/src/config.rs
index aedabdb7807d..2ea96b87e084 100644
--- a/rust/personhog-leader/src/config.rs
+++ b/rust/personhog-leader/src/config.rs
@@ -23,6 +23,11 @@ pub struct Config {
#[envconfig(default = "9102")]
pub metrics_port: u16,
+ /// Maximum concurrent partition warms. Warms are broker-bound reads
+ /// on MSK, so this can sit well above the S3-era default of 4.
+ #[envconfig(default = "8")]
+ pub warm_concurrency: usize,
+
// ── gRPC server ──────────────────────────────────────────────
/// Interval between HTTP/2 keepalive pings sent by the gRPC server (0 = disabled)
#[envconfig(default = "30")]
diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rs
index 7ef05588099a..667b2b13fbc2 100644
--- a/rust/personhog-leader/src/main.rs
+++ b/rust/personhog-leader/src/main.rs
@@ -51,6 +51,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.expect("failed to install rustls ring CryptoProvider");
let config = Config::init_from_env().expect("Invalid configuration");
+ preregister_metrics();
validate_table_name(&config.fallback_table).expect("Invalid FALLBACK_TABLE");
// Initialize tracing
@@ -309,6 +310,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
lease_ttl: config.lease_ttl,
heartbeat_interval: config.heartbeat_interval(),
advertise_address: Some(advertise_address),
+ // Zero would park every warm on an unobtainable permit and wedge
+ // handoffs; treat it as fully sequential instead.
+ warm_concurrency: config.warm_concurrency.max(1),
..Default::default()
};
@@ -323,7 +327,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let pools = Arc::clone(&warm_pools);
let warm_slots = pod_config.warm_concurrency;
tokio::spawn(async move {
- pools.offsets.warm_up(2).await;
+ // Committed-offset queries run one per concurrent warm, so
+ // the offsets pool needs the same depth as the warm slots.
+ pools.offsets.warm_up(warm_slots).await;
pools.warming.warm_up(warm_slots).await;
});
}
@@ -351,6 +357,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
tokio::spawn(run_dirty_index_prune_loop(
Arc::clone(&dirty_index),
+ Arc::clone(&cache),
Arc::clone(&warm_pools),
config.kafka_person_state_topic.clone(),
Duration::from_secs(config.warm_committed_offsets_timeout_secs),
@@ -444,6 +451,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// client — each tick reuses the connection instead of rebuilding one.
async fn run_dirty_index_prune_loop(
dirty_index: Arc<DirtyIndex>,
+ cache: Arc<PartitionedCache>,
pools: Arc<WarmClientPools>,
topic: String,
offsets_timeout: Duration,
@@ -459,6 +467,7 @@ async fn run_dirty_index_prune_loop(
let partitions = dirty_index.partitions_with_marks();
gauge!("personhog_leader_dirty_index_size").set(dirty_index.len() as f64);
gauge!("personhog_leader_dirty_index_max_entries").set(dirty_index.max_entries() as f64);
+ gauge!("personhog_leader_cache_weight_bytes").set(cache.usage_bytes() as f64);
if partitions.is_empty() {
continue;
}
@@ -526,3 +535,19 @@ async fn discover_own_controller(
.map_err(|e| format!("controller discovery failed: {e}"))?;
Ok((awareness, info))
}
+
+/// Touch the leader's deploy-burst counters so their series exist with
+/// zero samples before any burst. metrics registration is lazy: a counter
+/// that first fires between two scrapes materializes with the burst
+/// already inside it, and no rate function can recover a delta that
+/// precedes a series' first sample.
+fn preregister_metrics() {
+ counter!("personhog_leader_warmed_messages_total").increment(0);
+ counter!("personhog_leader_warm_retries_exhausted_total", "stage" => "committed_offset")
+ .increment(0);
+ counter!("personhog_leader_warm_retries_exhausted_total", "stage" => "fetch_watermarks")
+ .increment(0);
+ for stage in ["committed_offset", "fetch_watermarks"] {
+ counter!("personhog_leader_warm_retries_total", "stage" => stage).increment(0);
+ }
+}
diff --git a/rust/personhog-leader/src/warming.rs b/rust/personhog-leader/src/warming.rs
index 5a11ffd03640..c57c0d4959fc 100644
--- a/rust/personhog-leader/src/warming.rs
+++ b/rust/personhog-leader/src/warming.rs
@@ -375,10 +375,18 @@ pub async fn warm_from_kafka(
CoordError::invalid_state(format!("partition {partition} exceeds i32::MAX"))
})?;
- // Query the writer's committed offset via a separate, short-lived client.
- // This keeps our long-lived warming consumer isolated from the writer's
- // consumer group.
- let committed_offset = with_warm_retry("committed_offset", partition, cfg.retry, || async {
+ // Arc because the watermark retry closure needs its own handle for
+ // the blocking pool; sole ownership returns once the retries finish.
+ let consumer = Arc::new(pools.warming.checkout()?);
+
+ // The two offset queries are independent — the writer's committed
+ // position comes from the offsets pool, the watermarks from this
+ // consumer — so they run concurrently; each keeps its own retry
+ // policy. The committed query uses a separate, short-lived client to
+ // keep the long-lived warming consumer isolated from the writer's
+ // consumer group. `fetch_watermarks` is synchronous in rdkafka and
+ // may block for the full timeout, so it runs on the blocking pool.
+ let committed_fut = with_warm_retry("committed_offset", partition, cfg.retry, || async {
fetch_writer_committed_offset(
&pools.offsets,
&cfg.topic,
@@ -386,17 +394,8 @@ pub async fn warm_from_kafka(
cfg.committed_offsets_timeout,
)
.await
- })
- .await?;
-
- // Arc because the watermark retry closure needs its own handle for
- // the blocking pool; sole ownership returns once the retries finish.
- let consumer = Arc::new(pools.warming.checkout()?);
-
- // `fetch_watermarks` is synchronous in rdkafka and may block for the
- // full timeout. Run it on the blocking pool so retries don't park the
- // runtime thread.
- let (low, hwm) = with_warm_retry("fetch_watermarks", partition, cfg.retry, || {
+ });
+ let watermarks_fut = with_warm_retry("fetch_watermarks", partition, cfg.retry, || {
let consumer = Arc::clone(&consumer);
let topic = cfg.topic.clone();
let timeout = cfg.fetch_watermarks_timeout;
@@ -409,8 +408,28 @@ pub async fn warm_from_kafka(
.await
.map_err(|e| CoordError::invalid_state(format!("fetch_watermarks join: {e}")))?
}
- })
- .await?;
+ });
+ let (committed_res, watermarks_res) = tokio::join!(committed_fut, watermarks_fut);
+ let (low, hwm) = match watermarks_res {
+ Ok(marks) => marks,
+ // The watermark call failed on this consumer, so the pool's
+ // drop-doubtful-clients contract applies: fall through without
+ // giving it back.
+ Err(e) => return Err(e),
+ };
+ let committed_offset = match committed_res {
+ Ok(offset) => offset,
+ Err(e) => {
+ // The committed-offset query runs on the offsets pool's
+ // client; this consumer did nothing and is sound. Returning
+ // it keeps reconcile-driven warm retries from rebuilding a
+ // Kafka client per attempt.
+ if let Ok(consumer) = Arc::try_unwrap(consumer) {
+ pools.warming.give_back(consumer);
+ }
+ return Err(e);
+ }
+ };
let start_offset = resolve_start_offset(committed_offset, low, cfg.lookback_offsets);
@@ -425,24 +444,28 @@ pub async fn warm_from_kafka(
"computed warming range"
);
- let mut assign_tpl = TopicPartitionList::new();
- assign_tpl
- .add_partition_offset(&cfg.topic, partition_i32, Offset::Offset(start_offset))
- .map_err(|e| CoordError::invalid_state(format!("tpl add_partition_offset: {e}")))?;
- consumer
- .assign(&assign_tpl)
- .map_err(|e| CoordError::invalid_state(format!("consumer assign: {e}")))?;
-
if hwm <= start_offset {
// Empty range — install an empty partition cache. Use the
// atomic install path so this matches the populated path's
// publication semantics (the partition becomes observable in
- // a single dashmap insert).
+ // a single dashmap insert). The consumer never got assigned, so
+ // it goes straight back to the pool.
cache.install_warmed_partition(partition, std::iter::empty());
tracing::info!(partition, hwm, start_offset, "no messages to warm in range");
+ if let Ok(consumer) = Arc::try_unwrap(consumer) {
+ pools.warming.give_back(consumer);
+ }
return Ok(());
}
+ let mut assign_tpl = TopicPartitionList::new();
+ assign_tpl
+ .add_partition_offset(&cfg.topic, partition_i32, Offset::Offset(start_offset))
+ .map_err(|e| CoordError::invalid_state(format!("tpl add_partition_offset: {e}")))?;
+ consumer
+ .assign(&assign_tpl)
+ .map_err(|e| CoordError::invalid_state(format!("consumer assign: {e}")))?;
+
// Buffer records locally and only commit them to the cache after the
// entire range warms successfully. Any decode/IO failure mid-range
// aborts warming with no observable cache mutation, which keeps a
diff --git a/rust/personhog-leader/tests/warming_integration.rs b/rust/personhog-leader/tests/warming_integration.rs
index 46434ac1b68f..6e98228497e5 100644
--- a/rust/personhog-leader/tests/warming_integration.rs
+++ b/rust/personhog-leader/tests/warming_integration.rs
@@ -153,6 +153,18 @@ async fn warming_handles_empty_partition() {
matches!(cache.get(0, &key), CacheLookup::PersonNotFound),
"no records were produced, so cache must be empty"
);
+
+ // The empty path must return its consumer to the pool, not drop it —
+ // a second empty warm reuses the same client instead of creating one.
+ let created_after_first = pools.warming.created_count();
+ warm_from_kafka(&cfg, &pools, &cache, &DirtyIndex::new(1_000_000), 0)
+ .await
+ .expect("second empty warm should succeed");
+ assert_eq!(
+ pools.warming.created_count(),
+ created_after_first,
+ "an empty warm must give its pooled consumer back"
+ );
}
/// Partition isolation: warming partition 0 must not populate cache
diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rs
index 5edc54a98ba5..7dd5e517f0a3 100644
--- a/rust/personhog-router/src/main.rs
+++ b/rust/personhog-router/src/main.rs
@@ -36,6 +36,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.expect("Failed to install rustls crypto provider");
let config = Config::init_from_env().expect("Invalid configuration");
+ preregister_metrics();
// Initialize tracing
let log_layer = fmt::layer()
@@ -448,3 +449,32 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
monitor_guard.wait().await?;
Ok(())
}
+
+/// Touch the deploy-burst counters so their series exist with zero
+/// samples before any burst. metrics registration is lazy: a counter
+/// that first fires between two scrapes materializes with the burst
+/// already inside it, and no rate function can recover a delta that
+/// precedes a series' first sample. Only enumerable label sets are
+/// touched; series with dynamic labels (client names) stay lazy.
+fn preregister_metrics() {
+ use metrics::counter;
+ counter!("personhog_router_stash_enqueued_total").increment(0);
+ counter!("personhog_router_stash_replayed_total").increment(0);
+ counter!("personhog_router_forward_retries_exhausted_total").increment(0);
+ for outcome in ["success", "error", "expired"] {
+ counter!("personhog_router_stash_drained_total", "outcome" => outcome).increment(0);
+ }
+ for cause in ["max_messages", "max_bytes"] {
+ counter!("personhog_router_stash_rejected_total", "cause" => cause).increment(0);
+ }
+ counter!("personhog_router_stash_dropped_total", "reason" => "receiver_gone").increment(0);
+ for reason in ["unrouted", "fenced", "transport"] {
+ counter!("personhog_router_forward_retries_total", "path" => "direct", "reason" => reason)
+ .increment(0);
+ }
+ for reason in ["unrouted", "fenced", "transport", "cancelled"] {
+ counter!("personhog_router_forward_retries_total", "path" => "stash", "reason" => reason)
+ .increment(0);
+ }
+ personhog_coordination::preregister_router_coordination_metrics();
+}
diff --git a/rust/personhog-router/src/proxy.rs b/rust/personhog-router/src/proxy.rs
index 70fddc98654e..3d1d7407a2cb 100644
--- a/rust/personhog-router/src/proxy.rs
+++ b/rust/personhog-router/src/proxy.rs
@@ -19,7 +19,7 @@ use tower::{Service, ServiceExt};
use crate::backend::{LeaderBackend, ReplicaBackend};
use crate::config::RetryConfig;
-use crate::grpc_http::{grpc_error_response, is_grpc_error_response};
+use crate::grpc_http::{grpc_error_response, grpc_status_code, is_grpc_error_response};
const SERVICE_PREFIX: &str = "/personhog.service.v1.PersonHogService/";
const REPLICA_PREFIX: &str = "/personhog.replica.v1.PersonHogReplica/";
@@ -238,6 +238,7 @@ impl RawProxyInner {
"method" => method.clone(),
"backend" => backend,
"client" => client.clone(),
+ "code" => grpc_code_label(grpc_status_code(&response)),
)
.increment(1);
}
@@ -452,6 +453,22 @@ impl RawProxyInner {
}
}
+/// Static label for an error response's gRPC status, separating expected
+/// admission rejections (invalid_argument) from availability and internal
+/// failures on the errors counter.
+fn grpc_code_label(code: Option<i32>) -> &'static str {
+ match code {
+ Some(3) => "invalid_argument",
+ Some(4) => "deadline_exceeded",
+ Some(5) => "not_found",
+ Some(8) => "resource_exhausted",
+ Some(9) => "failed_precondition",
+ Some(13) => "internal",
+ Some(14) => "unavailable",
+ _ => "other",
+ }
+}
+
// ── gRPC body helpers ──────────────────────────────────────────────────
async fn collect_body_limited(
diff --git a/rust/personhog-stateright/src/model.rs b/rust/personhog-stateright/src/model.rs
index 889930c791d7..482a1956c667 100644
--- a/rust/personhog-stateright/src/model.rs
+++ b/rust/personhog-stateright/src/model.rs
@@ -618,6 +618,7 @@ impl Model for HandoffModel {
router_name: router_name(r),
partition: p as u32,
acked_at: 0,
+ acked_at_ms: 0,
handoff_id: id.to_string(),
})
})
@@ -654,6 +655,7 @@ impl Model for HandoffModel {
pod_name: pod_name(x),
partition: p as u32,
acked_at: 0,
+ acked_at_ms: 0,
handoff_id: id.to_string(),
})
})
@@ -671,6 +673,7 @@ impl Model for HandoffModel {
pod_name: pod_name(x),
partition: p as u32,
acked_at: 0,
+ acked_at_ms: 0,
handoff_id: id.to_string(),
})
})