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.

fix(personhog): retry a shed call on another pod (#103120)

Zach Brownfe5e40a8f006
diff --git a/rust/personhog-common/src/grpc.rs b/rust/personhog-common/src/grpc.rs
index eee4bcb1d4f7..e31fce12313a 100644
--- a/rust/personhog-common/src/grpc.rs
+++ b/rust/personhog-common/src/grpc.rs
@@ -34,6 +34,9 @@ pub const CLIENT_NAME_HEADER: &str = "x-client-name";
/// observability.
pub const SEMANTIC_REFUSAL_METADATA_KEY: &str = "x-semantic-refusal";
+/// Never set where the request may have been applied.
+pub const NOT_APPLIED_HEADER: &str = "x-not-applied";
+
/// Build a semantic refusal. The reason is a short slug used as a metric
/// label.
pub fn semantic_refusal(message: impl Into<String>, reason: &'static str) -> tonic::Status {
@@ -582,6 +585,7 @@ where
.header("content-type", "application/grpc")
.header("grpc-status", "14") // UNAVAILABLE
.header("grpc-message", "Server at capacity")
+ .header(NOT_APPLIED_HEADER, "load_shed")
.body(ResBody::default())
.unwrap();
@@ -736,6 +740,7 @@ mod tests {
resp.headers().get("grpc-message").unwrap(),
"Server at capacity"
);
+ assert_eq!(resp.headers().get(NOT_APPLIED_HEADER).unwrap(), "load_shed");
// Shed path: increment then immediate decrement, net zero change
assert_eq!(in_flight.load(Ordering::Relaxed), 2);
}
diff --git a/rust/personhog-router/src/grpc_http.rs b/rust/personhog-router/src/grpc_http.rs
index 55eb393407ca..d5ad53d35890 100644
--- a/rust/personhog-router/src/grpc_http.rs
+++ b/rust/personhog-router/src/grpc_http.rs
@@ -5,6 +5,7 @@
use bytes::Bytes;
use http::HeaderValue;
use http_body_util::{BodyExt, Empty};
+use personhog_common::grpc::NOT_APPLIED_HEADER;
use tonic::body::BoxBody;
use tonic::Code;
@@ -52,6 +53,27 @@ pub(crate) fn grpc_status_code(response: &http::Response<BoxBody>) -> Option<i32
.and_then(|s| s.parse::<i32>().ok())
}
+/// Any other status may have applied the call. The slug is bounded for the label.
+pub(crate) fn unapplied_refusal_reason(response: &http::Response<BoxBody>) -> Option<&str> {
+ if grpc_status_code(response) != Some(Code::Unavailable as i32) {
+ return None;
+ }
+ response
+ .headers()
+ .get(NOT_APPLIED_HEADER)
+ .and_then(|v| v.to_str().ok())
+ .map(|r| {
+ if r.len() <= 64
+ && r.chars()
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
+ {
+ r
+ } else {
+ "unknown"
+ }
+ })
+}
+
/// Percent-encode a gRPC status message so it is safe to carry in the
/// ASCII-only `grpc-message` header.
fn percent_encode_grpc(s: &str) -> String {
@@ -88,6 +110,37 @@ mod tests {
)));
}
+ #[test]
+ fn only_a_marked_unavailable_reads_as_unapplied() {
+ let marked = |code| {
+ let mut r = grpc_error_response(code, "Server at capacity");
+ r.headers_mut()
+ .insert(NOT_APPLIED_HEADER, HeaderValue::from_static("load_shed"));
+ r
+ };
+ assert_eq!(
+ unapplied_refusal_reason(&marked(Code::Unavailable)),
+ Some("load_shed")
+ );
+ assert_eq!(unapplied_refusal_reason(&marked(Code::Ok)), None);
+ assert_eq!(unapplied_refusal_reason(&marked(Code::Internal)), None);
+ assert_eq!(
+ unapplied_refusal_reason(&grpc_error_response(
+ Code::Unavailable,
+ "Database pool exhausted"
+ )),
+ None
+ );
+ }
+
+ #[test]
+ fn an_unsafe_reason_slug_falls_back() {
+ let mut resp = grpc_error_response(Code::Unavailable, "shed");
+ resp.headers_mut()
+ .insert(NOT_APPLIED_HEADER, HeaderValue::from_static("a b/c"));
+ assert_eq!(unapplied_refusal_reason(&resp), Some("unknown"));
+ }
+
#[test]
fn grpc_error_response_sets_status_and_message() {
let response = grpc_error_response(Code::NotFound, "person not found");
diff --git a/rust/personhog-router/src/proxy.rs b/rust/personhog-router/src/proxy.rs
index c426d520cce2..fba76aedaacc 100644
--- a/rust/personhog-router/src/proxy.rs
+++ b/rust/personhog-router/src/proxy.rs
@@ -19,7 +19,9 @@ use tower::{Service, ServiceExt};
use crate::backend::{ChannelBackend, LeaderBackend};
use crate::config::RetryConfig;
-use crate::grpc_http::{grpc_error_response, grpc_status_code, is_grpc_error_response};
+use crate::grpc_http::{
+ grpc_error_response, grpc_status_code, is_grpc_error_response, unapplied_refusal_reason,
+};
const SERVICE_PREFIX: &str = "/personhog.service.v1.PersonHogService/";
const REPLICA_PREFIX: &str = "/personhog.replica.v1.PersonHogReplica/";
@@ -511,13 +513,28 @@ impl RawProxyInner {
match ready_channel.call(req).await {
Ok(response) => {
let channel_call_ms = call_start.elapsed().as_secs_f64() * 1000.0;
+ let unapplied = unapplied_refusal_reason(&response).map(str::to_owned);
histogram!(
"personhog_router_channel_call_ms",
"method" => method.clone(),
"client" => client.clone(),
- "outcome" => "ok",
+ "outcome" => if unapplied.is_some() { "refused" } else { "ok" },
)
.record(channel_call_ms);
+ if let (Some(reason), true) =
+ (unapplied, attempt < self.retry_config.max_retries)
+ {
+ counter!(
+ "personhog_router_unapplied_retries_total",
+ "method" => method.clone(),
+ "client" => client.clone(),
+ "reason" => reason,
+ )
+ .increment(1);
+ // The balancer re-picks an endpoint per request.
+ retry_backoff(&mut delay_ms, &self.retry_config, &method, &client).await;
+ continue;
+ }
return (response, Some(channel_call_ms));
}
Err(e) => {
diff --git a/rust/personhog-router/tests/common/mod.rs b/rust/personhog-router/tests/common/mod.rs
index 196f35157ace..03d33bda3e29 100644
--- a/rust/personhog-router/tests/common/mod.rs
+++ b/rust/personhog-router/tests/common/mod.rs
@@ -2,12 +2,13 @@
use std::collections::HashMap;
use std::net::SocketAddr;
-use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use dashmap::DashMap;
use personhog_common::async_gzip::{AsyncGzipConfig, AsyncGzipLayer};
+use personhog_common::grpc::NOT_APPLIED_HEADER;
use personhog_proto::personhog::identity::v1 as identity;
use personhog_proto::personhog::identity::v1::person_hog_identity_server::{
PersonHogIdentity, PersonHogIdentityServer,
@@ -79,6 +80,8 @@ pub struct TestReplicaService {
pub upsert_inserted_count: i64,
pub groups: Vec<Group>,
pub group_type_mappings: Vec<GroupTypeMapping>,
+ pub sheds_remaining: Arc<AtomicUsize>,
+ pub calls: Arc<AtomicUsize>,
}
impl TestReplicaService {
@@ -91,9 +94,16 @@ impl TestReplicaService {
upsert_inserted_count: 0,
groups: vec![],
group_type_mappings: vec![],
+ sheds_remaining: Arc::new(AtomicUsize::new(0)),
+ calls: Arc::new(AtomicUsize::new(0)),
}
}
+ pub fn sheds(mut self, n: usize) -> Self {
+ self.sheds_remaining = Arc::new(AtomicUsize::new(n));
+ self
+ }
+
pub fn with_person(person: Person) -> Self {
Self {
person: Some(person),
@@ -141,6 +151,18 @@ impl PersonHogReplica for TestReplicaService {
&self,
_request: Request<GetPersonRequest>,
) -> Result<Response<GetPersonResponse>, Status> {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ if self
+ .sheds_remaining
+ .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1))
+ .is_ok()
+ {
+ let mut status = Status::unavailable("Server at capacity");
+ status
+ .metadata_mut()
+ .insert(NOT_APPLIED_HEADER, "load_shed".parse().unwrap());
+ return Err(status);
+ }
Ok(Response::new(GetPersonResponse {
person: self.person.clone(),
}))
diff --git a/rust/personhog-router/tests/raw_proxy_integration.rs b/rust/personhog-router/tests/raw_proxy_integration.rs
index a2a59c2c2028..67d438e36e84 100644
--- a/rust/personhog-router/tests/raw_proxy_integration.rs
+++ b/rust/personhog-router/tests/raw_proxy_integration.rs
@@ -1,5 +1,6 @@
mod common;
+use std::sync::atomic::Ordering;
use std::sync::{Arc, Mutex};
use common::{
@@ -76,6 +77,57 @@ async fn raw_proxy_eventual_get_person_routes_to_replica() {
assert_eq!(response.into_inner().person.unwrap().id, test_person.id);
}
+#[tokio::test]
+async fn raw_proxy_retries_a_shed_onto_a_later_attempt() {
+ let test_person = create_test_person();
+ let replica_service = TestReplicaService::with_person(test_person.clone()).sheds(1);
+ let calls = replica_service.calls.clone();
+
+ let replica_addr = start_test_replica(replica_service).await;
+ let router_addr = start_test_router_raw(replica_addr).await;
+ let mut client = create_client(router_addr).await;
+
+ let response = client
+ .get_person(with_consistency(
+ GetPersonRequest {
+ team_id: 1,
+ person_id: 42,
+ read_options: None,
+ },
+ "eventual",
+ ))
+ .await
+ .expect("a shed must not surface to the caller");
+
+ assert_eq!(response.into_inner().person.unwrap().id, test_person.id);
+ assert_eq!(calls.load(Ordering::SeqCst), 2, "the shed was not retried");
+}
+
+#[tokio::test]
+async fn raw_proxy_returns_a_persistent_shed_after_the_budget() {
+ let replica_service = TestReplicaService::with_person(create_test_person()).sheds(usize::MAX);
+ let calls = replica_service.calls.clone();
+
+ let replica_addr = start_test_replica(replica_service).await;
+ let router_addr = start_test_router_raw(replica_addr).await;
+ let mut client = create_client(router_addr).await;
+
+ let status = client
+ .get_person(with_consistency(
+ GetPersonRequest {
+ team_id: 1,
+ person_id: 42,
+ read_options: None,
+ },
+ "eventual",
+ ))
+ .await
+ .expect_err("an exhausted retry budget must surface the refusal");
+
+ assert_eq!(status.code(), tonic::Code::Unavailable);
+ assert_eq!(calls.load(Ordering::SeqCst), 2, "the budget was not spent");
+}
+
#[tokio::test]
async fn raw_proxy_get_person_default_routes_to_replica() {
let test_person = create_test_person();