: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): path-labeled router forward metrics and stash occupancy latency gauges (#75786)
Zach Brownc910de5a303a
diff --git a/rust/personhog-router/README.md b/rust/personhog-router/README.mdindex b9b0a0c9bc30..675c4b11db96 100644--- a/rust/personhog-router/README.md+++ b/rust/personhog-router/README.md@@ -51,18 +51,19 @@ or address known yet — nothing sent), or a transport failure *bounces* with nooutcome. There is no blind inner retry layer; retry policy lives in exactlytwo places, both of which re-check routing state between attempts:-- **Live path** (`forward_or_stash`): a bounced request is held in its handler+- **Direct path** (`forward_or_stash`): a bounced request is held in its handlertask and the loop re-enters from the stash check after a short backoff — soby the re-attempt it parks if a handoff opened a stash window, re-resolves- if the table flipped, or re-sends if nothing changed. After a few- consecutive bounces it fails with a definitive `UNAVAILABLE` (a router with- a dead watch must not hold requests forever — the client's own retry can- reach a healthier router). A transport bounce marks the request- possibly-applied; any further forward of it is an at-least-once replay,- counted by `personhog_router_stash_replayed_total` and covered by the- redelivery contract in `personhog-leader`'s README. Clients never see- `FAILED_PRECONDITION` from the leader path.-- **Drain path**: the wave loop described below, with put-back for position+ if the table flipped, or re-sends if nothing changed. Each re-attempt is+ counted by `personhog_router_forward_retries_total` under the reason that+ caused it. After a few consecutive bounces it fails with a definitive+ `UNAVAILABLE`, counted by `personhog_router_forward_retries_exhausted_total`+ (a router with a dead watch must not hold requests forever — the client's+ own retry can reach a healthier router). A transport bounce marks the+ request possibly-applied; any further forward of it is an at-least-once+ replay, covered by the redelivery contract in `personhog-leader`'s README.+ Clients never see `FAILED_PRECONDITION` from the leader path.+- **Stash path**: the drain's wave loop described below, with put-back for positionand the reconcile pass as its outer driver.#### Stash and drain during partition handoffs@@ -133,9 +134,12 @@ client-visible error. The policies layered on the mechanism:fence: the owner resuming after a reaffirm, or the new owner'scutover), an unroutable target, or a transport failure (a podmid-restart or briefly unreachable) — puts the bounced request and- the rest of its key run back, backs off briefly, and retries; after- a few consecutive bounced waves the drain yields its lane and the- reconcile pass re-requests it on the next tick. Clients never see a+ the rest of its key run back (the interrupted attempt counts toward+ `personhog_router_forward_retries_total` as a stash-path retry under+ the reason that cut it short; the never-attempted tail goes back+ uncounted), backs off briefly, and retries; after a few consecutive+ bounced waves the drain yields its lane and the reconcile pass+ re-requests it on the next tick. Clients never see abounce — their requests stay parked until the condition clears orthe per-request deadline expires. A transport bounce marks therequest possibly-applied: re-forwarding it is an at-least-oncediff --git a/rust/personhog-router/src/backend/leader.rs b/rust/personhog-router/src/backend/leader.rsindex 80d31bf9da8f..a5686cf62cdd 100644--- a/rust/personhog-router/src/backend/leader.rs+++ b/rust/personhog-router/src/backend/leader.rs@@ -29,11 +29,11 @@ const LEADER_PREFIX: &str = "/personhog.leader.v1.PersonHogLeader/";/// Both bounce conditions clear on their own — a fence in/// watch-propagation time, a transport failure as the target pod comes/// up — so the cadence only needs to outpace the caller's latency bound,-/// not be aggressive. Shared by the live path's re-entrant retry loop+/// not be aggressive. Shared by the direct path's re-entrant retry loop/// and the drain's wave loop so the two paths settle at the same rate.pub(crate) const BOUNCE_BACKOFF: Duration = Duration::from_millis(150);-/// Consecutive bounces after which a retry loop gives up — the live path+/// Consecutive bounces after which a retry loop gives up — the direct path/// returns a definitive `UNAVAILABLE` (the client's own retry may reach/// a healthier router), the drain yields its lane to the reconcile pass.pub(crate) const MAX_CONSECUTIVE_BOUNCES: u32 = 4;@@ -69,6 +69,25 @@ impl BounceReason {}}+/// Which of the router's two forward paths issued a send: `Direct` for a+/// request forwarded from its own handler task, `Stash` for a parked+/// request forwarded by the drain. Carried as the `path` label on the+/// channel-call and retry metrics so the two paths read separately.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ForwardPath {+ Direct,+ Stash,+}++impl ForwardPath {+ pub fn label(self) -> &'static str {+ match self {+ ForwardPath::Direct => "direct",+ ForwardPath::Stash => "stash",+ }+ }+}+/// What one classified forward attempt concluded. `Delivered` covers/// every response the leader actually produced — success or error, it is/// a real outcome the caller must hand to the client (an error status@@ -195,14 +214,16 @@ impl LeaderBackend {/// round-trip time, used by the read path's network-overhead metric.////// Retry policy lives with the callers of `forward_classified`, both- /// of which re-check routing state between attempts: the live path's- /// re-entrant loop in `forward_or_stash` and the drain's wave loop.+ /// of which re-check routing state between attempts: the direct+ /// path's re-entrant loop in `forward_or_stash` and the stash path's+ /// drain wave loop./// A blind retry here would re-send without seeing a stash window/// that opened during the backoff, so this layer deliberately stays/// single-attempt.async fn send_frame(&self,mut channel: Channel,+ forward_path: ForwardPath,method: &'static str,partition: u32,headers: &HeaderMap,@@ -220,6 +241,7 @@ impl LeaderBackend {"method" => method,"client" => client.clone(),"outcome" => ready_outcome,+ "path" => forward_path.label(),).record(ready_start.elapsed().as_secs_f64() * 1000.0);let ready = ready_result@@ -245,6 +267,7 @@ impl LeaderBackend {"method" => method,"client" => client,"outcome" => call_outcome,+ "path" => forward_path.label(),).record(call_ms);let response =@@ -254,7 +277,7 @@ impl LeaderBackend {/// One classified forward attempt: resolve the target, send the/// frame, and decide what the result means. This is the single- /// shared reading of leader responses — the live path's retry loop+ /// shared reading of leader responses — the direct path's retry loop/// and the drain's wave loop both build on it, so the two paths can/// never drift in how they interpret the same response.///@@ -264,6 +287,7 @@ impl LeaderBackend {/// transport failure's is.pub async fn forward_classified(&self,+ forward_path: ForwardPath,method: &'static str,partition: u32,headers: &HeaderMap,@@ -274,7 +298,7 @@ impl LeaderBackend {Err(_status) => return ForwardDecision::Bounced(BounceReason::Unrouted),};match self- .send_frame(channel, method, partition, headers, frame)+ .send_frame(channel, forward_path, method, partition, headers, frame).await{// Every leader use of FailedPrecondition is a routing-race@@ -312,17 +336,19 @@ impl LeaderBackend {/// holds: a stash window opened (the request parks and rides the/// handoff — the race becomes the normal path), the table flipped/// (the re-resolve targets the new owner), or nothing changed yet- /// (re-send, possibly bounce again). After `MAX_CONSECUTIVE_BOUNCES`- /// the request fails with a definitive `UNAVAILABLE`, so a router+ /// (re-send, possibly bounce again). Each re-attempt is counted by+ /// `personhog_router_forward_retries_total` under the reason that+ /// caused it. After `MAX_CONSECUTIVE_BOUNCES` the request fails with+ /// a definitive `UNAVAILABLE`, counted by+ /// `personhog_router_forward_retries_exhausted_total`, so a router/// whose view never updates (a dead watch) can't hold requests/// forever — the client's own retry may land on a healthy router.////// A transport bounce marks the request possibly-applied: the leader/// may have processed it without us seeing the response, so any/// further forward — here or by the drain if it parks — is an- /// at-least-once replay, counted by- /// `personhog_router_stash_replayed_total` and covered by the- /// redelivery contract in `personhog-leader`'s README.+ /// at-least-once replay, covered by the redelivery contract in+ /// `personhog-leader`'s README.pub async fn forward_or_stash(&self,method: &'static str,@@ -364,11 +390,8 @@ impl LeaderBackend {StashDecision::Forward => {}}- if possibly_applied {- counter!("personhog_router_stash_replayed_total").increment(1);- }match self- .forward_classified(method, partition, &headers, &frame)+ .forward_classified(ForwardPath::Direct, method, partition, &headers, &frame).await{ForwardDecision::Delivered { response, call_ms } => {@@ -378,13 +401,9 @@ impl LeaderBackend {if reason == BounceReason::Transport {possibly_applied = true;}- counter!(- "personhog_router_forward_bounced_total",- "reason" => reason.label()- )- .increment(1);consecutive_bounces += 1;if consecutive_bounces >= MAX_CONSECUTIVE_BOUNCES {+ counter!("personhog_router_forward_retries_exhausted_total").increment(1);return (grpc_error_response(Code::Unavailable,@@ -393,6 +412,12 @@ impl LeaderBackend {None,);}+ counter!(+ "personhog_router_forward_retries_total",+ "path" => ForwardPath::Direct.label(),+ "reason" => reason.label()+ )+ .increment(1);tokio::time::sleep(BOUNCE_BACKOFF).await;}}diff --git a/rust/personhog-router/src/backend/mod.rs b/rust/personhog-router/src/backend/mod.rsindex 8a24abd0cc75..66ddc4ea128b 100644--- a/rust/personhog-router/src/backend/mod.rs+++ b/rust/personhog-router/src/backend/mod.rs@@ -4,7 +4,7 @@ mod replica;mod stash;pub use leader::{- AddressResolver, BounceReason, ForwardDecision, LeaderBackend, LeaderBackendConfig,+ AddressResolver, BounceReason, ForwardDecision, ForwardPath, LeaderBackend, LeaderBackendConfig,};pub(crate) use leader::{BOUNCE_BACKOFF, MAX_CONSECUTIVE_BOUNCES};pub use replica::{ReplicaBackend, ReplicaDnsConfig};diff --git a/rust/personhog-router/src/backend/stash.rs b/rust/personhog-router/src/backend/stash.rsindex fbfa0b84becb..dd7843318ca0 100644--- a/rust/personhog-router/src/backend/stash.rs+++ b/rust/personhog-router/src/backend/stash.rs@@ -242,7 +242,7 @@ impl StashTable {/// progress) returns `Forward` from the dashmap miss without copying/// anything.///- /// `possibly_applied` carries the live path's transport-failure mark+ /// `possibly_applied` carries the direct path's transport-failure mark/// into the parked entry: a request that bounced at the transport/// layer before parking may already have reached the leader, and the/// drain's eventual re-forward of it must count as a replay.@@ -303,6 +303,10 @@ impl StashTable {queue.messages += 1;queue.bytes += request_size;metrics::counter!("personhog_router_stash_enqueued_total").increment(1);+ // Occupancy gauges count a parked entry until its outcome+ // resolves, so in-attempt entries still occupy capacity.+ metrics::gauge!("personhog_router_stash_queued_messages").increment(1.0);+ metrics::gauge!("personhog_router_stash_queued_bytes").increment(request_size as f64);StashDecision::Stashed(rx)}@@ -395,6 +399,8 @@ impl DrainSession {q.queue.complete(&key);q.messages -= 1;q.bytes = q.bytes.saturating_sub(size);+ metrics::gauge!("personhog_router_stash_queued_messages").decrement(1.0);+ metrics::gauge!("personhog_router_stash_queued_bytes").decrement(size as f64);}/// Return in-attempt entries whose delivery was aborted before any@@ -918,7 +924,7 @@ mod tests {// created a fresh one). If begin_stash logically ran first// (observed the prior `Some` queue, was idempotent), then// the drain legitimately drained that prior queue and a- // subsequent enqueue forwards via the live path — that's a+ // subsequent enqueue forwards via the direct path — that's a// protocol-violation scenario, not a stash-module bug, and// the routing-table layer prevents it. We accept either// outcome here; what we *don't* accept is a non-emptydiff --git a/rust/personhog-router/src/stash_handler.rs b/rust/personhog-router/src/stash_handler.rsindex bdf8478224c4..e5f5b777fa80 100644--- a/rust/personhog-router/src/stash_handler.rs+++ b/rust/personhog-router/src/stash_handler.rs@@ -11,8 +11,8 @@ use tokio_util::sync::CancellationToken;use tonic::Code;use crate::backend::{- BounceReason, DrainSession, ForwardDecision, LeaderBackend, StashKey, StashedRequest,- TakenKeyRun, BOUNCE_BACKOFF, MAX_CONSECUTIVE_BOUNCES,+ BounceReason, DrainSession, ForwardDecision, ForwardPath, LeaderBackend, StashKey,+ StashedRequest, TakenKeyRun, BOUNCE_BACKOFF, MAX_CONSECUTIVE_BOUNCES,};use crate::grpc_http::{grpc_error_response, is_grpc_error_response};@@ -57,7 +57,7 @@ use crate::grpc_http::{grpc_error_response, is_grpc_error_response};////// 3. **Bounce and retry.** A classified forward attempt (see/// `LeaderBackend::forward_classified`, the single reading of leader-/// responses shared with the live path) can conclude no outcome+/// responses shared with the direct path) can conclude no outcome/// exists: a `FailedPrecondition` from the target (its fence or/// ownership is still settling — a reaffirm's drain racing the/// owner's resume, or a completion's drain racing the new owner's@@ -133,7 +133,7 @@ enum Disposition {/// `UNAVAILABLE` so the client retries with a fresh request rather than/// waiting out a response that may exceed its gRPC timeout. Otherwise/// the attempt is one classified forward — the same shared reading of-/// leader responses the live path uses (see+/// leader responses the direct path uses (see/// `LeaderBackend::forward_classified`), so the two paths cannot drift/// in what counts as an outcome versus a bounce.async fn forward_one(@@ -159,7 +159,13 @@ async fn forward_one(// stamps `x-partition` and the leader serializes per key, so replaying// here preserves arrival order without re-entering the stash.match leader_backend- .forward_classified(req.method, partition, &req.headers, &req.frame)+ .forward_classified(+ ForwardPath::Stash,+ req.method,+ partition,+ &req.headers,+ &req.frame,+ ).await{ForwardDecision::Delivered { response, .. } => {@@ -183,21 +189,17 @@ struct KeyRunOutcome {/// Put an interrupted key run's remainder back at its admission/// positions: the entry whose attempt was cut short plus everything not-/// yet attempted.+/// yet attempted. Retry accounting stays with the callers — only an+/// actually-attempted head counts as a stash-path retry, so the+/// never-attempted tail goes back uncounted.async fn put_back_rest(session: &DrainSession,key: StashKey,head: Entry<StashedRequest>,rest: IntoIter<Entry<StashedRequest>>,- reason: &'static str,) {let mut entries = vec![head];entries.extend(rest);- metrics::counter!(- "personhog_router_stash_put_back_total",- "reason" => reason- )- .increment(entries.len() as u64);session.put_back(key, entries).await;}@@ -219,7 +221,7 @@ async fn forward_key_run(let mut entries = run.entries.into_iter();while let Some(mut entry) = entries.next() {if cancel.is_cancelled() {- put_back_rest(session, run.key, entry, entries, "cancelled").await;+ put_back_rest(session, run.key, entry, entries).await;return outcome;}// Race the forward against cancellation: an in-flight call can@@ -237,7 +239,13 @@ async fn forward_key_run(// outcome is unknown — same ambiguity as a transport bounce,// same conservative marking.entry.item.possibly_applied = true;- put_back_rest(session, run.key, entry, entries, "cancelled").await;+ metrics::counter!(+ "personhog_router_forward_retries_total",+ "path" => ForwardPath::Stash.label(),+ "reason" => "cancelled"+ )+ .increment(1);+ put_back_rest(session, run.key, entry, entries).await;return outcome;};match disposition {@@ -249,7 +257,11 @@ async fn forward_key_run(metrics::histogram!("personhog_router_stash_wait_duration_ms").record(entry.item.enqueued_at.elapsed().as_secs_f64() * 1000.0);if entry.item.reply.send(response).is_err() {- metrics::counter!("personhog_router_stash_dropped_total").increment(1);+ metrics::counter!(+ "personhog_router_stash_dropped_total",+ "reason" => "receiver_gone"+ )+ .increment(1);}metrics::counter!("personhog_router_stash_drained_total",@@ -263,7 +275,13 @@ async fn forward_key_run(if matches!(reason, BounceReason::Transport) {entry.item.possibly_applied = true;}- put_back_rest(session, run.key, entry, entries, reason.label()).await;+ metrics::counter!(+ "personhog_router_forward_retries_total",+ "path" => ForwardPath::Stash.label(),+ "reason" => reason.label()+ )+ .increment(1);+ put_back_rest(session, run.key, entry, entries).await;outcome.bounced = true;return outcome;}