: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): route leaders by registered advertise address (#73594)
Zach Brownccc779ecdffc
diff --git a/rust/personhog-coordination/src/coordinator.rs b/rust/personhog-coordination/src/coordinator.rsindex c6bfd8c2d80d..f7937fa8e92a 100644--- a/rust/personhog-coordination/src/coordinator.rs+++ b/rust/personhog-coordination/src/coordinator.rs@@ -636,6 +636,10 @@ impl Coordinator {partition: h.partition,old_owner: h.old_owner.clone(),new_owner: h.new_owner.clone(),+ new_owner_address: pods+ .iter()+ .find(|p| p.pod_name == h.new_owner)+ .and_then(|p| p.advertise_address.clone()),phase: HandoffPhase::Freezing,started_at: now,handoff_id: util::new_handoff_id(),@@ -877,6 +881,7 @@ mod tests {registered_at: 0,last_heartbeat: 0,controller: None,+ advertise_address: None,}}diff --git a/rust/personhog-coordination/src/pod.rs b/rust/personhog-coordination/src/pod.rsindex b88bd0265c9b..5893e97522a8 100644--- a/rust/personhog-coordination/src/pod.rs+++ b/rust/personhog-coordination/src/pod.rs@@ -146,6 +146,9 @@ pub struct PodConfig {/// Should be less than K8s terminationGracePeriodSeconds to allow/// time for lease revocation before SIGKILL.pub drain_timeout: Duration,+ /// `host:port` where this pod's gRPC server is reachable; registered+ /// so routers can dial the pod through the routing table.+ pub advertise_address: Option<String>,}impl Default for PodConfig {@@ -157,6 +160,7 @@ impl Default for PodConfig {lease_ttl: 30,heartbeat_interval: Duration::from_secs(10),drain_timeout: Duration::from_secs(30),+ advertise_address: None,}}}@@ -316,6 +320,7 @@ impl PodHandle {registered_at: now,last_heartbeat: now,controller: self.config.controller.clone(),+ advertise_address: self.config.advertise_address.clone(),};self.store.register_pod(&pod, lease_id).await}@@ -613,6 +618,7 @@ mod tests {PartitionAssignment {partition: 1,owner: owner.to_string(),+ advertise_address: None,status: AssignmentStatus::Active,}}@@ -625,6 +631,7 @@ mod tests {phase,started_at: 0,handoff_id: "h-test".to_string(),+ new_owner_address: None,}}diff --git a/rust/personhog-coordination/src/protocol.rs b/rust/personhog-coordination/src/protocol.rsindex b2b32170b626..9c3067273a0f 100644--- a/rust/personhog-coordination/src/protocol.rs+++ b/rust/personhog-coordination/src/protocol.rs@@ -191,6 +191,7 @@ mod tests {phase: crate::types::HandoffPhase::Warming,started_at: 0,handoff_id: String::new(),+ new_owner_address: None,}}diff --git a/rust/personhog-coordination/src/routing_table.rs b/rust/personhog-coordination/src/routing_table.rsindex 6ed668a8e863..453fb5581b96 100644--- a/rust/personhog-coordination/src/routing_table.rs+++ b/rust/personhog-coordination/src/routing_table.rs@@ -1,5 +1,5 @@use std::collections::HashMap;-use std::sync::Arc;+use std::sync::{Arc, RwLock as StdRwLock};use std::time::Duration;use async_trait::async_trait;@@ -11,7 +11,7 @@ use assignment_coordination::store::parse_watch_value;use crate::error::{Error, Result};use crate::store::{self, PersonhogStore};-use crate::types::{HandoffPhase, HandoffState, RegisteredRouter, RouterFreezeAck};+use crate::types::{HandoffPhase, HandoffState, RegisteredPod, RegisteredRouter, RouterFreezeAck};use crate::util;/// Trait for the router-side stash handler. Implementations are responsible@@ -75,6 +75,13 @@ pub struct RoutingTable {store: Arc<PersonhogStore>,config: RoutingTableConfig,table: Arc<RwLock<HashMap<u32, String>>>,+ /// `pod_name` → advertised `host:port`, learned from the same+ /// assignments and handoff events that drive `table`, so reachability+ /// can never lag ownership. Entries for departed pods linger until+ /// overwritten; lookups only ever go through current owners. A std+ /// lock (never held across await) so the leader backend's synchronous+ /// address resolver can read it.+ addresses: Arc<StdRwLock<HashMap<String, String>>>,}impl RoutingTable {@@ -83,6 +90,7 @@ impl RoutingTable {store,config,table: Arc::new(RwLock::new(HashMap::new())),+ addresses: Arc::new(StdRwLock::new(HashMap::new())),}}@@ -104,6 +112,12 @@ impl RoutingTable {Arc::clone(&self.table)}+ /// Shared handle to the pod-name → advertised-address map, for the+ /// leader backend's dialing.+ pub fn addresses_handle(&self) -> Arc<StdRwLock<HashMap<String, String>>> {+ Arc::clone(&self.addresses)+ }+/// Run the routing table. Registers with etcd, loads the initial state,/// then watches the handoffs keyspace. Blocks until cancelled. Routing/// changes flow exclusively through handoff Complete events; there is@@ -123,7 +137,15 @@ impl RoutingTable {let lease_id = self.store.grant_lease(self.config.lease_ttl).await?;self.register_router(lease_id).await?;- let snapshot_revision = self.load_initial(&handler).await?;+ let (snapshot_revision, pods_revision) = self.load_initial(&handler).await?;++ // The pod watch anchors strictly after the pod snapshot, exactly+ // like the handoff watch below: nothing older than the snapshot+ // is ever replayed, so a registration installed by the snapshot+ // can never be regressed by a replayed predecessor. (Anchoring+ // before the snapshot — the coordinator's pattern — is only safe+ // for CAS-guarded consumers; this map is last-writer-wins.)+ let pods_stream = self.store.watch_pods_from(pods_revision + 1).await?;// Anchor the handoff watch to the snapshot's revision: every event// at or before it was handled by `load_initial`, every later one@@ -147,15 +169,32 @@ impl RoutingTable {});}+ {+ let addresses = Arc::clone(&self.addresses);+ let token = cancel.child_token();+ tasks.spawn(async move {+ Self::watch_pod_addresses_loop(addresses, token, pods_stream).await+ });+ }+{let store = Arc::clone(&self.store);let table = Arc::clone(&self.table);+ let addresses = Arc::clone(&self.addresses);let handler = Arc::clone(&handler);let router_name = self.config.router_name.clone();let token = cancel.child_token();tasks.spawn(async move {- Self::watch_handoffs_loop(store, table, handler, router_name, token, handoff_stream)- .await+ Self::watch_handoffs_loop(+ store,+ table,+ addresses,+ handler,+ router_name,+ token,+ handoff_stream,+ )+ .await});}@@ -188,9 +227,9 @@ impl RoutingTable {self.store.register_router(&router, lease_id).await}- /// Returns the etcd revision of the handoff snapshot, so the caller- /// can anchor the handoff watch to it.- async fn load_initial(&self, handler: &Arc<dyn StashHandler>) -> Result<i64> {+ /// Returns the etcd revisions of the handoff and pod snapshots, so+ /// the caller can anchor each watch strictly after its own snapshot.+ async fn load_initial(&self, handler: &Arc<dyn StashHandler>) -> Result<(i64, i64)> {// Catch up on any in-progress handoffs BEFORE populating the// routing table. The table starts empty, so every lookup fails// closed until it is loaded; opening the stashes first guarantees@@ -241,19 +280,82 @@ impl RoutingTable {}let assignments = self.store.list_assignments().await?;+ // Live registrations overlay assignment-carried addresses: an+ // assignment's address is a snapshot from the handoff that+ // installed the owner, and the owner may have re-registered at a+ // new address since (same pod name, new IP) without any handoff.+ // Registrations are the authority on addresses; everything else+ // is a fallback for entries the registration feed hasn't covered.+ let (pods, pods_revision) = self.store.list_pods_with_revision().await?;let mut table = self.table.write().await;+ {+ let mut addresses = self.addresses.write().expect("addresses lock poisoned");+ for a in &assignments {+ if let Some(address) = &a.advertise_address {+ addresses.insert(a.owner.clone(), address.clone());+ }+ }+ for pod in pods {+ if let Some(address) = pod.advertise_address {+ addresses.insert(pod.pod_name, address);+ }+ }+ }for a in assignments {table.insert(a.partition, a.owner);}tracing::info!(count = table.len(), "loaded initial routing table");drop(table);- Ok(snapshot_revision)+ Ok((snapshot_revision, pods_revision))}+ /// Keep the address map current with pod registrations. Ownership is+ /// untouched — routing still moves only on handoff events — but a pod+ /// that re-registers under the same name at a new address (a restart+ /// that kept its assignments) must refresh where the router dials, or+ /// every dial keeps hitting the dead address until the next handoff.+ /// Deletes are ignored: a lease expiry precedes either a re-register+ /// (which overwrites) or a handoff away (after which the entry is+ /// never consulted).+ async fn watch_pod_addresses_loop(+ addresses: Arc<StdRwLock<HashMap<String, String>>>,+ cancel: CancellationToken,+ mut stream: WatchStream,+ ) -> Result<()> {+ loop {+ tokio::select! {+ _ = cancel.cancelled() => return Ok(()),+ msg = stream.message() => {+ let resp = msg?.ok_or_else(|| Error::invalid_state("pod watch stream ended".to_string()))?;+ for event in resp.events() {+ if event.event_type() != EventType::Put {+ continue;+ }+ let pod: RegisteredPod = match parse_watch_value(event) {+ Ok(p) => p,+ Err(e) => {+ tracing::error!(error = %e, "failed to parse pod event");+ continue;+ }+ };+ if let Some(address) = pod.advertise_address {+ addresses+ .write()+ .expect("addresses lock poisoned")+ .insert(pod.pod_name, address);+ }+ }+ }+ }+ }+ }++ #[allow(clippy::too_many_arguments)]async fn watch_handoffs_loop(store: Arc<PersonhogStore>,table: Arc<RwLock<HashMap<u32, String>>>,+ addresses: Arc<StdRwLock<HashMap<String, String>>>,handler: Arc<dyn StashHandler>,router_name: String,cancel: CancellationToken,@@ -271,6 +373,7 @@ impl RoutingTable {event,store.as_ref(),&table,+ &addresses,handler.as_ref(),&router_name,).await?;@@ -319,6 +422,7 @@ impl RoutingTable {event: &etcd_client::Event,store: &PersonhogStore,table: &Arc<RwLock<HashMap<u32, String>>>,+ addresses: &Arc<StdRwLock<HashMap<String, String>>>,handler: &dyn StashHandler,router_name: &str,) -> Result<()> {@@ -357,6 +461,34 @@ impl RoutingTable {}}HandoffPhase::Complete => {+ // The address must land before the table flips: the drain+ // below dials the new owner immediately. Insert only if+ // absent — the handoff carries an address snapshotted at+ // handoff creation, and the pod may have re-registered at+ // a newer address since; the registration feed (a separate+ // stream with no cross-stream ordering) is the authority+ // and must never be overwritten by this fallback.+ match &handoff.new_owner_address {+ Some(address) => {+ addresses+ .write()+ .expect("addresses lock poisoned")+ .entry(handoff.new_owner.clone())+ .or_insert_with(|| address.clone());+ }+ None => {+ // Only possible for handoffs written by a+ // pre-advertise-address coordinator; dials to this+ // owner fail closed until it re-registers.+ tracing::warn!(+ router = %router_name,+ partition = handoff.partition,+ new_owner = %handoff.new_owner,+ "handoff carries no advertise address"+ );+ }+ }+// Pre-update the routing table before draining so that any// new request arriving between drain and the independent// assignment-watch dispatch routes to the new owner ratherdiff --git a/rust/personhog-coordination/src/store.rs b/rust/personhog-coordination/src/store.rsindex b26667201aba..baab0d6a2ea5 100644--- a/rust/personhog-coordination/src/store.rs+++ b/rust/personhog-coordination/src/store.rs@@ -111,6 +111,13 @@ impl PersonhogStore {Ok(self.inner.list(&key).await?)}+ /// List pods along with the etcd revision of the snapshot, so a watch+ /// can be anchored strictly after it.+ pub async fn list_pods_with_revision(&self) -> Result<(Vec<RegisteredPod>, i64)> {+ let key = self.key(StoreKey::PodsPrefix);+ Ok(self.inner.list_with_revision(&key).await?)+ }+pub async fn update_pod_status(&self,pod_name: &str,@@ -526,6 +533,7 @@ impl PersonhogStore {let assignment = PartitionAssignment {partition,owner: handoff.new_owner.clone(),+ advertise_address: handoff.new_owner_address.clone(),status: AssignmentStatus::Active,};diff --git a/rust/personhog-coordination/src/types.rs b/rust/personhog-coordination/src/types.rsindex ae8494829392..3e1bcc26d4a5 100644--- a/rust/personhog-coordination/src/types.rs+++ b/rust/personhog-coordination/src/types.rs@@ -20,6 +20,15 @@ pub struct RegisteredPod {/// Populated via K8s awareness on registration. None when K8s awareness is disabled.#[serde(default, skip_serializing_if = "Option::is_none")]pub controller: Option<ControllerRef>,+ /// `host:port` where this pod's gRPC server is reachable. Derived by+ /// the pod from its bind address (and POD_IP when binding a wildcard),+ /// so the advertised port is definitionally the serving port. Travels+ /// with ownership: the coordinator copies it into every handoff and+ /// assignment naming this pod, which is how routers learn where to+ /// dial without a second discovery system. `None` only for+ /// registrations written by binaries that predate the field.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub advertise_address: Option<String>,}/// Lifecycle status of a writer pod.@@ -50,6 +59,11 @@ pub struct PartitionAssignment {pub partition: u32,/// The `pod_name` of the writer pod that currently owns this partition.pub owner: String,+ /// The owner's advertised `host:port`, copied from its registration+ /// via the handoff that installed it. Routers load it with the+ /// assignment so reachability arrives with ownership.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub advertise_address: Option<String>,pub status: AssignmentStatus,}@@ -93,6 +107,11 @@ pub struct HandoffState {#[serde(default, skip_serializing_if = "Option::is_none")]pub old_owner: Option<String>,pub new_owner: String,+ /// The new owner's advertised `host:port`, copied from its+ /// registration when the coordinator creates the handoff; lands in+ /// the assignment at Complete.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub new_owner_address: Option<String>,pub phase: HandoffPhase,pub started_at: i64,/// Unique identity of this handoff attempt. Acks echo it, and the@@ -214,6 +233,7 @@ mod tests {registered_at: 1700000000,last_heartbeat: 1700000010,controller: None,+ advertise_address: None,};let json = serde_json::to_string(&pod).unwrap();let deserialized: RegisteredPod = serde_json::from_str(&json).unwrap();@@ -237,6 +257,7 @@ mod tests {let assignment = PartitionAssignment {partition: 42,owner: "personhog-writer-1".to_string(),+ advertise_address: Some("10.1.2.3:50053".to_string()),status: AssignmentStatus::Active,};let json = serde_json::to_string(&assignment).unwrap();@@ -244,6 +265,22 @@ mod tests {assert_eq!(assignment, deserialized);}+ /// Records written by binaries that predate advertise addresses must+ /// keep deserializing — the field arrives mid-rollout.+ #[test]+ fn pre_advertise_address_records_deserialize() {+ let assignment: PartitionAssignment = serde_json::from_str(+ r#"{"partition":1,"owner":"personhog-leader-0","status":"Active"}"#,+ )+ .unwrap();+ assert_eq!(assignment.advertise_address, None);+ let handoff: HandoffState = serde_json::from_str(+ r#"{"partition":1,"new_owner":"personhog-leader-0","phase":"Freezing","started_at":0}"#,+ )+ .unwrap();+ assert_eq!(handoff.new_owner_address, None);+ }+#[test]fn handoff_state_roundtrip() {let handoff = HandoffState {@@ -253,6 +290,7 @@ mod tests {phase: HandoffPhase::Freezing,started_at: 1700000000,handoff_id: "1700000000000-0".to_string(),+ new_owner_address: None,};let json = serde_json::to_string(&handoff).unwrap();let deserialized: HandoffState = serde_json::from_str(&json).unwrap();@@ -268,6 +306,7 @@ mod tests {phase: HandoffPhase::Freezing,started_at: 1700000000,handoff_id: "1700000000000-0".to_string(),+ new_owner_address: None,};let json = serde_json::to_string(&handoff).unwrap();let deserialized: HandoffState = serde_json::from_str(&json).unwrap();diff --git a/rust/personhog-coordination/tests/common/mod.rs b/rust/personhog-coordination/tests/common/mod.rsindex 4238d9ecf9c5..ad62a8bacef6 100644--- a/rust/personhog-coordination/tests/common/mod.rs+++ b/rust/personhog-coordination/tests/common/mod.rs@@ -120,6 +120,16 @@ pub fn start_pod_with_lease_ttl(name: &str,lease_ttl: i64,cancel: CancellationToken,+) -> PodHandles {+ start_pod_with_address(store, name, lease_ttl, None, cancel)+}++pub fn start_pod_with_address(+ store: Arc<PersonhogStore>,+ name: &str,+ lease_ttl: i64,+ advertise_address: Option<String>,+ cancel: CancellationToken,) -> PodHandles {let heartbeat_secs = (lease_ttl as u64 / 3).max(1);let (handler, events) = MockHandoffHandler::new();@@ -129,6 +139,7 @@ pub fn start_pod_with_lease_ttl(pod_name: name.to_string(),lease_ttl,heartbeat_interval: Duration::from_secs(heartbeat_secs),+ advertise_address,..Default::default()},Arc::new(handler),@@ -216,6 +227,7 @@ pub fn start_pod_slow(pub struct RouterHandles {pub events: Arc<Mutex<Vec<CutoverEvent>>>,+ pub addresses: Arc<std::sync::RwLock<std::collections::HashMap<String, String>>>,pub table: Arc<tokio::sync::RwLock<std::collections::HashMap<u32, String>>>,pub join_handle: Option<JoinHandle<Result<()>>>,}@@ -245,10 +257,12 @@ pub fn start_router_with_lease_ttl(},);let table = router.table_handle();+ let addresses = router.addresses_handle();let token = cancel.child_token();let join_handle = tokio::spawn(async move { router.run(token, Arc::new(handler)).await });RouterHandles {events,+ addresses,table,join_handle: Some(join_handle),}diff --git a/rust/personhog-coordination/tests/integration.rs b/rust/personhog-coordination/tests/integration.rsindex 9a8c8f7edac7..f1320b48d24b 100644--- a/rust/personhog-coordination/tests/integration.rs+++ b/rust/personhog-coordination/tests/integration.rs@@ -1417,6 +1417,7 @@ async fn handoff_delete_drains_stash_to_current_owner() {phase: HandoffPhase::Freezing,started_at: 0,handoff_id: String::new(),+ new_owner_address: None,};store.put_handoff(&stuck_handoff).await.unwrap();@@ -1493,6 +1494,178 @@ async fn handoff_delete_drains_stash_to_current_owner() {cancel.cancel();}+/// A handoff Complete carries an address snapshotted at handoff creation,+/// delivered on a stream with no ordering against the registration feed.+/// It may only fill a hole, never overwrite: a fresher re-registration+/// must survive a stale handoff-carried address arriving after it.+#[tokio::test]+async fn stale_handoff_address_never_overwrites_a_fresher_registration() {+ let store = test_store("addr-authority").await;+ let cancel = CancellationToken::new();++ store.set_total_partitions(NUM_PARTITIONS).await.unwrap();++ let strategy: Arc<dyn AssignmentStrategy> = Arc::new(StickyBalancedStrategy);+ let _coord = start_coordinator(Arc::clone(&store), strategy, cancel.clone());+ let router = start_router(Arc::clone(&store), "router-0", cancel.clone());+ let _pod = common::start_pod_with_address(+ Arc::clone(&store),+ "writer-0",+ 10,+ Some("10.0.0.2:50053".to_string()),+ cancel.clone(),+ );++ // Settle and learn the registered address.+ let addresses = Arc::clone(&router.addresses);+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {+ let addresses = Arc::clone(&addresses);+ async move {+ addresses+ .read()+ .unwrap()+ .get("writer-0")+ .map(String::as_str)+ == Some("10.0.0.2:50053")+ }+ })+ .await;++ // A Complete handoff arrives carrying a stale address (snapshotted+ // before the pod's latest registration). It must not clobber.+ store+ .put_handoff(&personhog_coordination::types::HandoffState {+ partition: 0,+ old_owner: None,+ new_owner: "writer-0".to_string(),+ new_owner_address: Some("10.0.0.1:50053".to_string()),+ phase: personhog_coordination::types::HandoffPhase::Complete,+ started_at: 0,+ handoff_id: "h-stale-addr".to_string(),+ })+ .await+ .unwrap();++ // The Complete still flows through the routing table (table update ++ // drain); wait for it to be observed, then assert the address held.+ let table = Arc::clone(&router.table);+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {+ let table = Arc::clone(&table);+ async move { table.read().await.get(&0).map(String::as_str) == Some("writer-0") }+ })+ .await;+ assert_eq!(+ addresses+ .read()+ .unwrap()+ .get("writer-0")+ .map(String::as_str),+ Some("10.0.0.2:50053"),+ "registration-fed address must survive a stale handoff-carried one"+ );++ cancel.cancel();+}++/// A leader that restarts under the same pod name at a new address while+/// keeping its assignments produces no handoff — the router must learn+/// the new address from the pod registration watch, or every dial keeps+/// hitting the dead address until the next rebalance.+#[tokio::test]+async fn pod_re_registration_refreshes_router_addresses_without_a_handoff() {+ let store = test_store("addr-refresh").await;+ let cancel = CancellationToken::new();++ store.set_total_partitions(NUM_PARTITIONS).await.unwrap();++ let strategy: Arc<dyn AssignmentStrategy> = Arc::new(StickyBalancedStrategy);+ let _coord = start_coordinator(Arc::clone(&store), strategy, cancel.clone());+ let router = start_router(Arc::clone(&store), "router-0", cancel.clone());+ let _pod = common::start_pod_with_address(+ Arc::clone(&store),+ "writer-0",+ 10,+ Some("10.0.0.1:50053".to_string()),+ cancel.clone(),+ );++ // Settle: all partitions assigned to writer-0, addresses learned.+ let check_store = Arc::clone(&store);+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {+ let store = Arc::clone(&check_store);+ async move {+ let assignments = store.list_assignments().await.unwrap_or_default();+ let handoffs = store.list_handoffs().await.unwrap_or_default();+ assignments.len() == NUM_PARTITIONS as usize && handoffs.is_empty()+ }+ })+ .await;+ let addresses = Arc::clone(&router.addresses);+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {+ let addresses = Arc::clone(&addresses);+ async move {+ addresses+ .read()+ .unwrap()+ .get("writer-0")+ .map(String::as_str)+ == Some("10.0.0.1:50053")+ }+ })+ .await;++ // Same pod name re-registers at a new address (a restart that kept+ // its IP-independent identity) — no pod-set change, so no handoff.+ let lease = store.grant_lease(10).await.unwrap();+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_secs() as i64;+ store+ .register_pod(+ &personhog_coordination::types::RegisteredPod {+ pod_name: "writer-0".to_string(),+ generation: String::new(),+ status: personhog_coordination::types::PodStatus::Ready,+ registered_at: now,+ last_heartbeat: now,+ controller: None,+ advertise_address: Some("10.0.0.2:50053".to_string()),+ },+ lease,+ )+ .await+ .unwrap();++ let addresses = Arc::clone(&router.addresses);+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {+ let addresses = Arc::clone(&addresses);+ async move {+ addresses+ .read()+ .unwrap()+ .get("writer-0")+ .map(String::as_str)+ == Some("10.0.0.2:50053")+ }+ })+ .await;++ // The refresh came from the registration watch alone: ownership never+ // moved and the persisted assignments still carry the old snapshot.+ let handoffs = store.list_handoffs().await.unwrap();+ assert!(handoffs.is_empty(), "no handoff may be involved");+ let assignments = store.list_assignments().await.unwrap();+ assert!(+ assignments+ .iter()+ .all(|a| a.owner == "writer-0"+ && a.advertise_address.as_deref() == Some("10.0.0.1:50053"))+ );++ cancel.cancel();+}+/// When the routing table sees a handoff Complete, it should update the/// table to point at the new owner inline. This proves the inline routing/// update inside `handle_handoff_put` runs (the assignment watch is gone).@@ -1590,6 +1763,7 @@ async fn late_joining_router_during_warming_begins_stash() {phase: HandoffPhase::Warming,started_at: 0,handoff_id: String::new(),+ new_owner_address: None,};store.put_handoff(&warming_handoff).await.unwrap();@@ -1653,6 +1827,7 @@ async fn dead_old_owner_in_freezing_advances_to_completion() {phase: HandoffPhase::Freezing,started_at: 0,handoff_id: String::new(),+ new_owner_address: None,};store.put_handoff(&stale).await.unwrap();@@ -1704,6 +1879,7 @@ async fn late_joining_router_during_freezing_acks_and_stashes() {phase: HandoffPhase::Freezing,started_at: 0,handoff_id: String::new(),+ new_owner_address: None,};store.put_handoff(&freezing_handoff).await.unwrap();@@ -1782,6 +1958,7 @@ async fn handoff_delete_during_warming_drains_to_current_owner() {phase: HandoffPhase::Warming,started_at: 0,handoff_id: String::new(),+ new_owner_address: None,};store.put_handoff(&stuck).await.unwrap();@@ -1879,6 +2056,7 @@ async fn reconcile_advances_warming_with_pre_staged_warmed_ack() {phase: HandoffPhase::Warming,started_at: 0,handoff_id: String::new(),+ new_owner_address: None,};store.put_handoff(&warming).await.unwrap();store@@ -1945,6 +2123,7 @@ async fn draining_old_owner_blocks_phase_advance() {registered_at: 0,last_heartbeat: 0,controller: None,+ advertise_address: None,};store.register_pod(&draining_pod, lease).await.unwrap();@@ -1956,6 +2135,7 @@ async fn draining_old_owner_blocks_phase_advance() {phase: HandoffPhase::Freezing,started_at: 0,handoff_id: String::new(),+ new_owner_address: None,};store.put_handoff(&handoff).await.unwrap();@@ -2044,6 +2224,7 @@ async fn draining_old_owner_does_not_trigger_cleanup() {registered_at: 0,last_heartbeat: 0,controller: None,+ advertise_address: None,};store.register_pod(&draining_pod, lease).await.unwrap();@@ -2055,6 +2236,7 @@ async fn draining_old_owner_does_not_trigger_cleanup() {phase: HandoffPhase::Freezing,started_at: 0,handoff_id: String::new(),+ new_owner_address: None,};store.put_handoff(&handoff).await.unwrap();@@ -2113,6 +2295,7 @@ async fn freezing_blocks_until_routers_ack_before_draining() {registered_at: 0,last_heartbeat: 0,controller: None,+ advertise_address: None,};store.register_pod(&pod, lease).await.unwrap();}@@ -2143,6 +2326,7 @@ async fn freezing_blocks_until_routers_ack_before_draining() {phase: HandoffPhase::Freezing,started_at: 0,handoff_id: String::new(),+ new_owner_address: None,};store.put_handoff(&handoff).await.unwrap();@@ -2211,6 +2395,7 @@ async fn initial_assignment_skips_draining_phase() {registered_at: 0,last_heartbeat: 0,controller: None,+ advertise_address: None,};store.register_pod(&new_pod, lease).await.unwrap();@@ -2228,6 +2413,7 @@ async fn initial_assignment_skips_draining_phase() {phase: HandoffPhase::Freezing,started_at: 0,handoff_id: String::new(),+ new_owner_address: None,};store.put_handoff(&handoff).await.unwrap();@@ -2273,6 +2459,7 @@ async fn dead_old_owner_in_draining_recovers() {registered_at: 0,last_heartbeat: 0,controller: None,+ advertise_address: None,};store.register_pod(&pod, lease).await.unwrap();}@@ -2285,6 +2472,7 @@ async fn dead_old_owner_in_draining_recovers() {phase: HandoffPhase::Draining,started_at: 0,handoff_id: String::new(),+ new_owner_address: None,};store.put_handoff(&handoff).await.unwrap();@@ -2371,6 +2559,7 @@ async fn reconcile_advances_draining_with_pre_staged_drained_ack() {registered_at: 0,last_heartbeat: 0,controller: None,+ advertise_address: None,};store.register_pod(&pod, lease).await.unwrap();}@@ -2382,6 +2571,7 @@ async fn reconcile_advances_draining_with_pre_staged_drained_ack() {phase: HandoffPhase::Draining,started_at: 0,handoff_id: String::new(),+ new_owner_address: None,};store.put_handoff(&handoff).await.unwrap();@@ -2440,6 +2630,7 @@ async fn late_joining_router_during_draining_begins_stash_no_ack() {phase: HandoffPhase::Draining,started_at: 0,handoff_id: String::new(),+ new_owner_address: None,};store.put_handoff(&draining_handoff).await.unwrap();@@ -2523,6 +2714,7 @@ async fn handoff_delete_during_draining_drains_to_current_owner() {phase: HandoffPhase::Draining,started_at: 0,handoff_id: String::new(),+ new_owner_address: None,};store.put_handoff(&stuck).await.unwrap();@@ -2768,6 +2960,7 @@ async fn conflicting_plan_cannot_replace_an_in_flight_handoff() {phase: HandoffPhase::Warming,started_at: 0,handoff_id: "first".to_string(),+ new_owner_address: None,};assert!(store.create_assignments_and_handoffs(&[], std::slice::from_ref(&first), &[])@@ -2783,11 +2976,13 @@ async fn conflicting_plan_cannot_replace_an_in_flight_handoff() {phase: HandoffPhase::Freezing,started_at: 0,handoff_id: "second".to_string(),+ new_owner_address: None,};let stable = PartitionAssignment {partition: 1,owner: "writer-0".to_string(),status: AssignmentStatus::Active,+ advertise_address: None,};assert!(!store.create_assignments_and_handoffs(&[stable], &[competing], &[])@@ -2820,6 +3015,7 @@ async fn stale_plan_is_rejected_when_the_assignment_moved() {partition: 0,owner: owner.to_string(),status: AssignmentStatus::Active,+ advertise_address: None,};let handoff = |old: &str, new: &str, id: &str| HandoffState {partition: 0,@@ -2828,6 +3024,7 @@ async fn stale_plan_is_rejected_when_the_assignment_moved() {phase: HandoffPhase::Freezing,started_at: 0,handoff_id: id.to_string(),+ new_owner_address: None,};// The world the stale planner reads: partition 0 owned by A.@@ -2904,6 +3101,7 @@ async fn fresh_plan_is_rejected_when_an_assignment_appeared() {phase: HandoffPhase::Freezing,started_at: 0,handoff_id: id.to_string(),+ new_owner_address: None,};// Partition 0 gained an assignment after the plan's snapshot.@@ -2913,6 +3111,7 @@ async fn fresh_plan_is_rejected_when_an_assignment_appeared() {partition: 0,owner: "pod-b".to_string(),status: AssignmentStatus::Active,+ advertise_address: None,}],&[],&[],diff --git a/rust/personhog-coordination/tests/k3s_integration.rs b/rust/personhog-coordination/tests/k3s_integration.rsindex c27386cfa946..f763ebf1dc29 100644--- a/rust/personhog-coordination/tests/k3s_integration.rs+++ b/rust/personhog-coordination/tests/k3s_integration.rs@@ -673,6 +673,7 @@ async fn statefulset_rollout_pod_skips_drain() {lease_ttl: 10,heartbeat_interval: Duration::from_secs(3),drain_timeout: Duration::from_secs(30),+ advertise_address: None,};let (_pod_events, pod_handle) = start_pod_k8s(Arc::clone(&store),diff --git a/rust/personhog-coordination/tests/protocol_hardening.rs b/rust/personhog-coordination/tests/protocol_hardening.rsindex 96400199e490..08c371e3c0a9 100644--- a/rust/personhog-coordination/tests/protocol_hardening.rs+++ b/rust/personhog-coordination/tests/protocol_hardening.rs@@ -48,6 +48,7 @@ async fn put_handoff(phase,started_at: 0,handoff_id: format!("test-handoff-{partition}"),+ new_owner_address: None,};// Raw put on purpose: fixtures force arbitrary handoff states,// including overwriting an existing one, which the guarded@@ -384,11 +385,13 @@ async fn restarted_pod_rewarms_assigned_partitions() {partition: 0,owner: "phoenix-pod".to_string(),status: AssignmentStatus::Active,+ advertise_address: None,},PartitionAssignment {partition: 1,owner: "phoenix-pod".to_string(),status: AssignmentStatus::Active,+ advertise_address: None,},]).await@@ -427,6 +430,7 @@ async fn restarted_old_owner_serves_again_after_handoff_cancelled() {partition: 0,owner: "victim-pod".to_string(),status: AssignmentStatus::Active,+ advertise_address: None,}]).await.expect("write assignment");@@ -476,6 +480,7 @@ async fn restarted_old_owner_refences_when_handoff_in_warming() {partition: 0,owner: "frozen-pod".to_string(),status: AssignmentStatus::Active,+ advertise_address: None,}]).await.expect("write assignment");@@ -797,6 +802,7 @@ async fn dead_old_owner_handoff_advances_in_place_not_cleaned_up() {registered_at: 0,last_heartbeat: 0,controller: None,+ advertise_address: None,},lease,)@@ -848,6 +854,7 @@ async fn dead_old_owner_handoff_advances_in_place_not_cleaned_up() {registered_at: 0,last_heartbeat: 0,controller: None,+ advertise_address: None,},bystander_lease,)@@ -1320,6 +1327,7 @@ async fn late_joining_router_stashes_before_populating_table() {partition: 0,owner: "pod-old".to_string(),status: AssignmentStatus::Active,+ advertise_address: None,}],&[],&[],diff --git a/rust/personhog-leader/src/config.rs b/rust/personhog-leader/src/config.rsindex b9d5124ae750..6b4d37a44e0b 100644--- a/rust/personhog-leader/src/config.rs+++ b/rust/personhog-leader/src/config.rs@@ -223,6 +223,12 @@ pub struct Config {#[envconfig(default = "leader-0")]pub pod_name: String,+ /// Pod IP from the K8s downward API (`status.podIP`), injected by the+ /// chart. Used to derive the advertised gRPC address when binding a+ /// wildcard. Unset in local runs, which bind a concrete address.+ #[envconfig(default = "")]+ pub pod_ip: String,+#[envconfig(default = "30")]pub lease_ttl: i64,@@ -267,3 +273,51 @@ impl Config {Duration::from_secs(self.heartbeat_interval_secs)}}++/// Derive the `host:port` this leader should advertise for routing.+///+/// The advertised port is always the serving port (taken from the bind+/// address), so it cannot drift from reality. The host is the bind host+/// when it is concrete (local runs bind `127.0.0.1:<port>`), or POD_IP+/// when binding a wildcard (deployments bind `0.0.0.0`). Wildcard with no+/// POD_IP fails closed: a leader that cannot say where it is reachable+/// must not register and claim partitions.+pub fn derive_advertise_address(+ grpc_address: &std::net::SocketAddr,+ pod_ip: &str,+) -> Result<String, String> {+ if !grpc_address.ip().is_unspecified() {+ return Ok(grpc_address.to_string());+ }+ if pod_ip.is_empty() {+ return Err(format!(+ "cannot derive an advertise address: GRPC_ADDRESS binds the wildcard \+ {grpc_address} and POD_IP is not set — routers would have nowhere to dial"+ ));+ }+ Ok(format!("{pod_ip}:{}", grpc_address.port()))+}++#[cfg(test)]+mod tests {+ use super::derive_advertise_address;++ #[test]+ fn advertise_address_prefers_concrete_bind_and_requires_pod_ip_for_wildcards() {+ let concrete = "127.0.0.1:50060".parse().unwrap();+ assert_eq!(+ derive_advertise_address(&concrete, "").unwrap(),+ "127.0.0.1:50060"+ );++ let wildcard = "0.0.0.0:50053".parse().unwrap();+ assert_eq!(+ derive_advertise_address(&wildcard, "10.1.2.3").unwrap(),+ "10.1.2.3:50053"+ );+ assert!(derive_advertise_address(&wildcard, "").is_err());++ let wildcard6 = "[::]:50053".parse().unwrap();+ assert!(derive_advertise_address(&wildcard6, "").is_err());+ }+}diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rsindex f7ea9aedb7a3..58caa5b7506e 100644--- a/rust/personhog-leader/src/main.rs+++ b/rust/personhog-leader/src/main.rs@@ -243,12 +243,18 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {},},);+ let advertise_address =+ personhog_leader::config::derive_advertise_address(&config.grpc_address, &config.pod_ip)+ .expect("Invalid advertise address configuration");+ tracing::info!(%advertise_address, "advertising gRPC address for routing");+let pod = PodHandle::new(store,PodConfig {pod_name: config.pod_name.clone(),lease_ttl: config.lease_ttl,heartbeat_interval: config.heartbeat_interval(),+ advertise_address: Some(advertise_address),..Default::default()},Arc::new(handler),diff --git a/rust/personhog-router/src/config.rs b/rust/personhog-router/src/config.rsindex d149a21a7402..be7c56db18f4 100644--- a/rust/personhog-router/src/config.rs+++ b/rust/personhog-router/src/config.rs@@ -174,10 +174,6 @@ pub struct Config {#[envconfig(default = "3")]pub heartbeat_interval_secs: u64,- /// Leader gRPC port used when resolving pod names to addresses- #[envconfig(default = "50053")]- pub leader_port: u16,-/// Maximum number of stashed write requests held per partition while/// a handoff is in progress. Excess requests return UNAVAILABLE and/// rely on caller-side retries.diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rsindex 18074f15f1d2..9e0ba9dc60a3 100644--- a/rust/personhog-router/src/main.rs+++ b/rust/personhog-router/src/main.rs@@ -271,19 +271,20 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {RoutingTable::new(Arc::clone(&store), routing_table_config);let shared_table = coordination_routing_table.table_handle();- let leader_port = config.leader_port;- // Pods may register with an explicit `host:port` name (local- // multi-leader setups, where a single fleet-wide port cannot hold);- // those resolve as-is. Bare pod names resolve via DNS on the- // fleet-wide leader port.+ // Addresses come from the same etcd records that carry ownership+ // (each pod registers its advertised host:port, and the+ // coordinator copies it into handoffs and assignments), so a+ // routable owner is always dialable — there is no separate+ // discovery or DNS step to lag behind the routing table.+ let leader_addresses = coordination_routing_table.addresses_handle();let leader_backend = Arc::new(LeaderBackend::new(shared_table,Arc::new(move |pod_name: &str| {- if pod_name.contains(':') {- Some(format!("http://{pod_name}"))- } else {- Some(format!("http://{pod_name}:{leader_port}"))- }+ leader_addresses+ .read()+ .expect("addresses lock poisoned")+ .get(pod_name)+ .map(|address| format!("http://{address}"))}),LeaderBackendConfig {num_partitions,diff --git a/rust/personhog-stateright/src/model.rs b/rust/personhog-stateright/src/model.rsindex 4776669c4773..2edc92e9d524 100644--- a/rust/personhog-stateright/src/model.rs+++ b/rust/personhog-stateright/src/model.rs@@ -42,6 +42,9 @@ fn production_handoff(p: Partition, h: &Handoff) -> HandoffState {partition: p as u32,old_owner: h.old_owner.map(pod_name),new_owner: pod_name(h.new_owner),+ // The model verifies ownership/fencing; addresses are transport+ // detail outside its state space.+ new_owner_address: None,phase: h.phase,started_at: 0,handoff_id: h.id.to_string(),@@ -96,6 +99,7 @@ fn model_desired_state(pod: PodId, state: &SystemState, partition: Partition) ->.map(|owner| PartitionAssignment {partition: partition as u32,owner: pod_name(*owner),+ advertise_address: None,status: AssignmentStatus::Active,});let handoff = state@@ -505,6 +509,7 @@ impl Model for HandoffModel {registered_at: 0,last_heartbeat: 0,controller: None,+ advertise_address: None,}).collect();let acks: Vec<PodDrainedAck> = selfdiff --git a/rust/personhog-test-harness/src/stack/mod.rs b/rust/personhog-test-harness/src/stack/mod.rsindex 28f43f6192a0..50925388f062 100644--- a/rust/personhog-test-harness/src/stack/mod.rs+++ b/rust/personhog-test-harness/src/stack/mod.rs@@ -264,14 +264,18 @@ impl Stack {Ok(stack)}- /// Spawn one more leader. The pod registers with an explicit host:port- /// name, which the router's resolver dials as-is.+ /// Spawn one more leader. The pod derives its advertise address from+ /// its concrete bind and registers it for the router to dial.pub fn spawn_leader(&mut self) -> Result<String> {let index = self.next_leader_index;self.next_leader_index += 1;let grpc_port = LEADER_GRPC_BASE_PORT + index as u16;- let pod_name = format!("127.0.0.1:{grpc_port}");+ // A real pod name: the leader derives its advertise address from+ // its concrete bind, registers it, and the router dials what the+ // routing table carries — the same path a deployment takes.+ let pod_name = format!("personhog-leader-{index}");+ let grpc_address = format!("127.0.0.1:{grpc_port}");// Heartbeats must land well inside the lease window or a healthy// pod's lease expires between renewals.let heartbeat_secs = (self.config.leader_lease_ttl / 3).max(1);@@ -279,7 +283,7 @@ impl Stack {&format!("leader-{index}"),&self.config.bin_dir.join("personhog-leader"),&[- ("GRPC_ADDRESS", pod_name.clone()),+ ("GRPC_ADDRESS", grpc_address),("POD_NAME", pod_name.clone()),("LEASE_TTL", self.config.leader_lease_ttl.to_string()),("HEARTBEAT_INTERVAL_SECS", heartbeat_secs.to_string()),