: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): snapshot freeze quorum and bound handoff age (#74025)
Zach Browne2e77839975b
diff --git a/rust/personhog-coordination/src/coordinator.rs b/rust/personhog-coordination/src/coordinator.rsindex 2f890d8c4204..e7455f441e62 100644--- a/rust/personhog-coordination/src/coordinator.rs+++ b/rust/personhog-coordination/src/coordinator.rs@@ -4,6 +4,7 @@ use std::time::Duration;use etcd_client::{EventType, WatchStream};use metrics::{counter, gauge, histogram};+use tokio::sync::Notify;use tokio_util::sync::CancellationToken;use assignment_coordination::store::parse_watch_value;@@ -35,6 +36,39 @@ pub struct CoordinatorConfig {/// indefinitely, and doubles as defense-in-depth for anything else/// that slips through the event-driven paths.pub reconcile_interval: Duration,+ /// How long a handoff may sit in a pre-terminal phase before the+ /// coordinator cancels it and lets the next plan try again.+ ///+ /// This is the backstop for causes we have not found: a participant+ /// that never acks leaves a handoff that no other path removes —+ /// cleanup only deletes handoffs whose new owner is gone, and an+ /// in-flight handoff pins its partition so no re-plan can touch it.+ /// Cancelling is the only safe response; force-advancing past a+ /// missing freeze ack is exactly the split-brain the quorum exists+ /// to prevent.+ ///+ /// Measured against the handoff's total age rather than time in its+ /// current phase: `started_at` is the only timestamp the record+ /// carries, and a per-phase budget derived from it would silently+ /// shrink for whichever phase happened to run last. One end-to-end+ /// budget is also the honest statement of intent — a handoff should+ /// finish, and how it divides its time between freezing, draining,+ /// and warming is not something to police.+ ///+ /// Generous by design: healthy handoffs complete in a few seconds,+ /// so this sits orders of magnitude above them. Too tight a bound+ /// would cancel the handoffs that are merely slow.+ ///+ /// Ages are wall-clock differences that may span machines: a+ /// handoff created by one coordinator can be evaluated by its+ /// successor after a failover, so clock skew between nodes shifts+ /// the effective deadline by its magnitude. That is tolerated+ /// rather than engineered away — skew is NTP-bounded at+ /// milliseconds against a deadline of minutes, and a mistimed+ /// cancellation is safe in either direction: early, the re-plan+ /// recreates the handoff stamped and judged by one clock; late, a+ /// wedge lives that much longer before cancellation.+ pub handoff_deadline: Duration,}impl Default for CoordinatorConfig {@@ -53,6 +87,7 @@ impl Default for CoordinatorConfig {election_retry_interval: Duration::from_secs(1),rebalance_debounce_interval: Duration::from_secs(1),reconcile_interval: Duration::from_secs(5),+ handoff_deadline: Duration::from_secs(120),}}}@@ -195,11 +230,21 @@ impl Coordinator {let mut tasks = tokio::task::JoinSet::new();+ // Wakes the planning loop for state changes only the coordinator+ // itself produces — a deadline cancellation deletes a handoff,+ // which fires no pod event, so without an explicit wake no+ // re-plan would run until the next unrelated pod change. Waking+ // the one planning loop rather than planning inline keeps a+ // single planner task; `Notify` stores a permit, so a wake fired+ // mid-plan is picked up on the next iteration rather than lost.+ let replan = Arc::new(Notify::new());+{let store = Arc::clone(&self.store);let strategy = Arc::clone(&self.strategy);let k8s_awareness = self.k8s_awareness.clone();let debounce_interval = self.config.rebalance_debounce_interval;+ let replan = Arc::clone(&replan);let token = cancel.child_token();tasks.spawn(async move {Self::watch_pods_loop(@@ -207,6 +252,7 @@ impl Coordinator {strategy,k8s_awareness,debounce_interval,+ replan,token,pods_stream,)@@ -252,8 +298,12 @@ impl Coordinator {{let store = Arc::clone(&self.store);let interval = self.config.reconcile_interval;+ let handoff_deadline = self.config.handoff_deadline;+ let replan = Arc::clone(&replan);let token = cancel.child_token();- tasks.spawn(async move { Self::reconcile_tick_loop(store, interval, token).await });+ tasks.spawn(async move {+ Self::reconcile_tick_loop(store, interval, handoff_deadline, replan, token).await+ });}// Reconcile any handoffs that already have full ack quorum.@@ -281,13 +331,17 @@ impl Coordinator {strategy: Arc<dyn AssignmentStrategy>,k8s_awareness: Option<Arc<K8sAwareness>>,debounce_interval: Duration,+ replan: Arc<Notify>,cancel: CancellationToken,mut stream: WatchStream,) -> Result<()> {loop {- // Wait for the first pod event+ // Wait for the first pod event, or an explicit re-plan wake+ // (a deadline cancellation deletes a handoff, which fires no+ // pod event but leaves the placement short of desired).tokio::select! {_ = cancel.cancelled() => return Ok(()),+ _ = replan.notified() => {}msg = stream.message() => {let resp = msg?.ok_or_else(|| Error::invalid_state("pod watch stream ended".to_string()))?;Self::log_pod_events(&resp);@@ -412,6 +466,8 @@ impl Coordinator {async fn reconcile_tick_loop(store: Arc<PersonhogStore>,interval: Duration,+ handoff_deadline: Duration,+ replan: Arc<Notify>,cancel: CancellationToken,) -> Result<()> {let mut tick = tokio::time::interval(interval);@@ -424,6 +480,15 @@ impl Coordinator {Self::handle_handoff_update_static(&store, handoff).await?;Self::check_phase_advance(&store, handoff.partition).await?;}+ // Advancement first, cancellation second: a handoff+ // that can still progress gets every chance to before+ // its deadline is considered. A cancellation wakes+ // the planning loop, since deleting a handoff fires+ // no pod event and the placement is now short of+ // desired.+ if Self::cancel_expired_handoffs(&store, &handoffs, handoff_deadline).await? {+ replan.notify_one();+ }// The gauge refresh is best-effort and runs after the// reconcile pass: its reads exist only for metrics and// must never delay or interrupt handoff advancement —@@ -654,6 +719,17 @@ impl Coordinator {return Ok(());}+ // Snapshot the routers that must ack these freezes. Read here,+ // once, rather than per-check: the whole point is that the+ // requirement is fixed at creation and cannot grow as routers+ // come and go (see `HandoffState::freeze_quorum`).+ let freeze_quorum: Vec<String> = store+ .list_routers()+ .await?+ .into_iter()+ .map(|r| r.router_name)+ .collect();+let now = util::now_seconds();let handoff_objects: Vec<HandoffState> = plan.handoffs@@ -669,6 +745,7 @@ impl Coordinator {phase: HandoffPhase::Freezing,started_at: now,handoff_id: util::new_handoff_id(),+ freeze_quorum: Some(freeze_quorum.clone()),}).collect();@@ -732,6 +809,91 @@ impl Coordinator {Ok(())}+ /// Cancel handoffs that have sat in one phase past its deadline.+ ///+ /// Nothing else removes a handoff that simply never gets its ack:+ /// `cleanup_stale_handoffs` only fires when the new owner is gone,+ /// and an in-flight handoff pins its partition so no re-plan can+ /// touch it. Deleting is the only safe response — advancing without+ /// the ack is the split-brain the phase exists to prevent — and the+ /// next plan is free to try again, with a fresh handoff id and a+ /// fresh quorum snapshot.+ ///+ /// Deliberately not backed off: the snapshot rule keeps freeze+ /// quorums satisfiable, so repeated cancellation of one partition+ /// means a new cause, and+ /// `handoffs_cancelled_total{reason="phase_deadline"}` exists to+ /// make that visible rather than absorbed.+ ///+ /// Returns whether anything was cancelled, so the caller can wake+ /// the planning loop — a deletion fires no pod event, and without+ /// the wake no re-plan would run until the next unrelated pod+ /// change. `handoffs` is the caller's already-listed snapshot; each+ /// candidate is re-read under mod_revision before deletion, so the+ /// snapshot's staleness only ever skips a cancel, never misdirects+ /// one.+ async fn cancel_expired_handoffs(+ store: &PersonhogStore,+ handoffs: &[HandoffState],+ handoff_deadline: Duration,+ ) -> Result<bool> {+ let now = util::now_seconds();+ let deadline = handoff_deadline.as_secs() as i64;+ let mut cancelled = false;+ for handoff in handoffs {+ // Complete is terminal and cleaned up by its own path.+ if handoff.phase == HandoffPhase::Complete {+ continue;+ }+ // A record carrying no creation time cannot be judged on age;+ // deleting it would be acting on an age of "since the epoch"+ // rather than on evidence that it is stuck.+ if handoff.started_at <= 0 {+ continue;+ }+ let age = now.saturating_sub(handoff.started_at);+ if age < deadline {+ continue;+ }+ // Re-read under mod_revision and re-verify the phase before+ // deleting: this runs alongside the watch-driven paths, and+ // the record at this key may already be a successor handoff+ // that has not had its own chance yet.+ let Some((current, mod_revision)) = store+ .get_handoff_with_mod_revision(handoff.partition)+ .await?+ else {+ continue;+ };+ if current.handoff_id != handoff.handoff_id+ || current.phase == HandoffPhase::Complete+ || now.saturating_sub(current.started_at) < deadline+ {+ continue;+ }+ tracing::error!(+ partition = current.partition,+ phase = ?current.phase,+ age_secs = age,+ new_owner = %current.new_owner,+ old_owner = ?current.old_owner,+ "handoff exceeded its deadline; cancelling so a later plan can retry"+ );+ if store+ .delete_handoff_and_acks_if_unchanged(current.partition, mod_revision)+ .await?+ {+ cancelled = true;+ counter!(+ "personhog_coordination_handoffs_cancelled_total",+ "reason" => "phase_deadline",+ )+ .increment(1);+ }+ }+ Ok(cancelled)+ }+/// Delete handoffs that cannot progress because the new_owner is gone —/// no `WarmedAck` will ever arrive, so the handoff can never complete,/// and deleting it lets the next rebalance pick a healthy owner.diff --git a/rust/personhog-coordination/src/pod.rs b/rust/personhog-coordination/src/pod.rsindex 6725739421fe..69b5d37d2716 100644--- a/rust/personhog-coordination/src/pod.rs+++ b/rust/personhog-coordination/src/pod.rs@@ -651,6 +651,7 @@ mod tests {phase,started_at: 0,handoff_id: "h-test".to_string(),+ freeze_quorum: None,new_owner_address: None,}}diff --git a/rust/personhog-coordination/src/protocol.rs b/rust/personhog-coordination/src/protocol.rsindex 9c3067273a0f..1ab669c1f8c5 100644--- a/rust/personhog-coordination/src/protocol.rs+++ b/rust/personhog-coordination/src/protocol.rs@@ -114,7 +114,7 @@ pub fn plan_partial_rebalance<S: AssignmentStrategy + ?Sized>(/// Whether the freeze quorum for `handoff` is met.///-/// Identity-based: every currently registered router must have acked+/// Identity-based: every router this handoff requires must have acked/// this partition's freeze. A count comparison would let a stale ack/// from a departed router (acks are not lease-bound) stand in for a live/// router that hasn't stashed yet — advancing to Draining while that@@ -122,7 +122,11 @@ pub fn plan_partial_rebalance<S: AssignmentStrategy + ?Sized>(/// handoff's id count: an ack left over from a previous handoff of the/// same partition proves nothing about this one.///-/// With zero routers there is no traffic to stash, so the freeze quorum+/// The required set is the handoff's creation-time snapshot intersected+/// with the live registry, so it only ever shrinks; see+/// [`required_freeze_ackers`].+///+/// With no required routers there is no traffic to stash, so the quorum/// is vacuously met. This keeps bootstrap and router-less configurations/// (e.g. tests exercising only the coordinator+pod) unblocked.pub fn freeze_quorum_met(@@ -135,9 +139,32 @@ pub fn freeze_quorum_met(.filter(|a| a.handoff_id == handoff.handoff_id).map(|a| a.router_name.as_str()).collect();+ required_freeze_ackers(routers, handoff).all(|name| acked.contains(name))+}++/// The routers whose freeze ack this handoff needs: those it was created+/// with that are still registered.+///+/// Intersecting the snapshot with the live set makes the requirement+/// monotonic — it can only shrink. A router that dies drops out (it is no+/// longer routing, so it cannot reach the old owner), and one that joins+/// later is never added (safe to exclude — see+/// [`HandoffState::freeze_quorum`] for why).+pub fn required_freeze_ackers<'a>(+ routers: &'a [RegisteredRouter],+ handoff: &'a HandoffState,+) -> impl Iterator<Item = &'a str> + 'a {routers.iter()- .all(|r| acked.contains(r.router_name.as_str()))+ .map(|r| r.router_name.as_str())+ // `None` is a pre-upgrade record: fall back to requiring every+ // live router, which is what it was written under. A `Some`+ // snapshot is authoritative even when empty — zero routers at+ // creation means nobody must ack, not "apply the legacy rule".+ .filter(move |name| match &handoff.freeze_quorum {+ None => true,+ Some(quorum) => quorum.iter().any(|member| member == name),+ })}/// Whether the drain requirement for `handoff` is satisfied.@@ -191,10 +218,97 @@ mod tests {phase: crate::types::HandoffPhase::Warming,started_at: 0,handoff_id: String::new(),+ freeze_quorum: None,new_owner_address: None,}}+ fn router(name: &str) -> RegisteredRouter {+ RegisteredRouter {+ router_name: name.to_string(),+ registered_at: 0,+ last_heartbeat: 0,+ }+ }++ fn freeze_ack(router: &str, handoff: &HandoffState) -> RouterFreezeAck {+ RouterFreezeAck {+ router_name: router.to_string(),+ partition: handoff.partition,+ acked_at: 0,+ handoff_id: handoff.handoff_id.clone(),+ }+ }++ /// The wedge this snapshot exists to prevent: a router that+ /// registers after the handoff was created never receives its+ /// `Freezing` event, so requiring its ack leaves a quorum that+ /// nothing can satisfy and no cleanup path removes.+ #[test]+ fn a_router_that_joined_after_creation_is_not_required() {+ let mut h = handoff(0, Some("pod-a"), "pod-b");+ h.freeze_quorum = Some(vec!["router-0".to_string()]);+ let acks = [freeze_ack("router-0", &h)];++ assert!(+ freeze_quorum_met(&[router("router-0"), router("late-joiner")], &acks, &h),+ "a router registered after creation must not block the quorum"+ );+ }++ /// The other direction is what keeps it safe: a router that was+ /// present at creation may hold a routing table pointing at the old+ /// owner, so its ack stays mandatory.+ #[test]+ fn a_router_present_at_creation_is_still_required() {+ let mut h = handoff(0, Some("pod-a"), "pod-b");+ h.freeze_quorum = Some(vec!["router-0".to_string(), "router-1".to_string()]);+ let acks = [freeze_ack("router-0", &h)];++ assert!(+ !freeze_quorum_met(&[router("router-0"), router("router-1")], &acks, &h),+ "a snapshot member that has not acked must block the quorum"+ );+ // ...until it departs: a router that is gone cannot route.+ assert!(+ freeze_quorum_met(&[router("router-0")], &acks, &h),+ "a departed snapshot member must drop out of the requirement"+ );+ }++ /// Records written before the snapshot existed must keep their old+ /// meaning: with no captured requirement, every live router is+ /// required, since any of them might hold a table pointing at the+ /// old owner.+ #[test]+ fn an_absent_snapshot_requires_every_live_router() {+ let h = handoff(0, Some("pod-a"), "pod-b");+ assert!(h.freeze_quorum.is_none());+ let acks = [freeze_ack("router-0", &h)];++ assert!(+ !freeze_quorum_met(&[router("router-0"), router("router-1")], &acks, &h),+ "without a snapshot every live router must still be required"+ );+ assert!(freeze_quorum_met(&[router("router-0")], &acks, &h));+ }++ /// A captured-but-empty snapshot is not the legacy fallback: zero+ /// routers were registered at creation, so nobody must ack — even+ /// routers that register afterward. Falling back to the live-set+ /// rule here would let the requirement grow from zero and reopen+ /// the wedge for exactly this corner.+ #[test]+ fn an_empty_snapshot_requires_nobody() {+ let mut h = handoff(0, Some("pod-a"), "pod-b");+ h.freeze_quorum = Some(Vec::new());++ assert!(+ freeze_quorum_met(&[router("late-joiner")], &[], &h),+ "a router that registered after a zero-router creation must not be required"+ );+ }+#[test]fn pinned_partitions_are_never_planned() {let current: HashMap<u32, String> = (0..4).map(|p| (p, "pod-a".to_string())).collect();diff --git a/rust/personhog-coordination/src/types.rs b/rust/personhog-coordination/src/types.rsindex 3e1bcc26d4a5..be10e591cbcb 100644--- a/rust/personhog-coordination/src/types.rs+++ b/rust/personhog-coordination/src/types.rs@@ -122,6 +122,27 @@ pub struct HandoffState {/// past a drain or warm that never happened.#[serde(default)]pub handoff_id: String,+ /// The routers whose freeze acks this handoff requires: those+ /// registered when the coordinator created it, intersected with the+ /// live registry at evaluation (`required_freeze_ackers`), so the+ /// requirement only ever shrinks. Fixing membership at creation+ /// keeps the quorum satisfiable — every member's watch coverage+ /// spans this handoff's Freezing event, and a router that registers+ /// later is never required to ack an event it may not observe.+ ///+ /// Exempting late joiners is safe because the freeze quorum is an+ /// availability gate, not the safety boundary: a joining router+ /// opens stashes for in-flight handoffs before its routing table+ /// can forward anywhere, and the drain fence plus the broker's+ /// producer epoch reject anything that slips through before it is+ /// ever acked.+ ///+ /// `None` means the record predates this field; the quorum then+ /// falls back to requiring every live router. `Some([])` is a real+ /// snapshot — zero routers were registered at creation — and+ /// requires nobody.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub freeze_quorum: Option<Vec<String>>,}/// State machine for partition handoffs:@@ -290,6 +311,7 @@ mod tests {phase: HandoffPhase::Freezing,started_at: 1700000000,handoff_id: "1700000000000-0".to_string(),+ freeze_quorum: None,new_owner_address: None,};let json = serde_json::to_string(&handoff).unwrap();@@ -306,6 +328,7 @@ mod tests {phase: HandoffPhase::Freezing,started_at: 1700000000,handoff_id: "1700000000000-0".to_string(),+ freeze_quorum: None,new_owner_address: None,};let json = serde_json::to_string(&handoff).unwrap();diff --git a/rust/personhog-coordination/tests/common/mod.rs b/rust/personhog-coordination/tests/common/mod.rsindex ad62a8bacef6..5fd7a541c1a5 100644--- a/rust/personhog-coordination/tests/common/mod.rs+++ b/rust/personhog-coordination/tests/common/mod.rs@@ -87,6 +87,24 @@ pub fn start_coordinator_named(leader_lease_ttl: i64,strategy: Arc<dyn AssignmentStrategy>,cancel: CancellationToken,+) -> JoinHandle<Result<()>> {+ start_coordinator_with_deadline(+ store,+ name,+ leader_lease_ttl,+ Duration::from_secs(86_400),+ strategy,+ cancel,+ )+}++pub fn start_coordinator_with_deadline(+ store: Arc<PersonhogStore>,+ name: &str,+ leader_lease_ttl: i64,+ handoff_deadline: Duration,+ strategy: Arc<dyn AssignmentStrategy>,+ cancel: CancellationToken,) -> JoinHandle<Result<()>> {let keepalive_secs = (leader_lease_ttl as u64 / 3).max(1);let coordinator = Coordinator::new(@@ -98,6 +116,11 @@ pub fn start_coordinator_named(election_retry_interval: Duration::from_secs(1),rebalance_debounce_interval: Duration::from_millis(100),reconcile_interval: Duration::from_millis(500),+ // Callers default this to a day: these tests deliberately+ // park handoffs mid-phase to assert what the protocol does+ // with them, and a live deadline would delete the state under+ // test. The cancellation test passes a short one explicitly.+ handoff_deadline,},strategy,None,diff --git a/rust/personhog-coordination/tests/integration.rs b/rust/personhog-coordination/tests/integration.rsindex f1320b48d24b..cf8dccb64978 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(),+ freeze_quorum: None,new_owner_address: None,};store.put_handoff(&stuck_handoff).await.unwrap();@@ -1542,6 +1543,7 @@ async fn stale_handoff_address_never_overwrites_a_fresher_registration() {phase: personhog_coordination::types::HandoffPhase::Complete,started_at: 0,handoff_id: "h-stale-addr".to_string(),+ freeze_quorum: None,}).await.unwrap();@@ -1763,6 +1765,7 @@ async fn late_joining_router_during_warming_begins_stash() {phase: HandoffPhase::Warming,started_at: 0,handoff_id: String::new(),+ freeze_quorum: None,new_owner_address: None,};store.put_handoff(&warming_handoff).await.unwrap();@@ -1827,6 +1830,7 @@ async fn dead_old_owner_in_freezing_advances_to_completion() {phase: HandoffPhase::Freezing,started_at: 0,handoff_id: String::new(),+ freeze_quorum: None,new_owner_address: None,};store.put_handoff(&stale).await.unwrap();@@ -1879,6 +1883,7 @@ async fn late_joining_router_during_freezing_acks_and_stashes() {phase: HandoffPhase::Freezing,started_at: 0,handoff_id: String::new(),+ freeze_quorum: None,new_owner_address: None,};store.put_handoff(&freezing_handoff).await.unwrap();@@ -1958,6 +1963,7 @@ async fn handoff_delete_during_warming_drains_to_current_owner() {phase: HandoffPhase::Warming,started_at: 0,handoff_id: String::new(),+ freeze_quorum: None,new_owner_address: None,};store.put_handoff(&stuck).await.unwrap();@@ -2056,6 +2062,7 @@ async fn reconcile_advances_warming_with_pre_staged_warmed_ack() {phase: HandoffPhase::Warming,started_at: 0,handoff_id: String::new(),+ freeze_quorum: None,new_owner_address: None,};store.put_handoff(&warming).await.unwrap();@@ -2135,6 +2142,7 @@ async fn draining_old_owner_blocks_phase_advance() {phase: HandoffPhase::Freezing,started_at: 0,handoff_id: String::new(),+ freeze_quorum: None,new_owner_address: None,};store.put_handoff(&handoff).await.unwrap();@@ -2236,6 +2244,7 @@ async fn draining_old_owner_does_not_trigger_cleanup() {phase: HandoffPhase::Freezing,started_at: 0,handoff_id: String::new(),+ freeze_quorum: None,new_owner_address: None,};store.put_handoff(&handoff).await.unwrap();@@ -2268,6 +2277,106 @@ async fn draining_old_owner_does_not_trigger_cleanup() {/// wrote DrainedAck, advancing Kafka HWM past the point warming/// snapshots and leaving the new owner with a stale cache.///+/// A handoff whose quorum can never be met must not sit in etcd+/// forever. Nothing else removes it: cleanup only fires when the *new+/// owner* is gone, and an in-flight handoff pins its partition so no+/// re-plan can replace it — which is exactly how a wedge survives until+/// someone restarts a pod by hand. Past its deadline the coordinator+/// deletes it so a later plan can try again.+#[tokio::test]+async fn a_handoff_that_can_never_reach_quorum_is_cancelled() {+ use personhog_coordination::types::{+ HandoffPhase, HandoffState, PodStatus, RegisteredPod, RegisteredRouter,+ };++ let store = test_store("handoff-deadline-cancels").await;+ let cancel = CancellationToken::new();+ store.set_total_partitions(NUM_PARTITIONS).await.unwrap();++ // A live new owner, so the dead-new-owner cleanup path stays out of+ // this: the handoff must be removed by the deadline alone.+ let pod_lease = store.grant_lease(60).await.unwrap();+ store+ .register_pod(+ &RegisteredPod {+ pod_name: "writer-new".to_string(),+ generation: String::new(),+ status: PodStatus::Ready,+ registered_at: 0,+ last_heartbeat: 0,+ controller: None,+ advertise_address: None,+ },+ pod_lease,+ )+ .await+ .unwrap();++ // A router that is required but never acks — the shape of every+ // wedge seen in production.+ let router_lease = store.grant_lease(60).await.unwrap();+ store+ .register_router(+ &RegisteredRouter {+ router_name: "silent-router".to_string(),+ registered_at: 0,+ last_heartbeat: 0,+ },+ router_lease,+ )+ .await+ .unwrap();++ let strategy: Arc<dyn AssignmentStrategy> = Arc::new(StickyBalancedStrategy);+ let _coord = common::start_coordinator_with_deadline(+ Arc::clone(&store),+ "coordinator-0",+ 10,+ Duration::from_secs(1),+ strategy,+ cancel.clone(),+ );++ store+ .put_handoff(&HandoffState {+ partition: 1,+ old_owner: None,+ new_owner: "writer-new".to_string(),+ new_owner_address: None,+ phase: HandoffPhase::Freezing,+ // A real creation time: the deadline is evaluated against it,+ // and a zero here would mean "unknown age", which is never+ // cancelled.+ started_at: std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_secs() as i64,+ handoff_id: "wedged-handoff".to_string(),+ freeze_quorum: Some(vec!["silent-router".to_string()]),+ })+ .await+ .unwrap();++ // Cancellation wakes the planner, which is free to create a fresh+ // handoff for the same partition — that successor (different id) is+ // the retry working as designed, not the wedge persisting. The+ // property under test is only that the unsatisfiable handoff itself+ // does not outlive its deadline.+ let check_store = Arc::clone(&store);+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {+ let store = Arc::clone(&check_store);+ async move {+ !matches!(+ store.get_handoff(1).await.unwrap(),+ Some(ref s) if s.handoff_id == "wedged-handoff"+ )+ }+ })+ .await;++ cancel.cancel();+}+/// This test verifies the gate by injecting a Freezing handoff with a/// registered router that never acks. The handoff must remain in/// Freezing — it cannot advance to Draining without the freeze quorum,@@ -2326,6 +2435,7 @@ async fn freezing_blocks_until_routers_ack_before_draining() {phase: HandoffPhase::Freezing,started_at: 0,handoff_id: String::new(),+ freeze_quorum: None,new_owner_address: None,};store.put_handoff(&handoff).await.unwrap();@@ -2413,6 +2523,7 @@ async fn initial_assignment_skips_draining_phase() {phase: HandoffPhase::Freezing,started_at: 0,handoff_id: String::new(),+ freeze_quorum: None,new_owner_address: None,};store.put_handoff(&handoff).await.unwrap();@@ -2472,6 +2583,7 @@ async fn dead_old_owner_in_draining_recovers() {phase: HandoffPhase::Draining,started_at: 0,handoff_id: String::new(),+ freeze_quorum: None,new_owner_address: None,};store.put_handoff(&handoff).await.unwrap();@@ -2571,6 +2683,7 @@ async fn reconcile_advances_draining_with_pre_staged_drained_ack() {phase: HandoffPhase::Draining,started_at: 0,handoff_id: String::new(),+ freeze_quorum: None,new_owner_address: None,};store.put_handoff(&handoff).await.unwrap();@@ -2630,6 +2743,7 @@ async fn late_joining_router_during_draining_begins_stash_no_ack() {phase: HandoffPhase::Draining,started_at: 0,handoff_id: String::new(),+ freeze_quorum: None,new_owner_address: None,};store.put_handoff(&draining_handoff).await.unwrap();@@ -2714,6 +2828,7 @@ async fn handoff_delete_during_draining_drains_to_current_owner() {phase: HandoffPhase::Draining,started_at: 0,handoff_id: String::new(),+ freeze_quorum: None,new_owner_address: None,};store.put_handoff(&stuck).await.unwrap();@@ -2960,6 +3075,7 @@ async fn conflicting_plan_cannot_replace_an_in_flight_handoff() {phase: HandoffPhase::Warming,started_at: 0,handoff_id: "first".to_string(),+ freeze_quorum: None,new_owner_address: None,};assert!(store@@ -2976,6 +3092,7 @@ async fn conflicting_plan_cannot_replace_an_in_flight_handoff() {phase: HandoffPhase::Freezing,started_at: 0,handoff_id: "second".to_string(),+ freeze_quorum: None,new_owner_address: None,};let stable = PartitionAssignment {@@ -3024,6 +3141,7 @@ async fn stale_plan_is_rejected_when_the_assignment_moved() {phase: HandoffPhase::Freezing,started_at: 0,handoff_id: id.to_string(),+ freeze_quorum: None,new_owner_address: None,};@@ -3101,6 +3219,7 @@ async fn fresh_plan_is_rejected_when_an_assignment_appeared() {phase: HandoffPhase::Freezing,started_at: 0,handoff_id: id.to_string(),+ freeze_quorum: None,new_owner_address: None,};diff --git a/rust/personhog-coordination/tests/k3s_integration.rs b/rust/personhog-coordination/tests/k3s_integration.rsindex f763ebf1dc29..dd40c0fcb689 100644--- a/rust/personhog-coordination/tests/k3s_integration.rs+++ b/rust/personhog-coordination/tests/k3s_integration.rs@@ -410,6 +410,12 @@ fn start_coordinator_k8s(store,CoordinatorConfig {rebalance_debounce_interval: Duration::from_millis(100),+ // These tests bring up a k3s container and deliberately park+ // handoffs to assert what the rollout paths do with them, so+ // they run far longer than the production deadline is sized+ // for. Leaving it at the default would delete the state under+ // test partway through.+ handoff_deadline: Duration::from_secs(86_400),..Default::default()},Arc::new(StickyBalancedStrategy),diff --git a/rust/personhog-coordination/tests/protocol_hardening.rs b/rust/personhog-coordination/tests/protocol_hardening.rsindex 08c371e3c0a9..679a6bf108ab 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}"),+ freeze_quorum: None,new_owner_address: None,};// Raw put on purpose: fixtures force arbitrary handoff states,diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rsindex f2ccb3e6fd66..e233c3ee9dec 100644--- a/rust/personhog-leader/tests/common/mod.rs+++ b/rust/personhog-leader/tests/common/mod.rs@@ -99,6 +99,10 @@ pub fn start_coordinator(election_retry_interval: Duration::from_secs(1),rebalance_debounce_interval: Duration::from_millis(100),reconcile_interval: Duration::from_millis(500),+ // Effectively disabled: these tests park handoffs to assert+ // warming behavior, and a live deadline would delete the+ // state under test.+ handoff_deadline: Duration::from_secs(86_400),},strategy,None,diff --git a/rust/personhog-router/src/config.rs b/rust/personhog-router/src/config.rsindex be7c56db18f4..1f327a357e73 100644--- a/rust/personhog-router/src/config.rs+++ b/rust/personhog-router/src/config.rs@@ -246,6 +246,15 @@ pub struct Config {#[envconfig(default = "5")]pub coordinator_reconcile_secs: u64,+ /// How long a handoff may run before the coordinator cancels it so a+ /// later plan can retry. The backstop for a handoff that can never+ /// satisfy its quorum: nothing else removes one whose new owner is+ /// alive, and an in-flight handoff pins its partition, so without+ /// this it waits for a human. Sized well above healthy handoffs,+ /// which complete in seconds.+ #[envconfig(default = "120")]+ pub coordinator_handoff_deadline_secs: u64,+// ── K8s awareness (leader mode only) ────────────────────────/// Enable K8s-aware departure classification for smarter rebalancing./// When disabled, falls back to lease-based behavior.@@ -441,6 +450,10 @@ impl Config {Duration::from_secs(self.coordinator_reconcile_secs)}+ pub fn coordinator_handoff_deadline(&self) -> Duration {+ Duration::from_secs(self.coordinator_handoff_deadline_secs)+ }+pub fn stash_max_wait(&self) -> Duration {Duration::from_millis(self.stash_max_wait_ms)}diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rsindex 28f83dea6407..810fd90c86bf 100644--- a/rust/personhog-router/src/main.rs+++ b/rust/personhog-router/src/main.rs@@ -363,6 +363,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {election_retry_interval: config.coordinator_election_retry_interval(),rebalance_debounce_interval: config.coordinator_rebalance_debounce_interval(),reconcile_interval: config.coordinator_reconcile_interval(),+ handoff_deadline: config.coordinator_handoff_deadline(),},Arc::new(StickyBalancedStrategy),k8s_awareness,diff --git a/rust/personhog-stateright/src/main.rs b/rust/personhog-stateright/src/main.rsindex 9f2082e2ddfc..055e45b93f1b 100644--- a/rust/personhog-stateright/src/main.rs+++ b/rust/personhog-stateright/src/main.rs@@ -41,12 +41,14 @@ fn main() {let model = HandoffModel {pods: 2,routers: 2,+ late_routers: 0,partitions: 1,variant,writes: 2,reads: 1,crashes,rejoins: 0,+ router_joins: 0,zombie_window,probes: false,};diff --git a/rust/personhog-stateright/src/model.rs b/rust/personhog-stateright/src/model.rsindex 2edc92e9d524..4c98509d8f78 100644--- a/rust/personhog-stateright/src/model.rs+++ b/rust/personhog-stateright/src/model.rs@@ -48,6 +48,14 @@ fn production_handoff(p: Partition, h: &Handoff) -> HandoffState {phase: h.phase,started_at: 0,handoff_id: h.id.to_string(),+ // The model always captures a snapshot (its Rebalance mirrors+ // the production coordinator, which always writes one). The+ // production `None` legacy fallback is a serialization concern+ // pinned by unit tests, not a reachable state here. With+ // `RouterJoin` in the action space the snapshot diverges from+ // the live registry, and the production quorum predicate below+ // is exercised on exactly that divergence.+ freeze_quorum: Some(h.quorum.iter().map(|r| router_name(*r)).collect()),}}@@ -69,6 +77,9 @@ pub enum Variant {pub struct HandoffModel {pub pods: u8,pub routers: u8,+ /// Additional router slots that start unregistered and not running;+ /// they exist only to `RouterJoin` mid-run.+ pub late_routers: u8,pub partitions: u8,pub variant: Variant,/// Total client writes the checker may inject.@@ -79,6 +90,9 @@ pub struct HandoffModel {pub crashes: u8,/// Times a dead pod may rejoin under its old name.pub rejoins: u8,+ /// Times a router may (re)join: late slots coming up, or dead+ /// routers returning as fresh processes.+ pub router_joins: u8,/// Writes a lease-expired pod may still accept before its keepalive/// self-fences it. Zero disables the zombie window entirely.pub zombie_window: u8,@@ -114,7 +128,7 @@ impl HandoffModel {0..self.pods}fn router_ids(&self) -> impl Iterator<Item = RouterId> {- 0..self.routers+ 0..(self.routers + self.late_routers)}fn partition_ids(&self) -> impl Iterator<Item = Partition> {0..self.partitions@@ -280,11 +294,14 @@ impl Model for HandoffModel {let routers: BTreeMap<RouterId, Router> = self.router_ids().map(|id| {+ // Slots at or past `routers` start dark and only come up+ // via `RouterJoin`.+ let active = id < self.routers;(id,Router {- registered: true,- running: true,+ registered: active,+ running: active,table: BTreeMap::new(),stashing: BTreeSet::new(),stash: BTreeMap::new(),@@ -311,6 +328,7 @@ impl Model for HandoffModel {reads_left: self.reads,crashes_left: self.crashes,rejoins_left: self.rejoins,+ router_joins_left: self.router_joins,next_write_id: 0,reads_served: 0,lost_acked_write: false,@@ -355,6 +373,9 @@ impl Model for HandoffModel {}for r in self.router_ids() {actions.push(Action::RouterSelfFence(r));+ if state.router_joins_left > 0 {+ actions.push(Action::RouterJoin(r));+ }}}@@ -431,6 +452,13 @@ impl Model for HandoffModel {// sequential handoff-id assignment is deterministic// (next_state must be a pure function of its inputs).plan.handoffs.sort_by_key(|h| h.partition);+ // Mirror of the coordinator's snapshot read: the routers+ // registered when the plan is applied become the freeze+ // requirement for every handoff it creates.+ let quorum: BTreeSet<RouterId> = self+ .router_ids()+ .filter(|r| state.routers[r].registered)+ .collect();for planned in plan.handoffs {let id = state.next_handoff_id;state.next_handoff_id += 1;@@ -443,6 +471,7 @@ impl Model for HandoffModel {old_owner: planned.old_owner.as_deref().map(pod_id),new_owner: pod_id(&planned.new_owner),phase: Phase::Freezing,+ quorum: quorum.clone(),},).is_some();@@ -879,6 +908,24 @@ impl Model for HandoffModel {router.stashing.clear();router.stash.clear();}+ Action::RouterJoin(r) => {+ let router = &state.routers[&r];+ if state.router_joins_left == 0 || router.registered || router.running {+ return None;+ }+ state.router_joins_left -= 1;+ // A fresh process: registration written, table empty+ // (fail-closed until Observe converges it — the model's+ // bootstrap). Handoffs created before this point do not+ // carry it in their quorum; the live-set legacy rule+ // would have counted it from here on.+ let router = state.routers.get_mut(&r).unwrap();+ router.registered = true;+ router.running = true;+ router.table.clear();+ router.stashing.clear();+ router.stash.clear();+ }}if state == *last {@@ -990,6 +1037,41 @@ impl Model for HandoffModel {}),];if self.probes {+ // The freeze-quorum snapshot doing its job: a handoff+ // advanced past Freezing while some registered router — a+ // late joiner outside the snapshot — never wrote a freeze+ // ack for it. Under the pre-snapshot live-set rule this+ // state is unreachable; its reachability is the machine+ // statement that the wedge is fixed, and the safety+ // properties judge every interleaving that reaches it.+ // Two in-flight handoffs carrying different snapshots —+ // one created before a join, one after, coexisting because+ // the first is pinned while a crash forces a second+ // rebalance. This is the shape that would expose a refactor+ // computing "the" requirement once from live state and+ // sharing it across handoffs: correct-looking, wrong only+ // here, invisible to every single-partition config.+ props.push(Property::<Self>::sometimes(+ "handoffs_with_divergent_quorums",+ |_, s| {+ s.handoffs+ .values()+ .any(|h1| s.handoffs.values().any(|h2| h1.quorum != h2.quorum))+ },+ ));+ props.push(Property::<Self>::sometimes(+ "advances_past_silent_late_joiner",+ |m, s| {+ s.handoffs.iter().any(|(p, h)| {+ h.phase != Phase::Freezing+ && m.router_ids().any(|r| {+ s.routers[&r].registered+ && !h.quorum.contains(&r)+ && s.freeze_acks.get(&(*p, r)) != Some(&h.id)+ })+ })+ },+ ));// Two or more handoffs in flight at once (one rebalance txn// creates them all; concurrent rebalances only add handoffs// for unpinned partitions).diff --git a/rust/personhog-stateright/src/types.rs b/rust/personhog-stateright/src/types.rsindex c2be2309d465..248e0ad23726 100644--- a/rust/personhog-stateright/src/types.rs+++ b/rust/personhog-stateright/src/types.rs@@ -27,6 +27,13 @@ pub struct Handoff {pub old_owner: Option<PodId>,pub new_owner: PodId,pub phase: Phase,+ /// The freeze-quorum snapshot: routers registered when the rebalance+ /// created this handoff (production `HandoffState::freeze_quorum`,+ /// always captured — the model never writes legacy records, so the+ /// production `None` fallback is pinned by unit tests instead).+ /// With `RouterJoin` in the action space this diverges from the live+ /// registry, which is exactly what the checker is here to explore.+ pub quorum: BTreeSet<RouterId>,}/// Per-partition warm state on a pod — everything the invariants need to@@ -143,6 +150,9 @@ pub struct SystemState {pub reads_left: u8,pub crashes_left: u8,pub rejoins_left: u8,+ /// Times a router may (re)join: a late slot coming up for the first+ /// time, or a dead router returning as a fresh process.+ pub router_joins_left: u8,pub next_write_id: WriteId,/// Count of strong reads actually served (reachability evidence for/// the read properties).@@ -236,4 +246,13 @@ pub enum Action {/// The zombie router's keepalive notices the dead lease and the/// process exits (production fix 1).RouterSelfFence(RouterId),+ /// A router process starts and registers: a late slot coming up+ /// mid-run, or a dead router returning under its old name. Fresh+ /// process, empty table — production `load_initial` starts from an+ /// empty routing table that fails every lookup closed, and the+ /// model's `Observe` is its bootstrap. A joiner whose `Observe` the+ /// checker never schedules is precisely the silent late joiner the+ /// freeze-quorum snapshot exists to tolerate: registered, counted by+ /// the legacy live-set rule, acking nothing.+ RouterJoin(RouterId),}diff --git a/rust/personhog-stateright/tests/model_tests.rs b/rust/personhog-stateright/tests/model_tests.rsindex c7e2ed50d4d9..b87f42f7122d 100644--- a/rust/personhog-stateright/tests/model_tests.rs+++ b/rust/personhog-stateright/tests/model_tests.rs@@ -32,12 +32,14 @@ fn base() -> HandoffModel {HandoffModel {pods: 2,routers: 2,+ late_routers: 0,partitions: 1,variant: Variant::Current,writes: 2,reads: 1,crashes: 0,rejoins: 0,+ router_joins: 0,zombie_window: 0,probes: false,}@@ -232,6 +234,196 @@ fn epoch_fenced_two_partitions_double_zombie_is_safe() {assert!(checker.discovery("no_split_write_acceptance").is_none());}+/// A router that joins mid-run — the rolling-deploy scenario behind the+/// freeze-quorum snapshot. The joiner starts with an empty (fail-closed)+/// table, is excluded from the quorum of every handoff created before+/// it, and the checker explores every interleaving of its bootstrap+/// (`Observe`) with the coordinator's advancement — including the silent+/// joiner whose bootstrap never runs. Every safety property must hold+/// across all of them, and the run must still converge.+///+/// The crash budget also reaches the same-name rejoin: a snapshot+/// member lease-expires, self-fences, and rejoins as a fresh process —+/// required again (snapshot member, live), empty table, while its dead+/// incarnation's freeze ack persists in etcd (acks are not+/// lease-bound, exactly as in production). The checker judges those+/// interleavings here too; safety holds because the fresh process+/// fails closed until its bootstrap converges it.+#[test]+fn late_router_join_is_safe_and_live() {+ HandoffModel {+ routers: 1,+ late_routers: 1,+ router_joins: 1,+ crashes: 1,+ ..base()+ }+ .checker()+ .spawn_bfs()+ .join()+ .assert_properties();+}++/// Reachability probe for the snapshot doing its job: a handoff advances+/// past Freezing while a registered late joiner has acked nothing.+/// Under the pre-snapshot live-set rule this state is unreachable — the+/// joiner's ack would be required, which is precisely the wedge — so its+/// reachability is the machine statement that the fix works, and the+/// same run asserts no safety property breaks in any interleaving that+/// reaches it.+#[test]+fn probe_silent_late_joiner_advance_is_reachable_and_safe() {+ let checker = HandoffModel {+ routers: 1,+ late_routers: 1,+ router_joins: 1,+ writes: 1,+ reads: 0,+ probes: true,+ ..base()+ }+ .checker()+ .spawn_bfs()+ .join();+ assert!(+ checker+ .discovery("advances_past_silent_late_joiner")+ .is_some(),+ "a handoff must be able to advance while a registered late joiner has not acked"+ );+ assert!(+ checker.discovery("no_lost_acked_write").is_none(),+ "advancing past a silent late joiner must not lose acked writes"+ );+ assert!(+ checker.discovery("no_split_write_acceptance").is_none(),+ "advancing past a silent late joiner must not create dual write acceptance"+ );+}++/// A rebalance that fires while zero routers are registered writes a+/// captured-but-empty snapshot, and a router joining afterward must not+/// be required by it — `Some([])` means nobody was routing, not "apply+/// the legacy live-set fallback". The unit test pins the predicate in+/// isolation; this checks the semantics end to end — snapshot capture,+/// shared predicate, advancement, convergence — and the probe confirms+/// the handoff genuinely advances while the joiner has acked nothing.+#[test]+fn zero_router_creation_with_late_joiner_is_safe_and_live() {+ let checker = HandoffModel {+ routers: 0,+ late_routers: 1,+ router_joins: 1,+ writes: 1,+ reads: 0,+ probes: true,+ ..base()+ }+ .checker()+ .spawn_bfs()+ .join();+ assert!(+ checker+ .discovery("advances_past_silent_late_joiner")+ .is_some(),+ "an empty snapshot must advance without the late joiner's ack"+ );+ for safety in [+ "no_lost_acked_write",+ "no_split_write_acceptance",+ "drained_ack_is_final",+ "strong_reads_complete",+ "no_double_planned_handoff",+ ] {+ assert!(+ checker.discovery(safety).is_none(),+ "{safety} must hold under zero-router creation"+ );+ }+ assert!(+ checker.discovery("converges_to_stable").is_none(),+ "runs must still converge when handoffs were created router-less"+ );+}++/// Two in-flight handoffs carrying different snapshots: the first+/// rebalance's handoff (pre-join quorum) is still pinned while a pod+/// crash forces a second rebalance whose handoff captures the post-join+/// registry. Each handoff's requirement must be judged against its own+/// snapshot — this is the config that would catch a refactor computing+/// one requirement from live state and sharing it across handoffs,+/// which no single-partition config can distinguish from correct.+#[test]+fn probe_divergent_quorums_are_reachable_and_safe() {+ let checker = HandoffModel {+ partitions: 2,+ routers: 1,+ late_routers: 1,+ router_joins: 1,+ crashes: 1,+ writes: 1,+ reads: 0,+ probes: true,+ ..base()+ }+ .checker()+ .spawn_bfs()+ .join();+ assert!(+ checker+ .discovery("handoffs_with_divergent_quorums")+ .is_some(),+ "concurrent handoffs with different creation-time snapshots must be reachable"+ );+ assert!(+ checker.discovery("no_lost_acked_write").is_none(),+ "divergent quorums must not lose acked writes"+ );+ assert!(+ checker.discovery("no_double_planned_handoff").is_none(),+ "pinning must hold while snapshots diverge"+ );+ assert!(+ checker.discovery("no_split_write_acceptance").is_none(),+ "divergent quorums must not create dual write acceptance"+ );+}++/// The snapshot made the freeze quorum smaller, so the sharpest question+/// is whether the shrink reopens the residual epoch fencing closed. The+/// worst mix: a zombie router (a departed snapshot member — now exempt —+/// still routing on a stale table), a zombie pod, and a late joiner+/// outside every snapshot, all at once. Fencing is broker-side and+/// membership-independent, so the guarantee must survive; this run+/// checks that argument instead of trusting it.+#[test]+fn epoch_fenced_double_zombie_with_late_joiner_is_safe() {+ let checker = HandoffModel {+ variant: Variant::EpochFenced,+ routers: 1,+ late_routers: 1,+ router_joins: 1,+ crashes: 2,+ zombie_window: 1,+ ..base()+ }+ .checker()+ .spawn_bfs()+ .join();+ assert!(+ checker.discovery("no_lost_acked_write").is_none(),+ "the shrunken quorum must not reopen acked-write loss under fencing"+ );+ assert!(+ checker.discovery("no_split_write_acceptance").is_none(),+ "the shrunken quorum must not reopen dual write acceptance under fencing"+ );+ assert!(+ checker.discovery("drained_ack_is_final").is_none(),+ "a drained ack must remain final with membership churn"+ );+}+/// Reachability probe: concurrent handoffs are a real scenario — one/// rebalance transaction creates a handoff per moved/fresh partition, so/// the phase machinery is genuinely exercised with multiple handoffs in