: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): instrument the coordination protocol and changelog p… (#73917)
Zach Brown8748291f8b79
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex f2b30927ee05..75b9e314f4f6 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -7702,6 +7702,7 @@ dependencies = ["k8s-awareness","k8s-openapi","kube",+ "metrics","serde","serde_json","serial_test",diff --git a/rust/personhog-common/src/grpc.rs b/rust/personhog-common/src/grpc.rsindex 7fed9ad50ad4..4b944a777dac 100644--- a/rust/personhog-common/src/grpc.rs+++ b/rust/personhog-common/src/grpc.rs@@ -65,6 +65,44 @@ pub fn current_method_name() -> Arc<str> {.unwrap_or_else(|_| Arc::from("unknown"))}+/// Label for a failure carrying no gRPC status at all — a client-side+/// error (a serialization failure, say) rather than anything a server+/// said. Part of the same label vocabulary as [`code_as_str`], and+/// deliberately distinct from its `unknown`, which is a real code a+/// server can return.+pub const NON_STATUS: &str = "non_status";++/// Stable snake_case name for a gRPC status code, for use as a metric+/// label. Codes are a fixed vocabulary, which is what makes them safe to+/// label with; status *messages* never are. Shared so every service+/// labels the same failure the same way — a dashboard comparing a+/// client's view of an error against the router's should not have to+/// translate between two spellings. Callers that classify errors which+/// may carry no status at all complete the vocabulary with+/// [`NON_STATUS`].+pub fn code_as_str(code: tonic::Code) -> &'static str {+ use tonic::Code;+ match code {+ Code::Ok => "ok",+ Code::Cancelled => "cancelled",+ Code::Unknown => "unknown",+ Code::InvalidArgument => "invalid_argument",+ Code::DeadlineExceeded => "deadline_exceeded",+ Code::NotFound => "not_found",+ Code::AlreadyExists => "already_exists",+ Code::PermissionDenied => "permission_denied",+ Code::ResourceExhausted => "resource_exhausted",+ Code::FailedPrecondition => "failed_precondition",+ Code::Aborted => "aborted",+ Code::OutOfRange => "out_of_range",+ Code::Unimplemented => "unimplemented",+ Code::Internal => "internal",+ Code::Unavailable => "unavailable",+ Code::DataLoss => "data_loss",+ Code::Unauthenticated => "unauthenticated",+ }+}+const MAX_HEADER_TAG_LEN: usize = 128;fn is_safe_tag_char(c: char) -> bool {diff --git a/rust/personhog-coordination/Cargo.toml b/rust/personhog-coordination/Cargo.tomlindex 1e06faa65057..7163ec66c8ea 100644--- a/rust/personhog-coordination/Cargo.toml+++ b/rust/personhog-coordination/Cargo.toml@@ -9,6 +9,7 @@ assignment-coordination = { path = "../common/assignment-coordination" }async-trait = { workspace = true }etcd-client = "0.18"k8s-awareness = { path = "../common/k8s-awareness" }+metrics = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }thiserror = { workspace = true }diff --git a/rust/personhog-coordination/src/coordinator.rs b/rust/personhog-coordination/src/coordinator.rsindex f7937fa8e92a..2f890d8c4204 100644--- a/rust/personhog-coordination/src/coordinator.rs+++ b/rust/personhog-coordination/src/coordinator.rs@@ -3,6 +3,7 @@ use std::sync::Arc;use std::time::Duration;use etcd_client::{EventType, WatchStream};+use metrics::{counter, gauge, histogram};use tokio_util::sync::CancellationToken;use assignment_coordination::store::parse_watch_value;@@ -134,6 +135,8 @@ impl Coordinator {}tracing::info!(name = %self.config.name, "acquired leadership");+ gauge!("personhog_coordination_is_coordinator").set(1.0);+ counter!("personhog_coordination_elections_won_total").increment(1);// A failed keepalive means the lease is gone (or about to be) and// another candidate can win the election: abdicate rather than@@ -168,6 +171,8 @@ impl Coordinator {// of waiting out the lease TTL.drop(self.store.revoke_lease(lease_id).await);+ reset_coordinator_gauges();+result.map(|()| true)}@@ -414,10 +419,27 @@ impl Coordinator {tokio::select! {_ = cancel.cancelled() => return Ok(()),_ = tick.tick() => {- for handoff in store.list_handoffs().await? {- Self::handle_handoff_update_static(&store, &handoff).await?;+ 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?;}+ // The gauge refresh is best-effort and runs after the+ // reconcile pass: its reads exist only for metrics and+ // must never delay or interrupt handoff advancement —+ // this tick is the liveness backstop for router+ // departures, which fire no watched event. A skipped+ // refresh is repaired by the next tick.+ let pods = store.list_pods().await;+ let routers = store.list_routers().await;+ match (pods, routers) {+ (Ok(pods), Ok(routers)) => {+ record_cluster_gauges(&handoffs, &pods, routers.len());+ }+ (Err(e), _) | (_, Err(e)) => {+ tracing::debug!(error = %e, "skipping cluster gauge refresh");+ }+ }}}}@@ -461,6 +483,7 @@ impl Coordinator {.cas_handoff_phase(partition, HandoffPhase::Freezing, target).await?;if advanced {+ record_phase_advance(&handoff, target);tracing::info!(partition,freeze_acks = freeze_acks.len(),@@ -482,6 +505,7 @@ impl Coordinator {.cas_handoff_phase(partition, HandoffPhase::Draining, HandoffPhase::Warming).await?;if advanced {+ record_phase_advance(&handoff, HandoffPhase::Warming);tracing::info!(partition,old_owner = ?handoff.old_owner,@@ -499,7 +523,9 @@ impl Coordinator {"new owner warmed, completing handoff");match store.complete_handoff(partition).await {- Ok(true) => {}+ Ok(true) => {+ record_phase_advance(&handoff, HandoffPhase::Complete);+ }Ok(false) => {tracing::warn!(partition, "handoff modified concurrently, skipping");}@@ -689,6 +715,11 @@ impl Coordinator {return Ok(());}+ counter!("personhog_coordination_handoffs_created_total", "kind" => "move")+ .increment(moves as u64);+ counter!("personhog_coordination_handoffs_created_total", "kind" => "fresh")+ .increment((plan.handoffs.len() - moves) as u64);+// Nudge advancement for handoffs whose preconditions are already// satisfied at creation time (no old_owner, dead old_owner, vacuous// router quorum). Without this, such handoffs would stall waiting@@ -747,10 +778,13 @@ impl Coordinator {phase = ?current.phase,"cleaning up handoff targeting a dead new owner");- if !store+ if store.delete_handoff_and_acks_if_unchanged(current.partition, mod_revision).await?{+ counter!("personhog_coordination_handoffs_cancelled_total", "reason" => "dead_new_owner")+ .increment(1);+ } else {tracing::info!(partition = current.partition,"handoff changed concurrently, skipping cleanup"@@ -797,6 +831,71 @@ impl Coordinator {}}+// ── Metrics ─────────────────────────────────────────────────────++fn phase_label(phase: HandoffPhase) -> &'static str {+ match phase {+ HandoffPhase::Freezing => "freezing",+ HandoffPhase::Draining => "draining",+ HandoffPhase::Warming => "warming",+ HandoffPhase::Complete => "complete",+ }+}++/// Record a successful phase advance: a transition counter plus a+/// histogram of milliseconds elapsed since the handoff was created.+/// `started_at` carries one-second resolution, so these timings exist to+/// spot stalls (a handoff minutes into Freezing), not to micro-profile;+/// the pod side's warm and drain histograms carry the precise+/// per-operation cost.+fn record_phase_advance(handoff: &HandoffState, to: HandoffPhase) {+ 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);+}++/// 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) {+ for phase in [+ HandoffPhase::Freezing,+ HandoffPhase::Draining,+ HandoffPhase::Warming,+ HandoffPhase::Complete,+ ] {+ let count = handoffs.iter().filter(|h| h.phase == phase).count();+ gauge!("personhog_coordination_handoffs_in_flight", "phase" => phase_label(phase))+ .set(count as f64);+ }+ for (status, label) in [+ (PodStatus::Ready, "ready"),+ (PodStatus::Draining, "draining"),+ ] {+ let count = pods.iter().filter(|p| p.status == status).count();+ gauge!("personhog_coordination_pods_registered", "status" => label).set(count as f64);+ }+ gauge!("personhog_coordination_routers_registered").set(routers as f64);+}++/// Zero every gauge this instance exports as coordinator. Called when+/// leadership ends, so a former coordinator's scrape endpoint doesn't+/// keep reporting the last-known cluster state alongside the new+/// coordinator's live values.+fn reset_coordinator_gauges() {+ gauge!("personhog_coordination_is_coordinator").set(0.0);+ record_cluster_gauges(&[], &[], 0);+}+// ── Pure functions ──────────────────────────────────────────────/// Extract sorted pod names from registered pods, filtering to active statuses.diff --git a/rust/personhog-coordination/src/pod.rs b/rust/personhog-coordination/src/pod.rsindex 5893e97522a8..6725739421fe 100644--- a/rust/personhog-coordination/src/pod.rs+++ b/rust/personhog-coordination/src/pod.rs@@ -1,9 +1,10 @@use std::collections::HashSet;use std::sync::Arc;-use std::time::Duration;+use std::time::{Duration, Instant};use async_trait::async_trait;use etcd_client::{EventType, WatchStream};+use metrics::{counter, gauge, histogram};use tokio::sync::{Mutex, Notify};use tokio_util::sync::CancellationToken;@@ -506,7 +507,10 @@ impl PodHandle {DesiredState::Serving => {if !self.warmed_partitions.lock().await.contains(&partition) {tracing::info!(pod, partition, "converging to Serving: warming");+ let start = Instant::now();self.handler.warm_partition(partition).await?;+ histogram!("personhog_coordination_partition_warm_ms", "trigger" => "restart")+ .record(start.elapsed().as_secs_f64() * 1000.0);self.warmed_partitions.lock().await.insert(partition);} else if self.fenced_partitions.lock().await.contains(&partition) {tracing::info!(pod, partition, "converging to Serving: resuming writes");@@ -521,10 +525,19 @@ impl PodHandle {// waits for is meaningful. The produce path awaits Kafka// delivery before returning, so "no inflight handlers"// implies "every acked write is durable in Kafka."- if !self.fenced_partitions.lock().await.contains(&partition) {+ let newly_fencing = !self.fenced_partitions.lock().await.contains(&partition);+ if newly_fencing {tracing::info!(pod, partition, "converging to Drained: fencing + draining");}+ let start = Instant::now();self.handler.drain_partition_inflight(partition).await?;+ if newly_fencing {+ // Only the first convergence does a real drain wait;+ // later re-convergences are no-ops that would bury the+ // signal in near-zero samples.+ histogram!("personhog_coordination_partition_drain_ms")+ .record(start.elapsed().as_secs_f64() * 1000.0);+ }self.fenced_partitions.lock().await.insert(partition);if ack {let handoff = handoff.expect("Drained state only derives from a handoff");@@ -542,7 +555,10 @@ impl PodHandle {DesiredState::Acquiring => {if !self.warmed_partitions.lock().await.contains(&partition) {tracing::info!(pod, partition, "converging to Acquiring: warming");+ let start = Instant::now();self.handler.warm_partition(partition).await?;+ histogram!("personhog_coordination_partition_warm_ms", "trigger" => "handoff")+ .record(start.elapsed().as_secs_f64() * 1000.0);self.warmed_partitions.lock().await.insert(partition);}self.fenced_partitions.lock().await.remove(&partition);@@ -563,11 +579,15 @@ impl PodHandle {if was_warmed || was_fenced {tracing::info!(pod, partition, "converging to Released: releasing");self.handler.release_partition(partition).await?;+ counter!("personhog_coordination_partition_releases_total").increment(1);self.drain_notify.notify_one();}}}+ gauge!("personhog_coordination_partitions_held")+ .set(self.held_partition_count().await as f64);+Ok(())}diff --git a/rust/personhog-leader/src/kafka.rs b/rust/personhog-leader/src/kafka.rsindex e7857dd478a6..bdca42f68211 100644--- a/rust/personhog-leader/src/kafka.rs+++ b/rust/personhog-leader/src/kafka.rs@@ -1,5 +1,5 @@use common_kafka::kafka_producer::KafkaContext;-use metrics::counter;+use metrics::{counter, histogram};use prost::Message;use rdkafka::producer::{FutureProducer, FutureRecord};use tracing::error;@@ -51,10 +51,15 @@ pub async fn produce_person_changelog(.key(&key).payload(&payload);+ // Time-to-durable for the changelog append: every acked write waits+ // on this, so it is the broker's direct contribution to write latency.+ let start = std::time::Instant::now();match producer.send_result(record) {Ok(delivery_future) => match delivery_future.await {Ok(Ok((_, offset))) => {counter!("personhog_leader_kafka_produces_total").increment(1);+ histogram!("personhog_leader_kafka_produce_duration_ms")+ .record(start.elapsed().as_secs_f64() * 1000.0);Ok(offset)}Ok(Err((kafka_err, _))) => {diff --git a/rust/personhog-leader/src/pg.rs b/rust/personhog-leader/src/pg.rsindex a16d02d50600..fa71556147c2 100644--- a/rust/personhog-leader/src/pg.rs+++ b/rust/personhog-leader/src/pg.rs@@ -53,8 +53,8 @@ pub async fn load_person_from_pg(.fetch_optional(pool).await?;- histogram!("personhog_leader_pg_fallback_duration_seconds")- .record(start.elapsed().as_secs_f64());+ histogram!("personhog_leader_pg_fallback_duration_ms")+ .record(start.elapsed().as_secs_f64() * 1000.0);let Some(row) = row else {counter!("personhog_leader_pg_fallback_total", "outcome" => "not_found").increment(1);diff --git a/rust/personhog-router/src/backend/retry.rs b/rust/personhog-router/src/backend/retry.rsindex 576e969c1889..cdda6c02cef6 100644--- a/rust/personhog-router/src/backend/retry.rs+++ b/rust/personhog-router/src/backend/retry.rs@@ -2,7 +2,7 @@ use std::future::Future;use std::time::Duration;use metrics::counter;-use personhog_common::grpc::current_client_name;+use personhog_common::grpc::{code_as_str, current_client_name};use rand::Rng;use tonic::{Code, Status};use tracing::warn;@@ -13,28 +13,6 @@ fn is_retryable(code: Code) -> bool {matches!(code, Code::Unavailable | Code::DeadlineExceeded)}-fn code_as_str(code: Code) -> &'static str {- match code {- Code::Ok => "ok",- Code::Cancelled => "cancelled",- Code::Unknown => "unknown",- Code::InvalidArgument => "invalid_argument",- Code::DeadlineExceeded => "deadline_exceeded",- Code::NotFound => "not_found",- Code::AlreadyExists => "already_exists",- Code::PermissionDenied => "permission_denied",- Code::ResourceExhausted => "resource_exhausted",- Code::FailedPrecondition => "failed_precondition",- Code::Aborted => "aborted",- Code::OutOfRange => "out_of_range",- Code::Unimplemented => "unimplemented",- Code::Internal => "internal",- Code::Unavailable => "unavailable",- Code::DataLoss => "data_loss",- Code::Unauthenticated => "unauthenticated",- }-}-/// Executes an async operation with exponential backoff and jitter on transient gRPC errors.////// Only retries on `Unavailable` and `DeadlineExceeded` status codes.diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rsindex 9e0ba9dc60a3..28f83dea6407 100644--- a/rust/personhog-router/src/main.rs+++ b/rust/personhog-router/src/main.rs@@ -199,6 +199,19 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {RESPONSE_SIZE_BUCKETS,).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.+ .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,+ ],+ )+ .unwrap().install_recorder().expect("Failed to install metrics recorder");diff --git a/rust/personhog-test-harness/src/scenarios/blast.rs b/rust/personhog-test-harness/src/scenarios/blast.rsindex 20b5f59fe7d7..d53d4415e696 100644--- a/rust/personhog-test-harness/src/scenarios/blast.rs+++ b/rust/personhog-test-harness/src/scenarios/blast.rs@@ -4,7 +4,6 @@ use std::sync::Arc;use std::time::{Duration, Instant};use anyhow::{bail, Result};-use metrics::{counter, histogram};use personhog_proto::personhog::types::v1::ConsistencyLevel;use rand::{Rng, SeedableRng};use serde_json::{json, Value};@@ -16,6 +15,7 @@ use crate::client::HarnessClient;use crate::report::{print_report, ConsistencyViolation};use crate::state::PersonState;use crate::stats::StatsCollector;+use crate::traffic_metrics;pub async fn run(args: BlastArgs) -> Result<()> {let client = HarnessClient::connect(&args.router_url).await?;@@ -126,9 +126,10 @@ pub async fn run_traffic({Ok(resp) => {collector.writes.record_success(start.elapsed());- counter!("personhog_traffic_writes_total", "outcome" => "ok").increment(1);- histogram!("personhog_traffic_write_seconds")- .record(start.elapsed().as_secs_f64());+ traffic_metrics::record_write_ok(+ traffic_metrics::LANE_BLAST,+ start.elapsed(),+ );let mut written = HashMap::new();written.insert(key, serde_json::Value::String(value));match resp.person {@@ -140,8 +141,7 @@ pub async fn run_traffic(}Err(e) => {collector.writes.record_failure();- counter!("personhog_traffic_writes_total", "outcome" => "failed")- .increment(1);+ traffic_metrics::record_write_failed(traffic_metrics::LANE_BLAST, &e);// `{:#}` prints the full anyhow chain — the outer// context alone hides the gRPC status underneath.tracing::warn!(person_id, error = format!("{e:#}"), "write failed");@@ -194,6 +194,7 @@ pub async fn verify_strong(match result {Ok(Some(person)) => {collector.reads.record_success(start.elapsed());+ traffic_metrics::record_read_ok(traffic_metrics::LANE_VERIFY, start.elapsed());let props: Value = if person.properties.is_empty() {json!({})} else {@@ -204,6 +205,7 @@ pub async fn verify_strong(}Ok(None) => {collector.reads.record_failure();+ traffic_metrics::record_read_failed(traffic_metrics::LANE_VERIFY, "missing");all_violations.push(ConsistencyViolation {person_id,key: "__missing_person".to_string(),@@ -213,6 +215,10 @@ pub async fn verify_strong(}Err(e) => {collector.reads.record_failure();+ traffic_metrics::record_read_failed(+ traffic_metrics::LANE_VERIFY,+ traffic_metrics::status_reason(&e),+ );all_violations.push(ConsistencyViolation {person_id,key: "__strong_read_failed".to_string(),diff --git a/rust/personhog-test-harness/src/scenarios/consistency.rs b/rust/personhog-test-harness/src/scenarios/consistency.rsindex 3210172ead98..f095b39e483b 100644--- a/rust/personhog-test-harness/src/scenarios/consistency.rs+++ b/rust/personhog-test-harness/src/scenarios/consistency.rs@@ -11,6 +11,7 @@ use crate::client::HarnessClient;use crate::report::{print_report, ConsistencyViolation};use crate::state::PersonState;use crate::stats::StatsCollector;+use crate::traffic_metrics;pub async fn run(args: ConsistencyArgs) -> Result<()> {let client = HarnessClient::connect(&args.router_url).await?;@@ -217,10 +218,15 @@ pub async fn run_probers({Ok(response) => {collector.writes.record_success(write_start.elapsed());+ traffic_metrics::record_write_ok(+ traffic_metrics::LANE_PROBER,+ write_start.elapsed(),+ );response}Err(e) => {collector.writes.record_failure();+ traffic_metrics::record_write_failed(traffic_metrics::LANE_PROBER, &e);tracing::warn!(person_id, error = %e, "probe write failed");continue;}@@ -246,6 +252,10 @@ pub async fn run_probers({Ok(Some(person)) => {collector.reads.record_success(read_start.elapsed());+ traffic_metrics::record_read_ok(+ traffic_metrics::LANE_PROBER,+ read_start.elapsed(),+ );let props: serde_json::Value = serde_json::from_slice(&person.properties).unwrap_or_else(|_| serde_json::json!({}));let expected = serde_json::Value::String(marker);@@ -264,6 +274,10 @@ pub async fn run_probers(// acked write is a violation, not an availability// blip.collector.reads.record_failure();+ traffic_metrics::record_read_failed(+ traffic_metrics::LANE_PROBER,+ "missing",+ );violations.push(ConsistencyViolation {person_id,key,@@ -273,6 +287,10 @@ pub async fn run_probers(}Err(e) => {collector.reads.record_failure();+ traffic_metrics::record_read_failed(+ traffic_metrics::LANE_PROBER,+ traffic_metrics::status_reason(&e),+ );tracing::warn!(person_id, error = %e, "probe read failed");}}diff --git a/rust/personhog-test-harness/src/traffic_metrics.rs b/rust/personhog-test-harness/src/traffic_metrics.rsindex 7c312b1e0989..7f106fd70b0a 100644--- a/rust/personhog-test-harness/src/traffic_metrics.rs+++ b/rust/personhog-test-harness/src/traffic_metrics.rs@@ -8,14 +8,90 @@//! a process exit code.use std::process;+use std::time::Duration;use anyhow::Result;use axum::routing::get;use axum::Router;-use metrics::counter;+use metrics::{counter, histogram};+use personhog_common::grpc::{code_as_str, NON_STATUS};use crate::report::ConsistencyViolation;+/// The harness's own traffic sources, kept separable because they fail+/// for different reasons: `blast` is the paced write load, `prober` the+/// read-your-write canary a live client would notice, and `verify` the+/// epoch close-out sweep whose failure means the epoch cannot be checked+/// at all rather than that a client was served badly.+pub const LANE_BLAST: &str = "blast";+pub const LANE_PROBER: &str = "prober";+pub const LANE_VERIFY: &str = "verify";++/// Metric label for a failed request: the gRPC status code the client+/// wrapped in anyhow context, in the shared vocabulary every personhog+/// service labels with.+pub fn status_reason(err: &anyhow::Error) -> &'static str {+ match err.downcast_ref::<tonic::Status>() {+ Some(status) => code_as_str(status.code()),+ None => NON_STATUS,+ }+}++fn millis(elapsed: Duration) -> f64 {+ elapsed.as_secs_f64() * 1000.0+}++/// Record an acked write. `reason` carries `ok` rather than being+/// omitted so every series of this counter has the same label set.+pub fn record_write_ok(lane: &'static str, elapsed: Duration) {+ counter!(+ "personhog_traffic_writes_total",+ "lane" => lane,+ "outcome" => "ok",+ "reason" => "ok",+ )+ .increment(1);+ histogram!("personhog_traffic_write_duration_ms", "lane" => lane).record(millis(elapsed));+}++/// Record a write the stack refused or dropped. Latency is deliberately+/// not recorded: a timeout's duration is the deadline, not the stack's+/// service time, and mixing the two distorts the percentiles.+pub fn record_write_failed(lane: &'static str, err: &anyhow::Error) {+ counter!(+ "personhog_traffic_writes_total",+ "lane" => lane,+ "outcome" => "failed",+ "reason" => status_reason(err),+ )+ .increment(1);+}++pub fn record_read_ok(lane: &'static str, elapsed: Duration) {+ counter!(+ "personhog_traffic_reads_total",+ "lane" => lane,+ "outcome" => "ok",+ "reason" => "ok",+ )+ .increment(1);+ histogram!("personhog_traffic_read_duration_ms", "lane" => lane).record(millis(elapsed));+}++/// Record a strong read that did not return the person. `reason` is a+/// gRPC code for a failed call, or `missing` when the read succeeded but+/// found nothing — a served empty answer is a different failure from an+/// unavailable one, and only the harness can tell them apart.+pub fn record_read_failed(lane: &'static str, reason: &'static str) {+ counter!(+ "personhog_traffic_reads_total",+ "lane" => lane,+ "outcome" => "failed",+ "reason" => reason,+ )+ .increment(1);+}+/// Serve liveness + Prometheus metrics; runs for the process lifetime.pub fn spawn_server(port: u16) -> Result<()> {let router = Router::new().route("/_liveness", get(|| async { "ok" }));diff --git a/rust/personhog-writer/src/consumer.rs b/rust/personhog-writer/src/consumer.rsindex 3fa094c91206..697d56a2c18e 100644--- a/rust/personhog-writer/src/consumer.rs+++ b/rust/personhog-writer/src/consumer.rs@@ -177,7 +177,7 @@ impl ConsumerTask {self.handle.signal_failure("Writer task channel closed".to_string());}- histogram!("personhog_writer_channel_send_duration_seconds")- .record(start.elapsed().as_secs_f64());+ histogram!("personhog_writer_channel_send_duration_ms")+ .record(start.elapsed().as_secs_f64() * 1000.0);}}diff --git a/rust/personhog-writer/src/main.rs b/rust/personhog-writer/src/main.rsindex 3d473151664f..7443deefdb80 100644--- a/rust/personhog-writer/src/main.rs+++ b/rust/personhog-writer/src/main.rs@@ -3,7 +3,7 @@ use std::time::Duration;use axum::{routing::get, Router};use common_database::{get_pool_with_config, PoolConfig};-use common_metrics::setup_metrics_routes;+use common_metrics::{setup_metrics_routes_with_overrides, Matcher};use envconfig::Envconfig;use lifecycle::{ComponentOptions, Manager};use tokio::sync::mpsc;@@ -89,7 +89,20 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {}),).route("/_liveness", get(move || async move { liveness.check() }));- let metrics_router = setup_metrics_routes(health_router);+ // E2E latency is a lag detector: healthy produce-to-commit lag is+ // seconds (the flush cadence), and the interesting tail is minutes+ // of writer lag. The default buckets cap at 10s, which would+ // collapse every lag excursion into +Inf.+ let metrics_router = setup_metrics_routes_with_overrides(+ health_router,+ &[(+ Matcher::Full("personhog_writer_e2e_latency_ms".into()),+ &[+ 250.0, 1000.0, 2500.0, 5000.0, 10000.0, 30000.0, 60000.0, 120000.0, 300000.0,+ 600000.0,+ ],+ )],+ );let bind = format!("0.0.0.0:{metrics_port}");let listener = tokio::net::TcpListener::bind(&bind)diff --git a/rust/personhog-writer/src/store.rs b/rust/personhog-writer/src/store.rsindex bb140323ddfd..4139302a218b 100644--- a/rust/personhog-writer/src/store.rs+++ b/rust/personhog-writer/src/store.rs@@ -127,7 +127,8 @@ impl<D: PersonDb + 'static> PersonWriteStore<D> {self.run_parallel_chunks(chunks).await};- histogram!("personhog_writer_flush_duration_seconds").record(start.elapsed().as_secs_f64());+ histogram!("personhog_writer_flush_duration_ms")+ .record(start.elapsed().as_secs_f64() * 1000.0);histogram!("personhog_writer_flush_rows").record(total as f64);outcome}@@ -157,8 +158,8 @@ impl<D: PersonDb + 'static> PersonWriteStore<D> {.buffer_unordered(concurrency).collect().await;- histogram!("personhog_writer_row_fallback_duration_seconds")- .record(start.elapsed().as_secs_f64());+ histogram!("personhog_writer_row_fallback_duration_ms")+ .record(start.elapsed().as_secs_f64() * 1000.0);let mut outcome = RowFallbackOutcome::default();for (person, result) in results {diff --git a/rust/personhog-writer/src/writer.rs b/rust/personhog-writer/src/writer.rsindex 4f561319ce76..1dd8c1357951 100644--- a/rust/personhog-writer/src/writer.rs+++ b/rust/personhog-writer/src/writer.rs@@ -190,7 +190,7 @@ impl<D: PersonDb + 'static> WriterTask<D> {.unwrap_or_default().as_millis() as i64;let latency_ms = now_ms.saturating_sub(ts_ms);- histogram!("personhog_writer_e2e_latency_seconds").record(latency_ms as f64 / 1000.0);+ histogram!("personhog_writer_e2e_latency_ms").record(latency_ms as f64);}debug!(rows = rows_written, "flushed to store");