: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
chore(personhog): enforce message size after compression (#61517)
Zach Brown4b880275f206
diff --git a/rust/personhog-common/src/async_gzip.rs b/rust/personhog-common/src/async_gzip.rsindex bedf87b33b36..05642f38271c 100644--- a/rust/personhog-common/src/async_gzip.rs+++ b/rust/personhog-common/src/async_gzip.rs@@ -67,6 +67,23 @@ pub struct AsyncGzipConfig {/// than this pass through uncompressed — the gzip header overhead would/// make them larger, and the CPU cost isn't worth it.pub min_payload_size: usize,++ /// Maximum response payload size (bytes) after compression (or uncompressed+ /// if gzip is not negotiated). When a response exceeds this limit, behavior+ /// depends on `max_response_size_enforce`: in enforce mode, the response is+ /// rejected with an OUT_OF_RANGE gRPC error; in monitor mode, a metric is+ /// emitted but the response is delivered normally. `None` disables the check.+ ///+ /// This replaces tonic's `max_encoding_message_size` as the primary guardrail+ /// because tonic's check runs before this layer's gzip compression, rejecting+ /// responses that would compress well below the limit.+ pub max_response_size: Option<usize>,++ /// When true, responses exceeding `max_response_size` are rejected with a+ /// gRPC OUT_OF_RANGE error. When false (monitor mode), the metric fires+ /// but the response is delivered normally — useful for observing violations+ /// before enabling enforcement.+ pub max_response_size_enforce: bool,}impl AsyncGzipConfig {@@ -75,8 +92,16 @@ impl AsyncGzipConfig {enabled,compression_level: compression_level.clamp(1, 9),min_payload_size,+ max_response_size: None,+ max_response_size_enforce: false,}}++ pub fn with_max_response_size(mut self, max_bytes: Option<usize>, enforce: bool) -> Self {+ self.max_response_size = max_bytes;+ self.max_response_size_enforce = enforce;+ self+ }}impl Default for AsyncGzipConfig {@@ -85,6 +110,8 @@ impl Default for AsyncGzipConfig {enabled: false,compression_level: 6,min_payload_size: 256,+ max_response_size: None,+ max_response_size_enforce: false,}}}@@ -165,6 +192,22 @@ where.unwrap_or("unknown"),);+ let client: Arc<str> = Arc::from(+ request+ .headers()+ .get("x-client-name")+ .and_then(|v| v.to_str().ok())+ .unwrap_or("unknown"),+ );++ let caller_tag: Arc<str> = Arc::from(+ request+ .headers()+ .get("x-caller-tag")+ .and_then(|v| v.to_str().ok())+ .unwrap_or(""),+ );+let config = self.config.clone();let mut inner = self.inner.clone();@@ -172,22 +215,12 @@ wherelet response = inner.call(request).await?;let (mut parts, body) = response.into_parts();- // When compression isn't requested, pass the original body through- // without collecting or copying — zero overhead for the common case- // where the client doesn't accept gzip or the feature is disabled.- if !accepts_gzip {- counter!("grpc_gzip_responses_total", "outcome" => "passthrough", "method" => method.clone()).increment(1);- let body = body.map_err(|e| Status::internal(e.to_string()));- let boxed: ResponseBody = Box::pin(body);- return Ok(Response::from_parts(parts, boxed));- }-let gzip_start = Instant::now();- // Gather body data chunks and trailers separately. For unary RPCs,- // tonic produces one or more data frames (split at ~32KB boundaries)- // followed by a trailers frame. We keep chunks as individual Bytes- // references to avoid copying them into a contiguous buffer.+ // Always collect the body so we can enforce size limits on all+ // response paths. For unary RPCs this is a single frame — the+ // overhead is one Vec allocation and Bytes reference copies (no+ // data copying for the common single-chunk case).let mut chunks: Vec<Bytes> = Vec::new();let mut trailers: Option<HeaderMap> = None;let mut total_size: usize = 0;@@ -238,6 +271,19 @@ where).record(gzip_start.elapsed().as_secs_f64() * 1000.0);+ // Client doesn't accept gzip — return the collected body uncompressed.+ if !accepts_gzip {+ counter!("grpc_gzip_responses_total", "outcome" => "passthrough_no_gzip", "method" => method.clone()).increment(1);+ if let Some(body) =+ check_response_size(&config, &method, &client, &caller_tag, total_size)+ {+ return Ok(Response::from_parts(parts, body));+ }+ let data = concat_chunks(&chunks);+ let boxed: ResponseBody = Box::pin(PrecomputedBody::new(data, trailers));+ return Ok(Response::from_parts(parts, boxed));+ }+let payload_size = total_size.saturating_sub(GRPC_HEADER_SIZE);let already_compressed = chunks.iter().find_map(|c| c.first().copied()) == Some(1);@@ -248,7 +294,12 @@ where|| payload_size < config.min_payload_size|| already_compressed{- counter!("grpc_gzip_responses_total", "outcome" => "passthrough", "method" => method.clone()).increment(1);+ counter!("grpc_gzip_responses_total", "outcome" => "passthrough_small", "method" => method.clone()).increment(1);+ if let Some(body) =+ check_response_size(&config, &method, &client, &caller_tag, total_size)+ {+ return Ok(Response::from_parts(parts, body));+ }let gzip_overhead_ms = gzip_start.elapsed().as_secs_f64() * 1000.0;set_gzip_overhead_header(&mut parts, method.clone(), gzip_overhead_ms);let data = concat_chunks(&chunks);@@ -274,6 +325,19 @@ where.record(bytes.len() as f64);counter!("grpc_gzip_responses_total", "outcome" => "compressed", "method" => method.clone()).increment(1);+ // Size check on the compressed output — this is the actual+ // number of bytes that will go over the wire.+ let compressed_frame_size = GRPC_HEADER_SIZE + bytes.len();+ if let Some(body) = check_response_size(+ &config,+ &method,+ &client,+ &caller_tag,+ compressed_frame_size,+ ) {+ return Ok(Response::from_parts(parts, body));+ }+let mut frame = BytesMut::with_capacity(GRPC_HEADER_SIZE + bytes.len());frame.put_u8(1); // compression flagframe.put_u32(bytes.len() as u32);@@ -312,6 +376,63 @@ where}}+/// Checks the response size against the configured limit. In enforce mode,+/// returns a rejection body that the caller should wrap with the original+/// response `parts` (preserving headers like `Content-Type: application/grpc`).+/// In monitor mode, emits a metric and returns `None` so the caller proceeds+/// normally.+fn check_response_size(+ config: &AsyncGzipConfig,+ method: &Arc<str>,+ client: &Arc<str>,+ caller_tag: &Arc<str>,+ size: usize,+) -> Option<ResponseBody> {+ let limit = config.max_response_size?;+ if size <= limit {+ return None;+ }++ let enforced = config.max_response_size_enforce;++ counter!(+ "grpc_gzip_response_over_limit_total",+ "method" => method.clone(),+ "client" => client.clone(),+ "enforced" => if enforced { "true" } else { "false" },+ )+ .increment(1);++ if !enforced {+ warn!(+ response_size_bytes = size,+ limit_bytes = limit,+ method = %method,+ client = %client,+ caller_tag = %caller_tag,+ "oversized gRPC response (monitor mode)"+ );+ return None;+ }++ warn!(+ response_size_bytes = size,+ limit_bytes = limit,+ method = %method,+ client = %client,+ caller_tag = %caller_tag,+ "rejecting oversized gRPC response"+ );++ let mut trailers = HeaderMap::new();+ trailers.insert("grpc-status", HeaderValue::from_static("11")); // OUT_OF_RANGE+ let msg = format!("response size {size} bytes exceeds limit of {limit} bytes");+ if let Ok(hv) = HeaderValue::from_str(&msg) {+ trailers.insert("grpc-message", hv);+ }+ Some(Box::pin(PrecomputedBody::trailers_only(trailers)))+}+// ============================================================// Response bodies// ============================================================@@ -465,6 +586,8 @@ mod tests {enabled: true,compression_level: 6,min_payload_size: 0,+ max_response_size: None,+ max_response_size_enforce: false,}}@@ -532,7 +655,14 @@ mod tests {data: Some(self.body.clone()),trailers: self.trailers.clone(),};- Box::pin(async { Ok(Response::new(body)) })+ Box::pin(async {+ let mut resp = Response::new(body);+ resp.headers_mut().insert(+ "content-type",+ HeaderValue::from_static("application/grpc+proto"),+ );+ Ok(resp)+ })}}@@ -1000,4 +1130,99 @@ mod tests {None => panic!("header should be present"),}}++ // ============================================================+ // Response size limit tests+ // ============================================================++ #[tokio::test]+ async fn enforce_rejects_oversized_compressed_response() {+ let payload = vec![42u8; 10_000];+ let service = MockGrpcService::new(&payload);+ let config = AsyncGzipConfig {+ max_response_size: Some(10), // tiny limit — compressed output will exceed+ max_response_size_enforce: true,+ ..default_test_config()+ };++ let (parts, data, trailers) = call_layer(service, config, Some("gzip")).await;+ assert!(data.is_empty(), "rejected response should have no data");+ let trailers = trailers.expect("should have trailers");+ assert_eq!(trailers.get("grpc-status").unwrap(), "11"); // OUT_OF_RANGE+ // Verify the original response headers (e.g. content-type) are preserved+ assert_eq!(+ parts.headers.get("content-type").unwrap(),+ "application/grpc+proto"+ );+ }++ #[tokio::test]+ async fn enforce_rejects_oversized_uncompressed_response() {+ let payload = vec![42u8; 10_000];+ let service = MockGrpcService::new(&payload);+ let config = AsyncGzipConfig {+ max_response_size: Some(100),+ max_response_size_enforce: true,+ ..default_test_config()+ };++ // No gzip header — uncompressed passthrough, still size-checked+ let (parts, data, trailers) = call_layer(service, config, None).await;+ assert!(data.is_empty(), "rejected response should have no data");+ let trailers = trailers.expect("should have trailers");+ assert_eq!(trailers.get("grpc-status").unwrap(), "11");+ assert_eq!(+ parts.headers.get("content-type").unwrap(),+ "application/grpc+proto"+ );+ }++ #[tokio::test]+ async fn monitor_mode_delivers_oversized_response() {+ let payload = vec![42u8; 10_000];+ let service = MockGrpcService::new(&payload);+ let config = AsyncGzipConfig {+ max_response_size: Some(10), // tiny limit+ max_response_size_enforce: false, // monitor only+ ..default_test_config()+ };++ let (parts, data, _trailers) = call_layer(service, config, Some("gzip")).await;+ // Response should still be delivered despite exceeding the limit+ assert_eq!(parts.headers.get(GRPC_ENCODING).unwrap(), "gzip");+ let (compressed, compressed_payload) = parse_grpc_frame(&data);+ assert!(compressed);+ assert_eq!(gzip_decompress(&compressed_payload), payload);+ }++ #[tokio::test]+ async fn enforce_allows_response_under_limit() {+ let payload = b"small payload";+ let service = MockGrpcService::new(payload);+ let config = AsyncGzipConfig {+ max_response_size: Some(1_000_000), // generous limit+ max_response_size_enforce: true,+ ..default_test_config()+ };++ let (parts, data, trailers) = call_layer(service, config, Some("gzip")).await;+ assert_eq!(parts.headers.get(GRPC_ENCODING).unwrap(), "gzip");+ let (compressed, compressed_payload) = parse_grpc_frame(&data);+ assert!(compressed);+ assert_eq!(gzip_decompress(&compressed_payload), payload);+ let trailers = trailers.expect("trailers should be present");+ assert_eq!(trailers.get("grpc-status").unwrap(), "0");+ }++ #[tokio::test]+ async fn no_limit_allows_any_size() {+ let payload = vec![42u8; 100_000];+ let service = MockGrpcService::new(&payload);+ let config = default_test_config(); // max_response_size = None++ let (parts, data, _trailers) = call_layer(service, config, Some("gzip")).await;+ assert_eq!(parts.headers.get(GRPC_ENCODING).unwrap(), "gzip");+ let (_, compressed_payload) = parse_grpc_frame(&data);+ assert_eq!(gzip_decompress(&compressed_payload), payload);+ }}diff --git a/rust/personhog-replica/src/config.rs b/rust/personhog-replica/src/config.rsindex 60ddff83236f..441ce65073d8 100644--- a/rust/personhog-replica/src/config.rs+++ b/rust/personhog-replica/src/config.rs@@ -115,6 +115,18 @@ pub struct Config {/// than this pass through uncompressed.#[envconfig(default = "256")]pub gzip_min_payload_size: usize,++ /// Maximum response size (bytes) enforced after gzip compression. Applies+ /// to the final wire size — compressed bytes for gzip responses, raw bytes+ /// for uncompressed passthrough. 0 = disabled. Default 4 MiB.+ #[envconfig(default = "4194304")]+ pub gzip_max_response_size: usize,++ /// When true, responses exceeding `gzip_max_response_size` are rejected+ /// with a gRPC OUT_OF_RANGE error. When false, the metric fires but the+ /// response is delivered normally (monitor mode).+ #[envconfig(default = "false")]+ pub gzip_max_response_size_enforce: bool,}impl Config {diff --git a/rust/personhog-replica/src/main.rs b/rust/personhog-replica/src/main.rsindex 174a252533fe..f7ef499018b2 100644--- a/rust/personhog-replica/src/main.rs+++ b/rust/personhog-replica/src/main.rs@@ -308,11 +308,17 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {let max_send = config.grpc_max_send_message_size;let max_recv = config.grpc_max_recv_message_size;let max_concurrent_requests = config.max_concurrent_requests;+ let max_response_size = if config.gzip_max_response_size > 0 {+ Some(config.gzip_max_response_size)+ } else {+ None+ };let gzip_config = AsyncGzipConfig::new(config.gzip_response_compression,config.gzip_compression_level,config.gzip_min_payload_size,- );+ )+ .with_max_response_size(max_response_size, config.gzip_max_response_size_enforce);if gzip_config.enabled {tracing::info!(@@ -321,6 +327,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {"Async gzip response compression enabled");}+ if let Some(limit) = gzip_config.max_response_size {+ tracing::info!(+ limit_bytes = limit,+ enforce = gzip_config.max_response_size_enforce,+ "Response size limit active"+ );+ }if max_concurrent_requests > 0 {tracing::info!(limit = max_concurrent_requests,