: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): stash leader reads (#69456)
Zach Brown9ab3c321a492
diff --git a/rust/personhog-router/src/backend/leader.rs b/rust/personhog-router/src/backend/leader.rsindex d977dd1886e0..469ff4b1418e 100644--- a/rust/personhog-router/src/backend/leader.rs+++ b/rust/personhog-router/src/backend/leader.rs@@ -220,7 +220,7 @@ impl LeaderBackend {// steady-state forward path copies nothing.match self.stash- .enqueue_or_forward(partition, &frame, &headers, key)+ .enqueue_or_forward(partition, method, &frame, &headers, key).await{StashDecision::Stashed(rx) => {diff --git a/rust/personhog-router/src/backend/stash.rs b/rust/personhog-router/src/backend/stash.rsindex c90c7da72c12..d239340698b8 100644--- a/rust/personhog-router/src/backend/stash.rs+++ b/rust/personhog-router/src/backend/stash.rs@@ -1,17 +1,21 @@-//! Per-partition stash queue for the write-path.+//! Per-partition stash queue for the leader path.//!//! During a partition handoff, the coordinator advances the handoff state//! through `Freezing → Draining → Warming → Complete`. From the moment//! the handoff is created (in `Freezing`) and until the routing table-//! flips at `Complete`, routers buffer (stash) incoming write requests-//! for that partition here. When `Complete` arrives the stashed-//! requests are drained in arrival order to the new owner.+//! flips at `Complete`, routers buffer (stash) incoming leader-path+//! requests — writes and strong reads alike — for that partition here.+//! When `Complete` arrives the stashed requests are drained in arrival+//! order to the new owner.//!-//! This gives the protocol a clean "no split-brain writes" guarantee-//! without returning errors to callers — every write that hits the-//! router during the handoff window is either delivered to the new-//! owner in arrival order or fails fast with `UNAVAILABLE` once its-//! per-request deadline expires (see `RouterStashHandler`).+//! Stashing both request kinds gives the protocol two guarantees at once:+//! no split-brain writes, and strong reads that stay read-your-write+//! through the handoff — a read queued behind the write it must observe+//! (per-key FIFO) drains after it, instead of racing ahead to the old+//! owner's frozen cache. Every request that hits the router during the+//! handoff window is either delivered in arrival order or fails fast with+//! `UNAVAILABLE` once its per-request deadline expires (see+//! `RouterStashHandler`).use std::collections::VecDeque;use std::sync::Arc;@@ -55,9 +59,12 @@ fn approximate_size(frame: &Bytes) -> usize {PER_REQUEST_OVERHEAD + frame.len()}-/// A raw write held in the stash along with everything needed to replay it-/// to the new owner and return the response to the original caller.+/// A raw leader-path request held in the stash along with everything+/// needed to replay it and return the response to the original caller.pub struct StashedRequest {+ /// gRPC method the frame targets, so drain replays each request to+ /// the path it arrived on (writes and strong reads share the stash).+ pub method: &'static str,/// The raw gRPC request frame, forwarded verbatim on replay.pub frame: Bytes,/// The client's request headers, forwarded verbatim (the router stamps@@ -185,6 +192,7 @@ impl StashTable {pub async fn enqueue_or_forward(&self,partition: u32,+ method: &'static str,frame: &Bytes,headers: &HeaderMap,key: (i64, i64),@@ -223,6 +231,7 @@ impl StashTable {let (tx, rx) = oneshot::channel();queue.requests.push_back(StashedRequest {+ method,frame: frame.clone(),headers: headers.clone(),key,@@ -345,6 +354,7 @@ mod tests {table.enqueue_or_forward(partition,+ "UpdatePersonProperties",&Bytes::from_static(b"x"),&HeaderMap::new(),(1, person_id),@@ -363,6 +373,7 @@ mod tests {table.enqueue_or_forward(partition,+ "UpdatePersonProperties",&Bytes::from(vec![0u8; payload]),&HeaderMap::new(),(1, person_id),diff --git a/rust/personhog-router/src/proxy.rs b/rust/personhog-router/src/proxy.rsindex 4e7e3e8e52a0..70fddc98654e 100644--- a/rust/personhog-router/src/proxy.rs+++ b/rust/personhog-router/src/proxy.rs@@ -157,7 +157,7 @@ impl RawProxyInner {let (mut response, backend, channel_call_ms) = match method_name {"UpdatePersonProperties" => {let (resp, call_ms) = self- .raw_proxy_to_leader(req, "UpdatePersonProperties", true)+ .raw_proxy_to_leader(req, "UpdatePersonProperties").await;(resp, "leader", call_ms)}@@ -169,7 +169,7 @@ impl RawProxyInner {== Some("strong");if is_strong {- let (resp, call_ms) = self.raw_proxy_to_leader(req, "GetPerson", false).await;+ let (resp, call_ms) = self.raw_proxy_to_leader(req, "GetPerson").await;(resp, "leader", call_ms)} else {let (resp, call_ms) = self.raw_proxy_to_replica(req, method.clone()).await;@@ -387,14 +387,22 @@ impl RawProxyInner {/// client, is hashed to a partition, and the request bytes are forwarded/// verbatim with the partition in the `x-partition` header. The body is/// never inspected, so client-compressed request frames transit- /// untouched. Writes (`use_stash`) go through the per-partition stash so- /// they buffer correctly during a handoff; reads forward directly and- /// surface the channel round-trip time for the network-overhead metric.+ /// untouched.+ ///+ /// Both writes and strong reads go through the per-partition stash+ /// during a handoff. Writes must buffer for the no-split-brain+ /// guarantee; strong reads must buffer with them so read-your-write+ /// holds across the handoff — a strong read racing ahead to the old+ /// owner would miss any write parked in the stash before it, and a+ /// read arriving after cutover on a router that hasn't seen Complete+ /// would read the old owner's frozen cache after the new owner has+ /// already accepted writes. Outside a handoff the stash is empty and+ /// requests forward directly, surfacing the channel round-trip time+ /// for the network-overhead metric.async fn raw_proxy_to_leader(&self,req: http::Request<BoxBody>,method: &'static str,- use_stash: bool,) -> (http::Response<BoxBody>, Option<f64>) {let leader = match &self.leader {Some(l) => l.clone(),@@ -432,25 +440,15 @@ impl RawProxyInner {let partition = leader.partition_for_person(team_id, person_id);let _in_flight = ClientInFlightGuard::new("leader");- if use_stash {- leader- .forward_or_stash(- method,- partition,- (team_id, person_id),- parts.headers,- body_bytes,- )- .await- } else {- match leader- .forward_raw(method, partition, &parts.headers, &body_bytes)- .await- {- Ok((response, call_ms)) => (response, Some(call_ms)),- Err(status) => (grpc_error_response(status.code(), status.message()), None),- }- }+ leader+ .forward_or_stash(+ method,+ partition,+ (team_id, person_id),+ parts.headers,+ body_bytes,+ )+ .await}}diff --git a/rust/personhog-router/src/stash_handler.rs b/rust/personhog-router/src/stash_handler.rsindex 215b08dd0119..58505405b454 100644--- a/rust/personhog-router/src/stash_handler.rs+++ b/rust/personhog-router/src/stash_handler.rs@@ -11,21 +11,18 @@ use tonic::Code;use crate::backend::{LeaderBackend, StashedRequest};use crate::grpc_http::{grpc_error_response, grpc_status_code, is_grpc_error_response};-/// gRPC method name for stashed writes — the stash buffers only the write-/// path, so every replayed frame targets `UpdatePersonProperties`.-const UPDATE_METHOD: &str = "UpdatePersonProperties";-/// Stash handler for the router. Reacts to handoff phase transitions:////// * `Freezing` / `Draining` / `Warming` → `begin_stash`: start (or-/// re-confirm) buffering writes for the partition in the shared-/// `StashTable`. The routing-table layer calls `begin_stash` on+/// re-confirm) buffering leader-path requests — writes and strong+/// reads — for the partition in the shared `StashTable`. The routing-table layer calls `begin_stash` on/// every non-terminal phase the router observes, so the call must/// be idempotent — `StashTable::begin_stash` no-ops if the entry is-/// already live. New writes park in a per-partition queue while the-/// handoff progresses through `Freezing → Draining → Warming`.-/// * `Complete` → `drain_stash`: forward the buffered writes to the-/// new owner. The drain runs as a loop over the queue; any request+/// already live. New leader-path requests park in a per-partition+/// queue while the handoff progresses through+/// `Freezing → Draining → Warming`.+/// * `Complete` → `drain_stash`: forward the buffered requests to the+/// new owner, each to the method it arrived on. The drain runs as a loop over the queue; any request/// that arrives during drain (the dashmap entry is still live until/// drain observes the queue empty under the lock) is picked up by/// the next iteration, preserving FIFO ordering across the cutover.@@ -127,7 +124,7 @@ async fn forward_one(// headers, so no body poll is needed to classify them).let (response, outcome) = match leader_backend.forward_raw(- UPDATE_METHOD,+ stashed_req.method,partition,&stashed_req.headers,&stashed_req.frame,diff --git a/rust/personhog-router/tests/stash_integration.rs b/rust/personhog-router/tests/stash_integration.rsindex 89cfdecc3852..6356e36598d8 100644--- a/rust/personhog-router/tests/stash_integration.rs+++ b/rust/personhog-router/tests/stash_integration.rs@@ -16,7 +16,8 @@ use http::HeaderMap;use http_body_util::BodyExt;use personhog_coordination::routing_table::StashHandler;use personhog_proto::personhog::types::v1::{- UpdatePersonPropertiesRequest, UpdatePersonPropertiesResponse,+ GetPersonRequest, GetPersonResponse, UpdatePersonPropertiesRequest,+ UpdatePersonPropertiesResponse,};use personhog_router::backend::{LeaderBackend, LeaderBackendConfig, StashTable};use personhog_router::config::RetryConfig;@@ -123,9 +124,7 @@ async fn forward(/// its gRPC status code on error. The status lives in the response headers/// (router-generated errors, trailers-only leader errors) or the trailers/// (a normal leader response).-async fn decode_response(- resp: http::Response<BoxBody>,-) -> Result<UpdatePersonPropertiesResponse, Code> {+async fn decode_response<T: Message + Default>(resp: http::Response<BoxBody>) -> Result<T, Code> {let (parts, body) = resp.into_parts();let collected = body.collect().await.expect("collect leader response body");let trailers = collected.trailers().cloned();@@ -145,7 +144,39 @@ async fn decode_response(let msg = data.get(5..).expect("successful response carries a gRPC frame");- Ok(UpdatePersonPropertiesResponse::decode(msg).expect("decode UpdatePersonPropertiesResponse"))+ Ok(T::decode(msg).expect("decode leader response message"))+}++/// Drive a strong read through the backend's raw, stash-aware forward+/// path — the same route `raw_proxy_to_leader` takes for a strong+/// `GetPerson` — returning the router's gRPC response.+async fn forward_read(+ backend: &LeaderBackend,+ team_id: i64,+ person_id: i64,+) -> http::Response<BoxBody> {+ let req = GetPersonRequest {+ team_id,+ person_id,+ read_options: None,+ };+ let encoded = req.encode_to_vec();+ let mut buf = Vec::with_capacity(5 + encoded.len());+ buf.push(0);+ buf.extend_from_slice(&(encoded.len() as u32).to_be_bytes());+ buf.extend(encoded);++ let partition = backend.partition_for_person(team_id, person_id);+ let (response, _call_ms) = backend+ .forward_or_stash(+ "GetPerson",+ partition,+ (team_id, person_id),+ HeaderMap::new(),+ Bytes::from(buf),+ )+ .await;+ response}/// A request that arrives while the stash is open must park on a oneshot,@@ -192,7 +223,9 @@ async fn request_during_stash_completes_after_drain() {.await.expect("drain should release the parked request promptly").expect("task should not panic");- let response = decode_response(raw).await.expect("update should succeed");+ let response = decode_response::<UpdatePersonPropertiesResponse>(raw)+ .await+ .expect("update should succeed");let returned = response.person.expect("leader returned a person");assert_eq!(returned.id, person.id);assert!(response.updated, "leader marked the update as applied");@@ -238,7 +271,9 @@ async fn multiple_stashed_requests_drain_in_fifo() {.await.expect("each parked request should release after drain").expect("task should not panic");- let resp = decode_response(raw).await.expect("update should succeed");+ let resp = decode_response::<UpdatePersonPropertiesResponse>(raw)+ .await+ .expect("update should succeed");versions.push(resp.person.unwrap().version);}@@ -275,7 +310,9 @@ async fn requests_for_unstashed_partition_forward_immediately() {let raw = tokio::time::timeout(Duration::from_secs(2), forward(&backend, req)).await.expect("forward should not block");- let response = decode_response(raw).await.expect("update should succeed");+ let response = decode_response::<UpdatePersonPropertiesResponse>(raw)+ .await+ .expect("update should succeed");assert!(response.updated);}@@ -304,7 +341,7 @@ async fn stash_full_returns_unavailable_via_backend() {// The second request hits the cap and is rejected.let req2 = mk_request(person.team_id, person.id, "[email protected]");let raw = forward(&backend, req2).await;- let code = decode_response(raw)+ let code = decode_response::<UpdatePersonPropertiesResponse>(raw).await.expect_err("second request must be rejected");assert_eq!(@@ -337,7 +374,7 @@ async fn back_to_back_handoffs_use_fresh_queue() {tokio::time::sleep(Duration::from_millis(20)).await;handler.drain_stash(partition, "leader-a").await.unwrap();let raw_a = pending_a.await.unwrap();- decode_response(raw_a)+ decode_response::<UpdatePersonPropertiesResponse>(raw_a).await.expect("first handoff's stashed request should drain successfully");@@ -355,7 +392,7 @@ async fn back_to_back_handoffs_use_fresh_queue() {);handler.drain_stash(partition, "leader-b").await.unwrap();let raw_b = pending_b.await.unwrap();- decode_response(raw_b)+ decode_response::<UpdatePersonPropertiesResponse>(raw_b).await.expect("second handoff's stashed request should drain successfully");}@@ -414,10 +451,10 @@ async fn ordering_preserved_when_request_arrives_during_drain() {drain_task.await.unwrap();- let resp_a = decode_response(pending_a.await.unwrap())+ let resp_a = decode_response::<UpdatePersonPropertiesResponse>(pending_a.await.unwrap()).await.expect("A should succeed");- let resp_b = decode_response(pending_b.await.unwrap())+ let resp_b = decode_response::<UpdatePersonPropertiesResponse>(pending_b.await.unwrap()).await.expect("B should succeed");@@ -466,7 +503,7 @@ async fn stash_wait_exceeded_returns_unavailable() {handler.drain_stash(partition, "leader-new").await.unwrap();let raw = pending.await.unwrap();- let code = decode_response(raw)+ let code = decode_response::<UpdatePersonPropertiesResponse>(raw).await.expect_err("drain must fail-fast past-deadline requests");assert_eq!(@@ -510,7 +547,7 @@ async fn fenced_leader_during_drain_returns_unavailable() {handler.drain_stash(partition, "leader-new").await.unwrap();let response = pending.await.unwrap();- let code = decode_response(response)+ let code = decode_response::<UpdatePersonPropertiesResponse>(response).await.expect_err("fenced leader must reject the drained write");assert_eq!(@@ -520,6 +557,87 @@ async fn fenced_leader_during_drain_returns_unavailable() {);}+/// The reason strong reads stash at all: a write parked in the stash is+/// invisible everywhere until drain, so a strong read that raced ahead to+/// the (frozen) old owner would violate read-your-write for the whole+/// handoff window. Stashed behind the write in the same per-key FIFO, the+/// read drains after it and observes it.+#[tokio::test]+async fn stashed_strong_read_observes_stashed_write() {+ let person = create_test_person();+ let leader_addr = start_test_leader(TestLeaderService::new().with_person(person.clone())).await;++ let stash = StashTable::with_bounds(usize::MAX, usize::MAX);+ let backend = make_backend(leader_addr, stash.clone()).await;+ let handler = new_test_handler(Arc::clone(&backend));++ let partition = backend.partition_for_person(person.team_id, person.id);+ handler.begin_stash(partition, "leader-new").await.unwrap();++ // Write first, then a strong read for the same person — both park.+ let backend_w = Arc::clone(&backend);+ let req = mk_request(person.team_id, person.id, "[email protected]");+ let write = tokio::spawn(async move { forward(&backend_w, req).await });+ tokio::time::sleep(Duration::from_millis(50)).await;+ let backend_r = Arc::clone(&backend);+ let (team_id, person_id) = (person.team_id, person.id);+ let read = tokio::spawn(async move { forward_read(&backend_r, team_id, person_id).await });+ tokio::time::sleep(Duration::from_millis(50)).await;+ assert!(+ !write.is_finished() && !read.is_finished(),+ "both must park"+ );++ handler.drain_stash(partition, "leader-new").await.unwrap();++ let write_resp = decode_response::<UpdatePersonPropertiesResponse>(write.await.unwrap())+ .await+ .expect("stashed write must succeed on drain");+ assert!(write_resp.updated);++ let read_resp = decode_response::<GetPersonResponse>(read.await.unwrap())+ .await+ .expect("stashed read must succeed on drain");+ let props: serde_json::Value =+ serde_json::from_slice(&read_resp.person.expect("person").properties).unwrap();+ assert_eq!(+ props["email"], "[email protected]",+ "the drained read must observe the write stashed before it"+ );+}++/// A stashed strong read is bounded by the same per-request deadline as a+/// write: past `max_stash_wait` it fails fast with retryable UNAVAILABLE+/// instead of parking until the client's gRPC deadline.+#[tokio::test]+async fn stashed_read_past_deadline_returns_unavailable() {+ let person = create_test_person();+ let leader_addr = start_test_leader(TestLeaderService::new().with_person(person.clone())).await;++ let stash = StashTable::with_bounds(usize::MAX, usize::MAX);+ let backend = make_backend(leader_addr, stash.clone()).await;+ let handler = RouterStashHandler::new(Arc::clone(&backend), Duration::from_millis(50), 4);++ let partition = backend.partition_for_person(person.team_id, person.id);+ handler.begin_stash(partition, "leader-new").await.unwrap();++ let backend_r = Arc::clone(&backend);+ let (team_id, person_id) = (person.team_id, person.id);+ let read = tokio::spawn(async move { forward_read(&backend_r, team_id, person_id).await });+ tokio::time::sleep(Duration::from_millis(100)).await;++ handler.drain_stash(partition, "leader-new").await.unwrap();++ let code = decode_response::<GetPersonResponse>(read.await.unwrap())+ .await+ .expect_err("past-deadline read must fail fast");+ assert_eq!(+ code,+ Code::Unavailable,+ "past-deadline stashed reads must surface as retryable UNAVAILABLE"+ );+}+/// Convergence invariant: the loop-drain must terminate even when new/// requests keep arriving during drain (so long as forward-rate keeps/// up with arrival-rate). This test produces a steady stream of