: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
fix(personhog): let python clients read router error statuses (#116704)
Phil Haackb93bf471b257
diff --git a/rust/personhog-router/src/proxy.rs b/rust/personhog-router/src/proxy.rsindex ac87db07f080..b5f3d07787b5 100644--- a/rust/personhog-router/src/proxy.rs+++ b/rust/personhog-router/src/proxy.rs@@ -814,6 +814,18 @@ impl http_body::Body for ByteCountedBody {}result}++ /// hyper sets END_STREAM on the response HEADERS frame only when this+ /// returns true. A trailers-only gRPC error needs that flag. Without it,+ /// grpcio reads the status headers as initial metadata and reports+ /// UNKNOWN.+ fn is_end_stream(&self) -> bool {+ self.inner.is_end_stream()+ }++ fn size_hint(&self) -> http_body::SizeHint {+ self.inner.size_hint()+ }}impl Drop for ByteCountedBody {@@ -1002,6 +1014,20 @@ mod tests {}}+ #[test]+ fn byte_counted_body_reports_the_end_of_a_trailers_only_error() {+ let inner = grpc_error_response(Code::Unavailable, "Server at capacity").into_body();+ let body = ByteCountedBody::new(+ inner,+ Arc::from("GetPerson"),+ "replica",+ Arc::from("test"),+ Arc::from(""),+ 0,+ );+ assert!(http_body::Body::is_end_stream(&body));+ }+#[tokio::test]async fn collect_body_limited_accepts_within_limit() {let data = Bytes::from(vec![0u8; 100]);diff --git a/rust/personhog-router/tests/common/mod.rs b/rust/personhog-router/tests/common/mod.rsindex c96c2968f993..c9312a2c24ad 100644--- a/rust/personhog-router/tests/common/mod.rs+++ b/rust/personhog-router/tests/common/mod.rs@@ -63,7 +63,8 @@ use personhog_router::backend::{};use personhog_router::config::{Http2Windows, RetryConfig};use personhog_router::proxy::{IdentityProxyService, LifecycleProxyService, RawProxyService};-use tokio::net::TcpListener;+use tokio::io::AsyncReadExt;+use tokio::net::{TcpListener, TcpStream};use tokio::sync::RwLock;use tonic::codec::CompressionEncoding;use tonic::transport::{Channel, Server};@@ -1276,3 +1277,49 @@ pub async fn start_test_router_raw_with_identity(tokio::time::sleep(Duration::from_millis(10)).await;addr}++pub const H2_PREFACE: &[u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";+pub const H2_FRAME_DATA: u8 = 0x0;+pub const H2_FRAME_HEADERS: u8 = 0x1;+pub const H2_FRAME_SETTINGS: u8 = 0x4;+pub const H2_FRAME_WINDOW_UPDATE: u8 = 0x8;+pub const H2_FLAG_END_STREAM: u8 = 0x1;+pub const H2_FLAG_END_HEADERS: u8 = 0x4;++pub struct H2Frame {+ pub frame_type: u8,+ pub flags: u8,+ pub stream_id: u32,+ pub payload: Vec<u8>,+}++pub fn h2_frame(frame_type: u8, flags: u8, stream_id: u32, payload: &[u8]) -> Vec<u8> {+ let len = payload.len() as u32;+ let mut frame = vec![+ (len >> 16) as u8,+ (len >> 8) as u8,+ len as u8,+ frame_type,+ flags,+ ];+ frame.extend_from_slice(&stream_id.to_be_bytes());+ frame.extend_from_slice(payload);+ frame+}++pub async fn read_h2_frame(stream: &mut TcpStream) -> H2Frame {+ let mut header = [0u8; 9];+ stream.read_exact(&mut header).await.expect("frame header");+ let len = u32::from_be_bytes([0, header[0], header[1], header[2]]) as usize;+ let mut payload = vec![0u8; len];+ stream+ .read_exact(&mut payload)+ .await+ .expect("frame payload");+ H2Frame {+ frame_type: header[3],+ flags: header[4],+ stream_id: u32::from_be_bytes([header[5], header[6], header[7], header[8]]) & 0x7fff_ffff,+ payload,+ }+}diff --git a/rust/personhog-router/tests/h2_window_wiring.rs b/rust/personhog-router/tests/h2_window_wiring.rsindex cadd243e5cf8..5f2d696d4c58 100644--- a/rust/personhog-router/tests/h2_window_wiring.rs+++ b/rust/personhog-router/tests/h2_window_wiring.rs@@ -5,7 +5,10 @@ use std::net::SocketAddr;use std::sync::Arc;use std::time::Duration;-use common::TestLeaderService;+use common::{+ h2_frame, read_h2_frame, H2Frame, TestLeaderService, H2_FRAME_SETTINGS, H2_FRAME_WINDOW_UPDATE,+ H2_PREFACE,+};use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeaderServer;use personhog_router::backend::discovery::{build_discovered_endpoint, EndpointConfig};use personhog_router::backend::{@@ -18,7 +21,6 @@ use tokio::sync::RwLock;use tonic::transport::{Channel, Server};use tower::{Service, ServiceExt};-const PREFACE: &[u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";const DEFAULT_WINDOW: u32 = 65_535;const HYPER_SERVER_STREAM_WINDOW: u32 = 1 << 20;const HYPER_SERVER_CONNECTION_WINDOW: u32 = 1 << 20;@@ -26,8 +28,6 @@ const HYPER_CLIENT_STREAM_WINDOW: u32 = 2 << 20;const HYPER_CLIENT_CONNECTION_WINDOW: u32 = 5 << 20;const STREAM_WINDOW: u32 = 4 << 20;const CONNECTION_WINDOW: u32 = 8 << 20;-const FRAME_SETTINGS: u8 = 0x4;-const FRAME_WINDOW_UPDATE: u8 = 0x8;const SETTINGS_INITIAL_WINDOW_SIZE: u16 = 0x4;#[derive(Debug, Default, PartialEq, Eq)]@@ -40,19 +40,14 @@ async fn read_advertised_windows(stream: &mut TcpStream) -> AdvertisedWindows {let mut seen = AdvertisedWindows::default();let read_all = async {while seen.stream.is_none() || seen.connection_increment.is_none() {- let mut header = [0u8; 9];- stream.read_exact(&mut header).await.expect("frame header");- let len = u32::from_be_bytes([0, header[0], header[1], header[2]]) as usize;- let frame_type = header[3];- let stream_id =- u32::from_be_bytes([header[5], header[6], header[7], header[8]]) & 0x7fff_ffff;- let mut payload = vec![0u8; len];- stream- .read_exact(&mut payload)- .await- .expect("frame payload");+ let H2Frame {+ frame_type,+ stream_id,+ payload,+ ..+ } = read_h2_frame(stream).await;match frame_type {- FRAME_SETTINGS => {+ H2_FRAME_SETTINGS => {for entry in payload.chunks_exact(6) {let id = u16::from_be_bytes([entry[0], entry[1]]);let value = u32::from_be_bytes([entry[2], entry[3], entry[4], entry[5]]);@@ -61,7 +56,7 @@ async fn read_advertised_windows(stream: &mut TcpStream) -> AdvertisedWindows {}}}- FRAME_WINDOW_UPDATE if stream_id == 0 => {+ H2_FRAME_WINDOW_UPDATE if stream_id == 0 => {let increment =u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]])& 0x7fff_ffff;@@ -77,26 +72,6 @@ async fn read_advertised_windows(stream: &mut TcpStream) -> AdvertisedWindows {seen}-fn settings_frame(entries: &[(u16, u32)]) -> Vec<u8> {- let len = (entries.len() * 6) as u32;- let mut frame = vec![- (len >> 16) as u8,- (len >> 8) as u8,- len as u8,- FRAME_SETTINGS,- 0,- 0,- 0,- 0,- 0,- ];- for (id, value) in entries {- frame.extend_from_slice(&id.to_be_bytes());- frame.extend_from_slice(&value.to_be_bytes());- }- frame-}-fn windows(configured: bool) -> Http2Windows {if configured {Http2Windows::new(@@ -204,10 +179,12 @@ async fn every_outbound_channel_builder_advertises_the_configured_windows() {drive(channel);let (mut peer, _) = listener.accept().await.unwrap();- let mut preface = [0u8; PREFACE.len()];+ let mut preface = [0u8; H2_PREFACE.len()];peer.read_exact(&mut preface).await.unwrap();- assert_eq!(&preface, PREFACE, "{builder}");- peer.write_all(&settings_frame(&[])).await.unwrap();+ assert_eq!(&preface, H2_PREFACE, "{builder}");+ peer.write_all(&h2_frame(H2_FRAME_SETTINGS, 0, 0, &[]))+ .await+ .unwrap();let seen = read_advertised_windows(&mut peer).await;assert_eq!(@@ -238,8 +215,10 @@ async fn the_server_advertises_the_configured_windows() {});let mut peer = TcpStream::connect(addr).await.unwrap();- peer.write_all(PREFACE).await.unwrap();- peer.write_all(&settings_frame(&[])).await.unwrap();+ peer.write_all(H2_PREFACE).await.unwrap();+ peer.write_all(&h2_frame(H2_FRAME_SETTINGS, 0, 0, &[]))+ .await+ .unwrap();let seen = read_advertised_windows(&mut peer).await;assert_eq!(diff --git a/rust/personhog-router/tests/raw_proxy_integration.rs b/rust/personhog-router/tests/raw_proxy_integration.rsindex c8d5d3c13640..5636a1bf5319 100644--- a/rust/personhog-router/tests/raw_proxy_integration.rs+++ b/rust/personhog-router/tests/raw_proxy_integration.rs@@ -2,15 +2,18 @@ mod common;use std::sync::atomic::Ordering;use std::sync::{Arc, Mutex};+use std::time::Duration;use common::{- create_client, create_compressed_client, create_test_person, raw_grpc_call_with_gzip_accept,- start_test_identity, start_test_leader, start_test_replica, start_test_replica_with_async_gzip,+ create_client, create_compressed_client, create_test_person, h2_frame,+ raw_grpc_call_with_gzip_accept, read_h2_frame, start_test_identity, start_test_leader,+ start_test_replica, start_test_replica_with_async_gzip,start_test_replica_with_async_gzip_disabled, start_test_router_raw,start_test_router_raw_with_dying_leader, start_test_router_raw_with_identity,start_test_router_raw_with_leader, start_test_router_raw_with_leader_and_max_recv,start_test_router_raw_with_max_recv, TestIdentityService, TestLeaderService,- TestLifecycleService, TestReplicaService,+ TestLifecycleService, TestReplicaService, H2_FLAG_END_HEADERS, H2_FLAG_END_STREAM,+ H2_FRAME_DATA, H2_FRAME_HEADERS, H2_FRAME_SETTINGS, H2_PREFACE,};use personhog_proto::personhog::identity::v1::person_hog_identity_client::PersonHogIdentityClient;use personhog_proto::personhog::identity::v1::{@@ -24,6 +27,8 @@ use personhog_proto::personhog::types::v1::{GetPersonsByDistinctIdsInTeamRequest, Group, GroupIdentifier, Person,UpdatePersonPropertiesRequest,};+use tokio::io::AsyncWriteExt;+use tokio::net::TcpStream;use tonic::Request;const NUM_PARTITIONS: u32 = 8;@@ -128,6 +133,78 @@ async fn raw_proxy_returns_a_persistent_shed_after_the_budget() {assert_eq!(calls.load(Ordering::SeqCst), 2, "the budget was not spent");}+/// HPACK "literal header field without indexing, new name" with no Huffman+/// coding.+fn hpack_literal(name: &str, value: &str) -> Vec<u8> {+ assert!(name.len() < 127 && value.len() < 127);+ let mut field = vec![0x00, name.len() as u8];+ field.extend_from_slice(name.as_bytes());+ field.push(value.len() as u8);+ field.extend_from_slice(value.as_bytes());+ field+}++/// grpcio reads a trailers-only error only when its HEADERS frame sets+/// END_STREAM. tonic clients read the status from the headers either way, so+/// this test checks the raw frame flags.+#[tokio::test]+async fn raw_proxy_ends_the_stream_on_a_forwarded_error_headers_frame() {+ let replica_service = TestReplicaService::new().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 request_headers: Vec<u8> = [+ (":method", "POST"),+ (":scheme", "http"),+ (":authority", "localhost"),+ (":path", "/personhog.service.v1.PersonHogService/GetPerson"),+ ("content-type", "application/grpc"),+ ("te", "trailers"),+ ]+ .into_iter()+ .flat_map(|(name, value)| hpack_literal(name, value))+ .collect();+ // An uncompressed gRPC message of zero bytes decodes as a default GetPersonRequest.+ let empty_grpc_message = [0u8; 5];++ let request = [+ H2_PREFACE.to_vec(),+ h2_frame(H2_FRAME_SETTINGS, 0, 0, &[]),+ h2_frame(H2_FRAME_HEADERS, H2_FLAG_END_HEADERS, 1, &request_headers),+ h2_frame(H2_FRAME_DATA, H2_FLAG_END_STREAM, 1, &empty_grpc_message),+ ]+ .concat();+ let mut peer = TcpStream::connect(router_addr).await.unwrap();+ peer.write_all(&request).await.unwrap();++ let response = tokio::time::timeout(Duration::from_secs(5), async {+ loop {+ let frame = read_h2_frame(&mut peer).await;+ if frame.stream_id == 1 {+ return frame;+ }+ }+ })+ .await+ .expect("the router answered the request stream");++ assert_eq!(+ response.frame_type, H2_FRAME_HEADERS,+ "the first frame on the request stream must be HEADERS"+ );+ assert_ne!(+ response.flags & H2_FLAG_END_STREAM,+ 0,+ "a trailers-only error must set END_STREAM on its HEADERS frame"+ );+ assert_eq!(+ calls.load(Ordering::SeqCst),+ 2,+ "the request never reached the replica"+ );+}+#[tokio::test]async fn raw_proxy_get_person_default_routes_to_replica() {let test_person = create_test_person();