: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): extract x-caller-tag header in router (#60361)
Nick Best7fbc6a232782
diff --git a/rust/personhog-common/src/grpc.rs b/rust/personhog-common/src/grpc.rsindex e99f0dbab1fc..4b3ec72acfd4 100644--- a/rust/personhog-common/src/grpc.rs+++ b/rust/personhog-common/src/grpc.rs@@ -23,10 +23,19 @@ use tower::{Layer, Service};/// Header name for client identification in gRPC metadata.const CLIENT_NAME_HEADER: &str = "x-client-name";+/// Header name for caller-tag attribution in gRPC metadata.+/// Identifies the code path / feature area within a service that+/// triggered the request (e.g., "api/feature-flags", "celery/cohort-calculation").+const CALLER_TAG_HEADER: &str = "x-caller-tag";+tokio::task_local! {/// Per-request client name, set by `GrpcMetricsLayer` and readable/// anywhere in the request's async call chain via `current_client_name()`.pub static CLIENT_NAME: Arc<str>;++ /// Per-request caller tag, set by `GrpcMetricsLayer` and readable+ /// anywhere in the request's async call chain via `current_caller_tag()`.+ pub static CALLER_TAG: Arc<str>;}/// Get the current client name from the task-local, or `"unknown"` if not set.@@ -38,17 +47,51 @@ pub fn current_client_name() -> Arc<str> {.unwrap_or_else(|_| Arc::from("unknown"))}-/// Extract the client name from HTTP headers, defaulting to `"unknown"`.-fn extract_client_name<B>(request: &Request<B>) -> Arc<str> {+/// Get the current caller tag from the task-local, or `"unknown"` if not set.+pub fn current_caller_tag() -> Arc<str> {+ CALLER_TAG+ .try_with(|t| t.clone())+ .unwrap_or_else(|_| Arc::from("unknown"))+}++const MAX_HEADER_TAG_LEN: usize = 128;++fn is_safe_tag_char(c: char) -> bool {+ c.is_ascii_alphanumeric() || matches!(c, '/' | '_' | '-' | ':' | '.')+}++fn sanitize_header_tag(raw: &str) -> &str {+ let s = if raw.len() > MAX_HEADER_TAG_LEN {+ &raw[..MAX_HEADER_TAG_LEN]+ } else {+ raw+ };+ if s.chars().all(is_safe_tag_char) {+ s+ } else {+ "unknown"+ }+}++fn extract_sanitized_header<B>(request: &Request<B>, header: &str) -> Arc<str> {request.headers()- .get(CLIENT_NAME_HEADER)+ .get(header).and_then(|v| v.to_str().ok()).filter(|s| !s.is_empty())+ .map(sanitize_header_tag).unwrap_or("unknown").into()}+fn extract_client_name<B>(request: &Request<B>) -> Arc<str> {+ extract_sanitized_header(request, CLIENT_NAME_HEADER)+}++fn extract_caller_tag<B>(request: &Request<B>) -> Arc<str> {+ extract_sanitized_header(request, CALLER_TAG_HEADER)+}+// ============================================================// Connection tracking// ============================================================@@ -257,15 +300,19 @@ wherefn call(&mut self, request: Request<ReqBody>) -> Self::Future {let method = extract_grpc_method(request.uri().path());let client = extract_client_name(&request);+ let caller_tag = extract_caller_tag(&request);gauge!("grpc_server_requests_in_flight", "method" => method.clone(), "client" => client.clone()).increment(1.0);let start = Instant::now();- // Call inner inside the scope so any synchronous work in call() sees CLIENT_NAME.- let inner = CLIENT_NAME.sync_scope(client.clone(), || self.inner.call(request));+ // Call inner inside both scopes so any synchronous work in call()+ // sees CLIENT_NAME and CALLER_TAG.+ let inner = CLIENT_NAME.sync_scope(client.clone(), || {+ CALLER_TAG.sync_scope(caller_tag.clone(), || self.inner.call(request))+ });GrpcMetricsFuture {- inner: CLIENT_NAME.scope(client.clone(), inner),+ inner: CLIENT_NAME.scope(client.clone(), CALLER_TAG.scope(caller_tag, inner)),method,client,start,@@ -276,14 +323,14 @@ where/// Future returned by [`GrpcMetricsService`].///-/// Wraps the inner service future with task-local client name propagation-/// and records request metrics (counter, histogram, in-flight gauge) on-/// completion or cancellation. Lives inline in the caller's async state-/// machine — no heap allocation or dynamic dispatch.+/// Wraps the inner service future with task-local client name and caller tag+/// propagation, and records request metrics (counter, histogram, in-flight+/// gauge) on completion or cancellation. Lives inline in the caller's async+/// state machine — no heap allocation or dynamic dispatch.#[pin_project(PinnedDrop)]pub struct GrpcMetricsFuture<F> {#[pin]- inner: TaskLocalFuture<Arc<str>, F>,+ inner: TaskLocalFuture<Arc<str>, TaskLocalFuture<Arc<str>, F>>,method: String,client: Arc<str>,start: Instant,@@ -639,4 +686,94 @@ mod tests {assert_eq!(extract_grpc_method("/"), "unknown");assert_eq!(extract_grpc_method(""), "unknown");}++ #[test]+ fn extract_caller_tag_from_headers() {+ let req = Request::builder()+ .uri("/pkg.Svc/Method")+ .header("x-caller-tag", "api/feature-flags")+ .body(())+ .unwrap();+ assert_eq!(&*extract_caller_tag(&req), "api/feature-flags");+ }++ #[test]+ fn extract_caller_tag_defaults_to_unknown() {+ let req = Request::builder().uri("/pkg.Svc/Method").body(()).unwrap();+ assert_eq!(&*extract_caller_tag(&req), "unknown");+ }++ #[test]+ fn extract_caller_tag_treats_empty_as_unknown() {+ let req = Request::builder()+ .uri("/pkg.Svc/Method")+ .header("x-caller-tag", "")+ .body(())+ .unwrap();+ assert_eq!(&*extract_caller_tag(&req), "unknown");+ }++ #[test]+ fn current_caller_tag_defaults_outside_scope() {+ assert_eq!(&*current_caller_tag(), "unknown");+ }++ #[test]+ fn extract_caller_tag_truncates_long_value() {+ let long_tag = "a".repeat(200);+ let req = Request::builder()+ .uri("/pkg.Svc/Method")+ .header("x-caller-tag", &long_tag)+ .body(())+ .unwrap();+ assert_eq!(extract_caller_tag(&req).len(), MAX_HEADER_TAG_LEN);+ }++ #[test]+ fn extract_caller_tag_rejects_unsafe_chars() {+ let req = Request::builder()+ .uri("/pkg.Svc/Method")+ .header("x-caller-tag", "bad tag with spaces!")+ .body(())+ .unwrap();+ assert_eq!(&*extract_caller_tag(&req), "unknown");+ }++ #[test]+ fn extract_client_name_truncates_long_value() {+ let long_name = "b".repeat(200);+ let req = Request::builder()+ .uri("/pkg.Svc/Method")+ .header("x-client-name", &long_name)+ .body(())+ .unwrap();+ assert_eq!(extract_client_name(&req).len(), MAX_HEADER_TAG_LEN);+ }++ #[test]+ fn extract_client_name_rejects_unsafe_chars() {+ let req = Request::builder()+ .uri("/pkg.Svc/Method")+ .header("x-client-name", "bad name!")+ .body(())+ .unwrap();+ assert_eq!(&*extract_client_name(&req), "unknown");+ }++ #[test]+ fn sanitize_allows_valid_tag_chars() {+ assert_eq!(+ sanitize_header_tag("api/feature-flags"),+ "api/feature-flags"+ );+ assert_eq!(+ sanitize_header_tag("celery/calculate_cohort_ch"),+ "celery/calculate_cohort_ch"+ );+ assert_eq!(+ sanitize_header_tag("posthog-django-web"),+ "posthog-django-web"+ );+ assert_eq!(sanitize_header_tag("some:tag.v1"), "some:tag.v1");+ }}diff --git a/rust/personhog-router/src/backend/leader.rs b/rust/personhog-router/src/backend/leader.rsindex 1bcdf3464066..1771e3d5605d 100644--- a/rust/personhog-router/src/backend/leader.rs+++ b/rust/personhog-router/src/backend/leader.rs@@ -15,7 +15,7 @@ use tonic::codec::CompressionEncoding;use tonic::transport::Channel;use tonic::{Request, Status};-use personhog_common::grpc::current_client_name;+use personhog_common::grpc::{current_caller_tag, current_client_name};use super::retry::with_retry;use super::stash::{StashDecision, StashTable};@@ -207,12 +207,16 @@ impl LeaderOps for LeaderBackend {let client_fut = self.resolve_leader(partition);let req = leader_req;let client_name = current_client_name();+ let caller_tag = current_caller_tag();async move {let mut client = client_fut.await?;let mut request = Request::new(req);if let Ok(val) = client_name.parse() {request.metadata_mut().insert("x-client-name", val);}+ if let Ok(val) = caller_tag.parse() {+ request.metadata_mut().insert("x-caller-tag", val);+ }client.get_person(request).await.map(|r| r.into_inner())}})@@ -301,12 +305,16 @@ impl LeaderBackend {let client_fut = self.resolve_leader(partition);let req = request.clone();let client_name = current_client_name();+ let caller_tag = current_caller_tag();async move {let mut client = client_fut.await?;let mut request = Request::new(req);if let Ok(val) = client_name.parse() {request.metadata_mut().insert("x-client-name", val);}+ if let Ok(val) = caller_tag.parse() {+ request.metadata_mut().insert("x-caller-tag", val);+ }client.update_person_properties(request).awaitdiff --git a/rust/personhog-router/src/backend/replica.rs b/rust/personhog-router/src/backend/replica.rsindex 692543a3ca5a..98ec8260b448 100644--- a/rust/personhog-router/src/backend/replica.rs+++ b/rust/personhog-router/src/backend/replica.rs@@ -32,7 +32,7 @@ use tonic::transport::{Channel, Endpoint};use tonic::{Request, Status};use tracing::info;-use personhog_common::grpc::current_client_name;+use personhog_common::grpc::{current_caller_tag, current_client_name};use super::retry::with_retry;use super::PersonHogBackend;@@ -216,8 +216,8 @@ impl ReplicaBackend {}/// Wraps a gRPC call with retry logic. Clones the request for each attempt.-/// Forwards the `x-client-name` header so the downstream service can-/// attribute metrics to the originating client.+/// Forwards `x-client-name` and `x-caller-tag` headers so the downstream+/// service can attribute metrics to the originating client and code path.////// The `$client_fn` parameter selects the channel pool: `next_heavy_client`/// for RPCs returning large Person/Group payloads, `next_light_client` for@@ -228,11 +228,15 @@ macro_rules! retry_call {let mut client = $self.$client_fn();let req = $request.clone();let client_name = current_client_name();+ let caller_tag = current_caller_tag();async move {let mut request = Request::new(req);if let Ok(val) = client_name.parse() {request.metadata_mut().insert("x-client-name", val);}+ if let Ok(val) = caller_tag.parse() {+ request.metadata_mut().insert("x-caller-tag", val);+ }client.$method(request).await.map(|r| r.into_inner())}})diff --git a/rust/personhog-router/src/config.rs b/rust/personhog-router/src/config.rsindex 02000a169c1f..f17dc463044d 100644--- a/rust/personhog-router/src/config.rs+++ b/rust/personhog-router/src/config.rs@@ -147,6 +147,11 @@ pub struct Config {#[envconfig(default = "134217728")]pub grpc_max_recv_message_size: usize,+ /// Log a warning when a gRPC response exceeds this size in bytes.+ /// Set to 0 to disable. Default: 10 MiB.+ #[envconfig(default = "10485760")]+ pub response_size_warn_bytes: usize,+// ── etcd coordination (leader mode only) ─────────────────────#[envconfig(default = "http://localhost:2379")]pub etcd_endpoints: String,diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rsindex b5972a571702..123bdacff454 100644--- a/rust/personhog-router/src/main.rs+++ b/rust/personhog-router/src/main.rs@@ -315,8 +315,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {let incoming = tracked_tcp_incoming(listener);let result = if proxy_mode == ProxyMode::Raw {- let proxy =- RawProxyService::new(replica_backend, leader_backend, retry_config, max_recv);+ let proxy = RawProxyService::new(+ replica_backend,+ leader_backend,+ retry_config,+ max_recv,+ config.response_size_warn_bytes,+ );Server::builder().http2_keepalive_interval(keepalive_interval).http2_keepalive_timeout(keepalive_timeout)diff --git a/rust/personhog-router/src/proxy.rs b/rust/personhog-router/src/proxy.rsindex b8f7c04f9f2a..056d8802b170 100644--- a/rust/personhog-router/src/proxy.rs+++ b/rust/personhog-router/src/proxy.rs@@ -9,7 +9,9 @@ use http::{HeaderMap, HeaderValue};use http_body::Frame;use http_body_util::{BodyExt, Empty, Full};use metrics::{counter, histogram};-use personhog_common::grpc::{current_client_name, ClientInFlightGuard, PROCESSING_TIME_HEADER};+use personhog_common::grpc::{+ current_caller_tag, current_client_name, ClientInFlightGuard, PROCESSING_TIME_HEADER,+};use personhog_proto::personhog::types::v1::{GetPersonRequest, UpdatePersonPropertiesRequest};use prost::Message;use rand::Rng;@@ -75,6 +77,7 @@ struct RawProxyInner {leader: Option<Arc<LeaderBackend>>,retry_config: RetryConfig,max_recv_message_size: usize,+ response_size_warn_bytes: usize,}impl RawProxyService {@@ -83,6 +86,7 @@ impl RawProxyService {leader: Option<Arc<LeaderBackend>>,retry_config: RetryConfig,max_recv_message_size: usize,+ response_size_warn_bytes: usize,) -> Self {Self {inner: Arc::new(RawProxyInner {@@ -90,6 +94,7 @@ impl RawProxyService {leader,retry_config,max_recv_message_size,+ response_size_warn_bytes,}),}}@@ -142,6 +147,7 @@ impl RawProxyInner {let method = method_name.to_string();let client = current_client_name();+ let caller_tag = current_caller_tag();let start = Instant::now();let (mut response, backend) = match method_name {@@ -177,6 +183,7 @@ impl RawProxyInner {"method" => method.clone(),"backend" => backend,"client" => client.clone(),+ "caller_tag" => caller_tag.clone(),).record(duration_ms);@@ -207,7 +214,14 @@ impl RawProxyInner {}let (parts, body) = response.into_parts();- let counted = ByteCountedBody::new(body, method, backend, client);+ let counted = ByteCountedBody::new(+ body,+ method,+ backend,+ client,+ caller_tag,+ self.response_size_warn_bytes,+ );http::Response::from_parts(parts, BoxBody::new(counted))}@@ -466,23 +480,35 @@ fn percent_encode_grpc(s: &str) -> String {}/// Response body wrapper that counts bytes from DATA frames and records-/// the total to a histogram on drop.+/// the total to a histogram on drop. Emits a structured warning when the+/// response exceeds `warn_threshold` bytes.struct ByteCountedBody {inner: BoxBody,bytes_counted: usize,method: String,backend: &'static str,client: Arc<str>,+ caller_tag: Arc<str>,+ warn_threshold: usize,}impl ByteCountedBody {- fn new(inner: BoxBody, method: String, backend: &'static str, client: Arc<str>) -> Self {+ fn new(+ inner: BoxBody,+ method: String,+ backend: &'static str,+ client: Arc<str>,+ caller_tag: Arc<str>,+ warn_threshold: usize,+ ) -> Self {Self {inner,bytes_counted: 0,method,backend,client,+ caller_tag,+ warn_threshold,}}}@@ -513,8 +539,20 @@ impl Drop for ByteCountedBody {"method" => self.method.clone(),"backend" => self.backend,"client" => self.client.clone(),+ "caller_tag" => self.caller_tag.clone(),).record(self.bytes_counted as f64);++ if self.warn_threshold > 0 && self.bytes_counted > self.warn_threshold {+ tracing::warn!(+ response_size_bytes = self.bytes_counted,+ method = %self.method,+ backend = self.backend,+ client = %self.client,+ caller_tag = %self.caller_tag,+ "oversized gRPC response"+ );+ }}}diff --git a/rust/personhog-router/tests/common/mod.rs b/rust/personhog-router/tests/common/mod.rsindex 86109e827f19..34cf77e8c664 100644--- a/rust/personhog-router/tests/common/mod.rs+++ b/rust/personhog-router/tests/common/mod.rs@@ -891,7 +891,7 @@ pub async fn start_test_router_raw_with_max_recv(initial_backoff_ms: 1,max_backoff_ms: 1,};- let proxy = RawProxyService::new(replica, None, retry_config, max_recv_message_size);+ let proxy = RawProxyService::new(replica, None, retry_config, max_recv_message_size, 0);tokio::spawn(async move {Server::builder()@@ -937,7 +937,13 @@ pub async fn start_test_router_raw_with_leader_and_max_recv(initial_backoff_ms: 1,max_backoff_ms: 1,};- let proxy = RawProxyService::new(replica, Some(leader), retry_config, max_recv_message_size);+ let proxy = RawProxyService::new(+ replica,+ Some(leader),+ retry_config,+ max_recv_message_size,+ 0,+ );tokio::spawn(async move {Server::builder()