Skip to content

: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.

fix(personhog): advance freezes on router departure and unblock shutdown teardown (#75715)

Zach Brown88534221fb78
diff --git a/rust/personhog-coordination/src/coordinator.rs b/rust/personhog-coordination/src/coordinator.rs
index f69d56193968..6de94dfaf1ed 100644
--- a/rust/personhog-coordination/src/coordinator.rs
+++ b/rust/personhog-coordination/src/coordinator.rs
@@ -36,12 +36,11 @@ pub struct CoordinatorConfig {
/// rapid pod registrations into a single rebalance.
pub rebalance_debounce_interval: Duration,
/// How often to re-evaluate in-flight handoffs regardless of watch
- /// events. Phase advancement is normally event-driven, but some state
- /// changes produce no watched event at all — a router departing
- /// (nothing watches router registrations) can newly satisfy a freeze
- /// quorum. The tick backstops those so handoffs cannot stall
- /// indefinitely, and doubles as defense-in-depth for anything else
- /// that slips through the event-driven paths.
+ /// events. Phase advancement is event-driven — acks, handoff writes,
+ /// and router departures are all watched — so the tick is pure
+ /// defense-in-depth: it catches a dropped stream or an event lost in
+ /// a coordinator failover window, keeping a handoff from stalling
+ /// indefinitely on a missed delivery.
pub reconcile_interval: Duration,
/// How long a handoff may sit in Freezing or Draining before the
/// coordinator cancels it — by atomic replacement with whatever
@@ -275,6 +274,7 @@ impl Coordinator {
let freeze_acks_stream = self.store.watch_freeze_acks_from(anchor).await?;
let drained_acks_stream = self.store.watch_drained_acks_from(anchor).await?;
let warmed_acks_stream = self.store.watch_warmed_acks_from(anchor).await?;
+ let routers_stream = self.store.watch_routers_from(anchor).await?;
let mut tasks = tokio::task::JoinSet::new();
@@ -353,6 +353,14 @@ impl Coordinator {
});
}
+ {
+ let store = Arc::clone(&self.store);
+ let token = cancel.child_token();
+ tasks.spawn(async move {
+ Self::run_router_departure_watch(routers_stream, &store, token).await
+ });
+ }
+
{
let store = Arc::clone(&self.store);
let interval = self.config.reconcile_interval;
@@ -522,13 +530,47 @@ impl Coordinator {
}
}
+ /// React to router departures. The freeze quorum's required set is
+ /// the handoff's creation snapshot intersected with the live
+ /// registry, so a router leaving — deregistering at shutdown, or its
+ /// lease expiring after a crash — can newly satisfy the quorum of
+ /// every in-flight freeze. Nothing else fires an event for that:
+ /// without this watch, such handoffs wait for the reconcile tick.
+ /// Registrations (Put events) are ignored — a router that joins
+ /// after a handoff's creation is never added to its quorum, so a Put
+ /// can't change any evaluation.
+ async fn run_router_departure_watch(
+ mut stream: WatchStream,
+ store: &PersonhogStore,
+ cancel: CancellationToken,
+ ) -> Result<()> {
+ loop {
+ tokio::select! {
+ _ = cancel.cancelled() => return Ok(()),
+ msg = stream.message() => {
+ let resp = msg?.ok_or_else(|| {
+ Error::invalid_state("router watch stream ended".to_string())
+ })?;
+ let departed = resp
+ .events()
+ .iter()
+ .any(|e| e.event_type() == EventType::Delete);
+ if departed {
+ for handoff in store.list_handoffs().await? {
+ Self::check_phase_advance(store, handoff.partition).await?;
+ }
+ }
+ }
+ }
+ }
+ }
+
/// Periodically re-evaluate every in-flight handoff, mirroring what
- /// the ack watches do on events. This is the liveness backstop for
- /// state changes that fire no watched event — a router departing
- /// (nothing watches router registrations) can newly satisfy a freeze
- /// quorum. All the work it drives is idempotent: phase transitions
- /// use CAS and completed-handoff cleanup tolerates already-deleted
- /// records.
+ /// the ack and router-departure watches do on events. This is the
+ /// liveness backstop for anything the watches miss — a dropped
+ /// stream, an event lost in a coordinator failover window. All the
+ /// work it drives is idempotent: phase transitions use CAS and
+ /// completed-handoff cleanup tolerates already-deleted records.
async fn reconcile_tick_loop(
store: Arc<PersonhogStore>,
interval: Duration,
@@ -626,6 +668,18 @@ impl Coordinator {
"freeze quorum reached, advanced from Freezing"
);
}
+ } else {
+ // Evaluations are event-driven (acks, router
+ // departures, the reconcile tick), so this names the
+ // blocker a handful of times per stalled handoff
+ // rather than spamming.
+ tracing::info!(
+ partition,
+ handoff_id = %handoff.handoff_id,
+ missing_freeze_ackers =
+ ?missing_freeze_ackers(&routers, &freeze_acks, &handoff),
+ "freeze quorum not yet met"
+ );
}
}
HandoffPhase::Draining => {
@@ -950,6 +1004,19 @@ impl Coordinator {
tracing::info!("concurrent plan won handoff creation; standing down");
return Ok(());
}
+ for handoff in creations
+ .iter()
+ .chain(replacements.iter().map(|r| &r.handoff))
+ {
+ tracing::info!(
+ partition = handoff.partition,
+ handoff_id = %handoff.handoff_id,
+ old_owner = ?handoff.old_owner,
+ new_owner = %handoff.new_owner,
+ phase = ?handoff.phase,
+ "handoff created"
+ );
+ }
for disposition in &replaced_dispositions {
counter!(
"personhog_coordination_handoffs_replaced_total",
diff --git a/rust/personhog-coordination/src/routing_table.rs b/rust/personhog-coordination/src/routing_table.rs
index f67cca0ca3d6..2e2b4577219f 100644
--- a/rust/personhog-coordination/src/routing_table.rs
+++ b/rust/personhog-coordination/src/routing_table.rs
@@ -601,8 +601,35 @@ impl RoutingTable {
// Deregister so freeze quorums stop counting this router
// immediately. Left to lease expiry, every handoff frozen in the
// next TTL window stalls waiting for a freeze ack this router
- // will never write.
- drop(self.store.revoke_lease(lease_id).await);
+ // will never write. Still best-effort — an unreachable etcd lets
+ // the lease lapse by TTL — but loudly so: this line is the proof
+ // a graceful shutdown reached its deregistration.
+ match self.store.revoke_lease(lease_id).await {
+ Ok(()) => {
+ metrics::counter!(
+ "personhog_coordination_router_deregistered_total",
+ "outcome" => "revoked"
+ )
+ .increment(1);
+ tracing::info!(
+ router = %self.config.router_name,
+ "router deregistered, freeze quorums no longer count it"
+ );
+ }
+ Err(e) => {
+ metrics::counter!(
+ "personhog_coordination_router_deregistered_total",
+ "outcome" => "revoke_failed"
+ )
+ .increment(1);
+ tracing::warn!(
+ router = %self.config.router_name,
+ error = %e,
+ "router lease revoke failed; registration lapses by TTL and \
+ freezes created meanwhile stall on it"
+ );
+ }
+ }
result
}
diff --git a/rust/personhog-coordination/src/store.rs b/rust/personhog-coordination/src/store.rs
index 3cdb8e535af0..c2c754c38069 100644
--- a/rust/personhog-coordination/src/store.rs
+++ b/rust/personhog-coordination/src/store.rs
@@ -172,6 +172,11 @@ impl PersonhogStore {
Ok(self.inner.watch(&key).await?)
}
+ pub async fn watch_routers_from(&self, start_revision: i64) -> Result<WatchStream> {
+ let key = self.key(StoreKey::RoutersPrefix);
+ Ok(self.inner.watch_from(&key, start_revision).await?)
+ }
+
// ── Assignment operations ───────────────────────────────────
pub async fn get_assignment(&self, partition: u32) -> Result<Option<PartitionAssignment>> {
diff --git a/rust/personhog-coordination/tests/common/mod.rs b/rust/personhog-coordination/tests/common/mod.rs
index b0ca01fbf1ab..7b3e07035120 100644
--- a/rust/personhog-coordination/tests/common/mod.rs
+++ b/rust/personhog-coordination/tests/common/mod.rs
@@ -217,6 +217,29 @@ pub fn start_pod_blocking(
}
}
+/// Coordinator whose reconcile tick and phase deadlines are parked, so a
+/// test can prove an advancement was event-driven rather than rescued by
+/// the periodic backstop.
+pub fn start_coordinator_reconcile_parked(
+ store: Arc<PersonhogStore>,
+ strategy: Arc<dyn AssignmentStrategy>,
+ cancel: CancellationToken,
+) -> JoinHandle<Result<()>> {
+ let coordinator = Coordinator::new(
+ store,
+ CoordinatorConfig {
+ reconcile_interval: Duration::from_secs(86_400),
+ handoff_deadline: Duration::from_secs(86_400),
+ warming_deadline: Duration::from_secs(86_400),
+ ..Default::default()
+ },
+ strategy,
+ None,
+ );
+ let token = cancel.child_token();
+ tokio::spawn(async move { coordinator.run(token).await })
+}
+
pub fn start_coordinator_with_debounce(
store: Arc<PersonhogStore>,
strategy: Arc<dyn AssignmentStrategy>,
diff --git a/rust/personhog-coordination/tests/protocol_hardening.rs b/rust/personhog-coordination/tests/protocol_hardening.rs
index 90287e43c346..231ef2fcc8f6 100644
--- a/rust/personhog-coordination/tests/protocol_hardening.rs
+++ b/rust/personhog-coordination/tests/protocol_hardening.rs
@@ -21,10 +21,11 @@ use tokio_util::sync::CancellationToken;
use assignment_coordination::store::parse_watch_value;
use async_trait::async_trait;
use common::{
- revoke_lease_of_key, start_coordinator, start_coordinator_named, start_pod, start_pod_gated,
- start_pod_with_lease_ttl, start_router_with_lease_ttl, store_at, test_store,
- test_store_with_prefix, wait_for_condition, CutoverEvent, FlakyProxy, HandoffEvent,
- MockCutoverHandler, MockHandoffHandler, ETCD_ENDPOINT, POLL_INTERVAL, WAIT_TIMEOUT,
+ revoke_lease_of_key, start_coordinator, start_coordinator_named,
+ start_coordinator_reconcile_parked, start_pod, start_pod_gated, start_pod_with_lease_ttl,
+ start_router_with_lease_ttl, store_at, test_store, test_store_with_prefix, wait_for_condition,
+ CutoverEvent, FlakyProxy, HandoffEvent, MockCutoverHandler, MockHandoffHandler, ETCD_ENDPOINT,
+ POLL_INTERVAL, WAIT_TIMEOUT,
};
use personhog_coordination::error::Result;
use personhog_coordination::routing_table::{RoutingTable, RoutingTableConfig, StashHandler};
@@ -737,6 +738,103 @@ async fn ack_for_previous_handoff_does_not_satisfy_quorum() {
cancel.cancel();
}
+/// A freeze whose quorum is held open by a registered-but-silent router
+/// must advance the moment that router's registration disappears —
+/// event-driven via the router-departure watch, not rescued later by
+/// the reconcile tick (parked here to prove the distinction). This is
+/// the deploy path: a router deregisters at shutdown, or its lease
+/// expires after a crash, while handoffs sit frozen on its ack.
+#[tokio::test]
+async fn router_departure_advances_a_waiting_freeze() {
+ let store = test_store("router-departure").await;
+ let cancel = CancellationToken::new();
+
+ // Two registered routers: one will ack, one never will — its process
+ // is gone and only its registration remains, on its own lease.
+ let live_lease = store.grant_lease(30).await.expect("lease");
+ store
+ .register_router(
+ &RegisteredRouter {
+ router_name: "r-live".to_string(),
+ registered_at: 0,
+ last_heartbeat: 0,
+ },
+ live_lease,
+ )
+ .await
+ .expect("register live router");
+ let dead_lease = store.grant_lease(30).await.expect("lease");
+ store
+ .register_router(
+ &RegisteredRouter {
+ router_name: "r-dead".to_string(),
+ registered_at: 0,
+ last_heartbeat: 0,
+ },
+ dead_lease,
+ )
+ .await
+ .expect("register dead router");
+
+ let _coord = start_coordinator_reconcile_parked(
+ Arc::clone(&store),
+ Arc::new(StickyBalancedStrategy),
+ cancel.clone(),
+ );
+
+ put_handoff(
+ &store,
+ 0,
+ Some("pod-old"),
+ "pod-new",
+ HandoffPhase::Freezing,
+ )
+ .await;
+ store
+ .put_freeze_ack(&RouterFreezeAck {
+ router_name: "r-live".to_string(),
+ partition: 0,
+ acked_at: 0,
+ handoff_id: "test-handoff-0".to_string(),
+ })
+ .await
+ .expect("write ack");
+
+ // The live ack alone must not satisfy the quorum while the silent
+ // router is still registered.
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ let handoff = store
+ .get_handoff(0)
+ .await
+ .expect("get handoff")
+ .expect("handoff exists");
+ assert_eq!(
+ handoff.phase,
+ HandoffPhase::Freezing,
+ "a registered router that has not acked must hold the freeze"
+ );
+
+ // The silent router departs. Revoke stands in for both shutdown
+ // deregistration and crash-side lease expiry — the same Delete event.
+ store.revoke_lease(dead_lease).await.expect("revoke");
+
+ let check_store = Arc::clone(&store);
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let store = Arc::clone(&check_store);
+ async move {
+ store
+ .get_handoff(0)
+ .await
+ .ok()
+ .flatten()
+ .is_some_and(|h| h.phase != HandoffPhase::Freezing)
+ }
+ })
+ .await;
+
+ cancel.cancel();
+}
+
/// An ack written by a pre-`handoff_id` binary (the JSON has no
/// `handoff_id` field, so it deserializes to "") must not satisfy the
/// quorum of a handoff carrying a real id. This is the rolling-upgrade
diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rs
index 99d6d5e0ea38..5edc54a98ba5 100644
--- a/rust/personhog-router/src/main.rs
+++ b/rust/personhog-router/src/main.rs
@@ -67,7 +67,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
);
let mut manager = Manager::builder("personhog-router")
- .with_global_shutdown_timeout(Duration::from_secs(30))
+ // Below the pod's 30s termination grace so shutdown always
+ // concludes process-side — reaching the routing table's lease
+ // revoke — rather than racing the kubelet's SIGKILL.
+ .with_global_shutdown_timeout(Duration::from_secs(25))
.build();
// Shutdown order is the inverse of the leader's: the gRPC server
diff --git a/rust/personhog-router/src/stash_handler.rs b/rust/personhog-router/src/stash_handler.rs
index 32d0758fa26f..bdf8478224c4 100644
--- a/rust/personhog-router/src/stash_handler.rs
+++ b/rust/personhog-router/src/stash_handler.rs
@@ -222,7 +222,25 @@ async fn forward_key_run(
put_back_rest(session, run.key, entry, entries, "cancelled").await;
return outcome;
}
- match forward_one(leader_backend, max_stash_wait, partition, &entry.item).await {
+ // Race the forward against cancellation: an in-flight call can
+ // otherwise hold this lane for the full backend timeout, and at
+ // router shutdown the drain-lane join sits between cancellation
+ // and the lease revoke — a slow forward there delays
+ // deregistration, stalling every freeze that counts this router.
+ let forwarded = tokio::select! {
+ biased;
+ _ = cancel.cancelled() => None,
+ d = forward_one(leader_backend, max_stash_wait, partition, &entry.item) => Some(d),
+ };
+ let Some(disposition) = forwarded else {
+ // The abandoned call may already be on the wire, so the
+ // outcome is unknown — same ambiguity as a transport bounce,
+ // same conservative marking.
+ entry.item.possibly_applied = true;
+ put_back_rest(session, run.key, entry, entries, "cancelled").await;
+ return outcome;
+ };
+ match disposition {
Disposition::Reply {
response,
outcome: label,
diff --git a/rust/personhog-router/tests/stash_integration.rs b/rust/personhog-router/tests/stash_integration.rs
index 23ecb2ee7499..3ed81c9890e1 100644
--- a/rust/personhog-router/tests/stash_integration.rs
+++ b/rust/personhog-router/tests/stash_integration.rs
@@ -908,3 +908,63 @@ async fn drain_converges_with_concurrent_arrivals() {
drop(h.await.unwrap());
}
}
+
+/// Cancelling a drain mid-forward must return promptly and put the entry
+/// back — not ride out the backend timeout. At router shutdown the
+/// drain-lane join sits between cancellation and the lease revoke, so a
+/// forward that keeps a lane busy delays deregistration, and every
+/// freeze quorum still counting this router stalls with it.
+#[tokio::test]
+async fn drain_cancellation_returns_promptly_and_puts_the_entry_back() {
+ // A leader that accepts TCP connections but never speaks: the
+ // forward hangs in the HTTP/2 handshake until the backend timeout.
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind hanging leader");
+ let leader_addr = listener.local_addr().expect("addr");
+ tokio::spawn(async move {
+ let mut held = Vec::new();
+ while let Ok((sock, _)) = listener.accept().await {
+ held.push(sock);
+ }
+ });
+
+ let stash = StashTable::with_bounds(usize::MAX, usize::MAX);
+ let backend = make_backend(leader_addr, stash).await;
+ let handler = new_test_handler(Arc::clone(&backend));
+
+ let (team_id, person_id) = (1, 42);
+ let partition = backend.partition_for_person(team_id, person_id);
+ handler
+ .begin_stash(partition, "leader-new")
+ .await
+ .expect("begin_stash should succeed");
+
+ let req = mk_request(team_id, person_id, "[email protected]");
+ let backend_for_call = Arc::clone(&backend);
+ let _in_flight = tokio::spawn(async move { forward(&backend_for_call, req).await });
+ tokio::time::sleep(Duration::from_millis(50)).await;
+
+ let cancel = CancellationToken::new();
+ let drain_cancel = cancel.clone();
+ let drain = tokio::spawn(async move {
+ handler
+ .drain_stash(partition, "leader-new", drain_cancel)
+ .await
+ });
+ // Let the drain reach the hanging forward before cancelling.
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ cancel.cancel();
+
+ tokio::time::timeout(Duration::from_secs(1), drain)
+ .await
+ .expect("cancelled drain must return well before the backend timeout")
+ .expect("drain task must not panic")
+ .expect("a cancelled drain is a pause, not an error");
+
+ let handler = new_test_handler(Arc::clone(&backend));
+ assert!(
+ handler.stash_pending(partition),
+ "the abandoned entry must be put back for the next drain"
+ );
+}