: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): a stuck handoff defers only its own partition (#71774)
Zach Brown42830b48409d
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.ymlindex 8909f20bcdf5..42fc677cdc40 100644--- a/.github/workflows/ci-rust.yml+++ b/.github/workflows/ci-rust.yml@@ -154,6 +154,7 @@ jobs:"personhog-leader": 115,"personhog-replica": 140,"personhog-router": 38,+ "personhog-stateright": 700,"posthog-symbol-data": 19,"property-defs-rs": 136,"posthog-replay-anonymizer": 20,diff --git a/rust/.config/nextest.toml b/rust/.config/nextest.tomlindex 5db7073b1ca4..fce523bb5419 100644--- a/rust/.config/nextest.toml+++ b/rust/.config/nextest.toml@@ -22,3 +22,11 @@ fail-fast = false[profile.ci.junit]path = "junit.xml"++# The two-partition double-zombie model checks each saturate every core+# (stateright spawn_bfs); running them concurrently on a small CI runner+# roughly doubles both. Requiring all test threads runs them one at a+# time with the full machine each.+[[profile.ci.overrides]]+filter = 'package(personhog-stateright) and (test(two_partitions_double_zombie_loses_acked_writes) or test(epoch_fenced_two_partitions_double_zombie_is_safe))'+threads-required = "num-cpus"diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex 2c76dc60ff05..178c9f0733cf 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -113,6 +113,16 @@ opt-level = 3[profile.dev.package.stateright]opt-level = 3+# The model's rebalance action runs the production placement computation+# (plan_partial_rebalance, the sticky strategy, the handoff diff) in every+# explored state, so the crates that host it need the same treatment or+# the checker's hot loop drops back to opt-level 0.+[profile.dev.package.personhog-coordination]+opt-level = 3++[profile.dev.package.assignment-coordination]+opt-level = 3+[workspace.dependencies]aho-corasick = "1.1"anyhow = "1.0"diff --git a/rust/common/assignment-coordination/src/store.rs b/rust/common/assignment-coordination/src/store.rsindex 507c3788a832..dc071aa09e45 100644--- a/rust/common/assignment-coordination/src/store.rs+++ b/rust/common/assignment-coordination/src/store.rs@@ -122,6 +122,21 @@ impl EtcdStore {Ok((items, revision))}+ /// Like `list`, but pairs each value with its key's `mod_revision` —+ /// the per-key version an optimistic transaction compares against to+ /// assert the record is unchanged since this read.+ pub async fn list_with_mod_revisions<T: DeserializeOwned>(+ &self,+ prefix: &str,+ ) -> Result<Vec<(T, i64)>> {+ let options = GetOptions::new().with_prefix();+ let resp = self.client.clone().get(prefix, Some(options)).await?;+ resp.kvs()+ .iter()+ .map(|kv| Ok((serde_json::from_slice(kv.value())?, kv.mod_revision())))+ .collect()+ }+/// The current etcd store revision, for anchoring watches when no/// snapshot read is involved.pub async fn current_revision(&self) -> Result<i64> {diff --git a/rust/personhog-coordination/src/coordinator.rs b/rust/personhog-coordination/src/coordinator.rsindex 7437c5a065db..c6bfd8c2d80d 100644--- a/rust/personhog-coordination/src/coordinator.rs+++ b/rust/personhog-coordination/src/coordinator.rs@@ -10,12 +10,10 @@ use k8s_awareness::types::ControllerKind;use k8s_awareness::{DepartureReason, K8sAwareness};use crate::error::{Error, Result};-use crate::protocol::{drain_satisfied, freeze_quorum_met, plan_rebalance, warm_satisfied};+use crate::protocol::{drain_satisfied, freeze_quorum_met, plan_partial_rebalance, warm_satisfied};use crate::store::{self, PersonhogStore};use crate::strategy::AssignmentStrategy;-use crate::types::{- AssignmentStatus, HandoffPhase, HandoffState, PartitionAssignment, PodStatus, RegisteredPod,-};+use crate::types::{AssignmentPrecondition, HandoffPhase, HandoffState, PodStatus, RegisteredPod};use crate::util;@@ -352,8 +350,10 @@ impl Coordinator {}// After processing all events in this batch, check if all- // handoffs have completed. If so, re-trigger rebalancing to- // pick up any pod changes that were deferred.+ // handoffs have completed. If so, re-trigger rebalancing as+ // the final sweep for moves that were pinned while these+ // handoffs were in flight (pod changes themselves are never+ // deferred; they plan around the in-flight set).if store.list_handoffs().await?.is_empty() {Self::handle_pod_change_static(&store,@@ -585,29 +585,43 @@ impl Coordinator {// be stuck forever otherwise.Self::cleanup_stale_handoffs(store).await?;- // Skip rebalancing while handoffs are in flight to prevent overlapping- // rebalances from overwriting each other. The watch_handoffs_loop will- // re-trigger rebalancing once all handoffs complete.- let remaining_handoffs = store.list_handoffs().await?;- if !remaining_handoffs.is_empty() {+ // In-flight handoffs pin their partitions: the plan excludes them+ // (no second handoff, no assignment write) and attributes them to+ // their target for the balance math, so a stuck handoff defers+ // only its own partition instead of all rebalancing.+ let in_flight = store.list_handoffs().await?;+ if !in_flight.is_empty() {tracing::info!(- in_flight = remaining_handoffs.len(),- "handoffs in progress, deferring rebalance"+ pinned = in_flight.len(),+ "planning around in-flight handoffs");- return Ok(());}- let current_assignments = store.list_assignments().await?;+ // One revisioned snapshot feeds both the placement computation and+ // the apply-time preconditions: a handoff's old_owner is only+ // meaningful while the assignment it was read from is unchanged.+ let current_assignments = store.list_assignments_with_mod_revisions().await?;let current_map: HashMap<u32, String> = current_assignments.iter()- .map(|a| (a.partition, a.owner.clone()))+ .map(|(a, _)| (a.partition, a.owner.clone()))+ .collect();+ let assignment_revisions: HashMap<u32, i64> = current_assignments+ .iter()+ .map(|(a, revision)| (a.partition, *revision)).collect();// Placement and diff semantics (moves carry the prior owner, fresh// partitions carry none, everything goes through Freezing) live in- // `protocol::plan_rebalance`, shared with the stateright model.- let plan = plan_rebalance(strategy, ¤t_map, &active_pods, total_partitions);+ // `protocol::plan_partial_rebalance`, shared with the stateright+ // model.+ let plan = plan_partial_rebalance(+ strategy,+ ¤t_map,+ &in_flight,+ &active_pods,+ total_partitions,+ );if plan.handoffs.is_empty() {tracing::debug!("no handoffs needed");@@ -639,26 +653,37 @@ impl Coordinator {"creating handoffs");- // Assignments for partitions that are NOT being moved (correct owner- // already) still need to be written to etcd, but reassignments and- // fresh assignments defer their PartitionAssignment writes until the- // handoff reaches Complete.- let handoff_partitions: HashSet<u32> =- handoff_objects.iter().map(|h| h.partition).collect();- let stable_assignments: Vec<PartitionAssignment> = plan- .desired+ // The rebalance writes no assignment records: handoff completion is+ // the sole writer of assignments (see `complete_handoff`'s+ // invariant), so routers always observe owner changes as Complete+ // events, and a stale plan can never restore a superseded owner.+ // Each handoff instead carries a precondition tying it to the+ // snapshot its old_owner came from.+ let preconditions: Vec<AssignmentPrecondition> = handoff_objects.iter()- .map(|(&partition, owner)| PartitionAssignment {- partition,- owner: owner.clone(),- status: AssignmentStatus::Active,+ .map(|h| match assignment_revisions.get(&h.partition) {+ Some(&mod_revision) => AssignmentPrecondition::UnchangedSince {+ partition: h.partition,+ mod_revision,+ },+ None => AssignmentPrecondition::Absent {+ partition: h.partition,+ },})- .filter(|a| !handoff_partitions.contains(&a.partition)).collect();- store- .create_assignments_and_handoffs(&stable_assignments, &handoff_objects)- .await?;+ if !store+ .create_assignments_and_handoffs(&[], &handoff_objects, &preconditions)+ .await?+ {+ // A concurrent invocation (the empty-set re-trigger racing a+ // pod event, or a failing-over coordinator) created a handoff+ // first. Its plan acted on fresher state than ours; whatever+ // this plan wanted beyond it is replanned by the next pod+ // event or the final sweep.+ tracing::info!("concurrent plan won handoff creation; standing down");+ return Ok(());+ }// Nudge advancement for handoffs whose preconditions are already// satisfied at creation time (no old_owner, dead old_owner, vacuousdiff --git a/rust/personhog-coordination/src/protocol.rs b/rust/personhog-coordination/src/protocol.rsindex 8655f608fd8b..b2b32170b626 100644--- a/rust/personhog-coordination/src/protocol.rs+++ b/rust/personhog-coordination/src/protocol.rs@@ -46,10 +46,13 @@ pub struct RebalancePlan {/// at Freezing — including fresh assignments — so routers never route to/// a pod whose cache hasn't been warmed.///-/// Callers must not rebalance while any handoff is in flight-/// (overlapping rebalances would overwrite each other); the coordinator-/// defers until the in-flight set is empty, and the model gates its-/// rebalance action the same way.+/// Callers with handoffs in flight must plan through+/// `plan_partial_rebalance`, which pins those partitions — planning a+/// mid-move partition twice would create overlapping handoffs and+/// conflicting assignment writes. The coordinator and the stateright+/// model both plan through the partial variant; the model's+/// `no_double_planned_handoff` property verifies the pinning across+/// every interleaving of rebalances with in-flight handoffs.pub fn plan_rebalance<S: AssignmentStrategy + ?Sized>(strategy: &S,current: &HashMap<u32, String>,@@ -80,6 +83,35 @@ pub fn plan_rebalance<S: AssignmentStrategy + ?Sized>(RebalancePlan { desired, handoffs }}+/// Plan a rebalance around in-flight handoffs. Their partitions are+/// pinned: excluded from the planned handoffs and from `desired` (whose+/// entries the coordinator writes as stable assignments), so the two+/// overlap hazards — a second handoff for a mid-move partition, and an+/// assignment write for one — are impossible by construction, and a+/// stuck handoff defers only its own partition instead of the topology.+/// For the placement computation each pinned partition is attributed to+/// its handoff's new owner, so the balance math agrees with the imminent+/// state and a sticky strategy plans around the in-flight moves instead+/// of fighting them.+pub fn plan_partial_rebalance<S: AssignmentStrategy + ?Sized>(+ strategy: &S,+ current: &HashMap<u32, String>,+ in_flight: &[HandoffState],+ active_pods: &[String],+ total_partitions: u32,+) -> RebalancePlan {+ let pinned: HashSet<u32> = in_flight.iter().map(|h| h.partition).collect();+ let mut effective = current.clone();+ for handoff in in_flight {+ effective.insert(handoff.partition, handoff.new_owner.clone());+ }+ let mut plan = plan_rebalance(strategy, &effective, active_pods, total_partitions);+ plan.handoffs.retain(|h| !pinned.contains(&h.partition));+ plan.desired+ .retain(|partition, _| !pinned.contains(partition));+ plan+}+/// Whether the freeze quorum for `handoff` is met.////// Identity-based: every currently registered router must have acked@@ -145,3 +177,72 @@ pub fn warm_satisfied(warmed_acks: &[PodWarmedAck], handoff: &HandoffState) -> b.iter().any(|a| a.pod_name == handoff.new_owner && a.handoff_id == handoff.handoff_id)}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::strategy::StickyBalancedStrategy;++ fn handoff(partition: u32, old_owner: Option<&str>, new_owner: &str) -> HandoffState {+ HandoffState {+ partition,+ old_owner: old_owner.map(str::to_string),+ new_owner: new_owner.to_string(),+ phase: crate::types::HandoffPhase::Warming,+ started_at: 0,+ handoff_id: String::new(),+ }+ }++ #[test]+ fn pinned_partitions_are_never_planned() {+ let current: HashMap<u32, String> = (0..4).map(|p| (p, "pod-a".to_string())).collect();+ let in_flight = [handoff(0, Some("pod-a"), "pod-b")];+ let active = [+ "pod-a".to_string(),+ "pod-b".to_string(),+ "pod-c".to_string(),+ ];++ let plan =+ plan_partial_rebalance(&StickyBalancedStrategy, ¤t, &in_flight, &active, 4);++ assert!(+ plan.handoffs.iter().all(|h| h.partition != 0),+ "a pinned partition must never get a second handoff"+ );+ assert!(+ !plan.desired.contains_key(&0),+ "a pinned partition must never get an assignment write"+ );+ // A stuck handoff defers only itself: the new pod still receives+ // partitions from the unpinned remainder.+ assert!(+ plan.handoffs.iter().any(|h| h.new_owner == "pod-c"),+ "unpinned partitions must still rebalance toward the new pod"+ );+ }++ #[test]+ fn pinned_partitions_count_against_their_target() {+ // Two of pod-a's four partitions are mid-move to pod-b. Attributed+ // to their target, the placement is already balanced — a plan that+ // read the raw current map would see 4-vs-0 and churn the other+ // two partitions to pod-b right behind the in-flight moves.+ let current: HashMap<u32, String> = (0..4).map(|p| (p, "pod-a".to_string())).collect();+ let in_flight = [+ handoff(0, Some("pod-a"), "pod-b"),+ handoff(1, Some("pod-a"), "pod-b"),+ ];+ let active = ["pod-a".to_string(), "pod-b".to_string()];++ let plan =+ plan_partial_rebalance(&StickyBalancedStrategy, ¤t, &in_flight, &active, 4);++ assert!(+ plan.handoffs.is_empty(),+ "in-flight moves already balance the placement; planning more is churn: {:?}",+ plan.handoffs+ );+ }+}diff --git a/rust/personhog-coordination/src/store.rs b/rust/personhog-coordination/src/store.rsindex f1cfed326063..b26667201aba 100644--- a/rust/personhog-coordination/src/store.rs+++ b/rust/personhog-coordination/src/store.rs@@ -3,8 +3,8 @@ use etcd_client::{Compare, CompareOp, DeleteOptions, PutOptions, Txn, TxnOp, Watuse crate::error::{Error, Result};use crate::types::{- AssignmentStatus, HandoffState, LeaderInfo, PartitionAssignment, PodDrainedAck, PodStatus,- PodWarmedAck, RegisteredPod, RegisteredRouter, RouterFreezeAck,+ AssignmentPrecondition, AssignmentStatus, HandoffState, LeaderInfo, PartitionAssignment,+ PodDrainedAck, PodStatus, PodWarmedAck, RegisteredPod, RegisteredRouter, RouterFreezeAck,};/// All etcd key patterns used by the PersonHog store.@@ -181,6 +181,16 @@ impl PersonhogStore {Ok(self.inner.list_with_revision(&key).await?)}+ /// Like `list_assignments`, but pairs each record with its key's+ /// `mod_revision` so a plan can assert, at apply time, that the+ /// assignments it read are unchanged (`AssignmentPrecondition`).+ pub async fn list_assignments_with_mod_revisions(+ &self,+ ) -> Result<Vec<(PartitionAssignment, i64)>> {+ let key = self.key(StoreKey::AssignmentsPrefix);+ Ok(self.inner.list_with_mod_revisions(&key).await?)+ }+pub async fn put_assignments(&self, assignments: &[PartitionAssignment]) -> Result<()> {if assignments.is_empty() {return Ok(());@@ -427,11 +437,30 @@ impl PersonhogStore {// ── Transactional operations ────────────────────────────────/// Atomically write assignments and create handoff states.+ /// Returns whether the transaction applied. Guarded so a plan only+ /// lands if the world it was computed from is still the world:+ ///+ /// * every handoff key must be absent — concurrent planners (the pod+ /// watch racing the handoff watch's re-trigger, or a failing-over+ /// coordinator) can both plan the same partition, and an unguarded+ /// put would replace the first handoff and orphan its acks;+ /// * every `AssignmentPrecondition` must hold — a handoff's+ /// `old_owner` is only meaningful if the assignment it was read+ /// from is unchanged. Without this, a plan whose snapshot predates+ /// a full create→complete→cleanup cycle of the same partition+ /// passes the absence guard and drains the wrong pod, leaving the+ /// real owner unfenced beside the new owner's warm cutoff.+ ///+ /// All-or-nothing on purpose — a plan is one consistent placement+ /// computation, and the losing caller replans off the winner's writes+ /// rather than applying a half-stale plan.pub async fn create_assignments_and_handoffs(&self,assignments: &[PartitionAssignment],handoffs: &[HandoffState],- ) -> Result<()> {+ preconditions: &[AssignmentPrecondition],+ ) -> Result<bool> {+ let mut guards: Vec<Compare> = Vec::with_capacity(handoffs.len() + preconditions.len());let mut ops: Vec<TxnOp> = Vec::with_capacity(assignments.len() + handoffs.len());for a in assignments {@@ -442,12 +471,30 @@ impl PersonhogStore {for h in handoffs {let key = self.key(StoreKey::Handoff(h.partition));let value = serde_json::to_vec(h)?;+ // A key that was never created has create_revision 0 — the+ // canonical etcd existence guard.+ guards.push(Compare::create_revision(key.clone(), CompareOp::Equal, 0));ops.push(TxnOp::put(key, value, None));}+ for precondition in preconditions {+ match precondition {+ AssignmentPrecondition::UnchangedSince {+ partition,+ mod_revision,+ } => {+ let key = self.key(StoreKey::Assignment(*partition));+ guards.push(Compare::mod_revision(key, CompareOp::Equal, *mod_revision));+ }+ AssignmentPrecondition::Absent { partition } => {+ let key = self.key(StoreKey::Assignment(*partition));+ guards.push(Compare::create_revision(key, CompareOp::Equal, 0));+ }+ }+ }- let txn = Txn::new().and_then(ops);- self.inner.txn(txn).await?;- Ok(())+ let txn = Txn::new().when(guards).and_then(ops);+ let resp = self.inner.txn(txn).await?;+ Ok(resp.succeeded())}/// Atomically: set handoff phase to Complete and update the assignment owner.diff --git a/rust/personhog-coordination/src/types.rs b/rust/personhog-coordination/src/types.rsindex c919b1795671..ae8494829392 100644--- a/rust/personhog-coordination/src/types.rs+++ b/rust/personhog-coordination/src/types.rs@@ -58,6 +58,17 @@ pub enum AssignmentStatus {Active,}+/// What a rebalance plan asserts, at apply time, about a touched+/// partition's assignment record: the plan's handoffs derive their+/// `old_owner` from the assignments it read, so applying is only sound+/// while those records are exactly as read (moves) or still absent+/// (fresh partitions).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum AssignmentPrecondition {+ UnchangedSince { partition: u32, mod_revision: i64 },+ Absent { partition: u32 },+}+/// Tracks the progress of moving a partition from one writer pod to another,/// or a fresh initial assignment.///diff --git a/rust/personhog-coordination/tests/integration.rs b/rust/personhog-coordination/tests/integration.rsindex 23ccb1ef13da..9a8c8f7edac7 100644--- a/rust/personhog-coordination/tests/integration.rs+++ b/rust/personhog-coordination/tests/integration.rs@@ -2661,3 +2661,356 @@ async fn routing_table_deregisters_router_on_graceful_exit() {}).await;}++/// A stuck handoff must defer only its own partition. One pod's handoffs+/// wedge at Warming (its handler never acks); a healthy pod that joins+/// afterwards must still receive partitions from the unpinned remainder+/// while the wedged handoffs stay in flight — and those handoffs must+/// never be re-planned. Before per-partition pinning, any in-flight+/// handoff deferred all rebalancing, so the healthy pod owned nothing+/// until the wedge resolved.+#[tokio::test]+async fn stuck_handoff_defers_only_its_own_partition() {+ let store = test_store("stuck_handoff_defers_only_its_own_partition").await;+ let cancel = CancellationToken::new();+ store.set_total_partitions(NUM_PARTITIONS).await.unwrap();++ let _coord = start_coordinator(+ Arc::clone(&store),+ Arc::new(StickyBalancedStrategy),+ cancel.clone(),+ );+ let _pod0 = start_pod(Arc::clone(&store), "writer-0", cancel.clone());++ 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;++ // The blocking pod joins: the rebalance moves partitions toward it and+ // every one of those handoffs wedges at Warming.+ let _blocked = start_pod_blocking(Arc::clone(&store), "writer-blocked", 30, cancel.clone());+ let check_store = Arc::clone(&store);+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {+ let store = Arc::clone(&check_store);+ async move {+ store+ .list_handoffs()+ .await+ .unwrap_or_default()+ .iter()+ .any(|h| h.new_owner == "writer-blocked")+ }+ })+ .await;++ let stuck: Vec<(u32, String)> = store+ .list_handoffs()+ .await+ .unwrap()+ .into_iter()+ .filter(|h| h.new_owner == "writer-blocked")+ .map(|h| (h.partition, h.handoff_id))+ .collect();+ assert!(!stuck.is_empty());++ // A healthy pod joins while those handoffs are wedged: it must own+ // partitions while they are still in flight.+ let _pod2 = start_pod(Arc::clone(&store), "writer-2", cancel.clone());+ 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.iter().any(|a| a.owner == "writer-2")+ && handoffs.iter().any(|h| h.new_owner == "writer-blocked")+ }+ })+ .await;++ // The wedged handoffs were pinned, never re-planned: each survives+ // with its original identity.+ let handoffs = store.list_handoffs().await.unwrap();+ for (partition, handoff_id) in &stuck {+ assert!(+ handoffs+ .iter()+ .any(|h| h.partition == *partition && h.handoff_id == *handoff_id),+ "pinned handoff for partition {partition} was replanned or destroyed"+ );+ }+}++/// Concurrent planners can both read a partition as unpinned and plan it;+/// handoff creation is guarded create-if-absent so the second plan's txn+/// fails whole instead of replacing the first handoff and orphaning its+/// acks. The losing plan's writes — including its innocent assignments —+/// must not land either: it was computed against a stale snapshot.+#[tokio::test]+async fn conflicting_plan_cannot_replace_an_in_flight_handoff() {+ use personhog_coordination::types::{+ AssignmentStatus, HandoffPhase, HandoffState, PartitionAssignment,+ };++ let store = test_store("conflicting_plan_cannot_replace_an_in_flight_handoff").await;++ let first = HandoffState {+ partition: 0,+ old_owner: Some("writer-0".to_string()),+ new_owner: "writer-1".to_string(),+ phase: HandoffPhase::Warming,+ started_at: 0,+ handoff_id: "first".to_string(),+ };+ assert!(store+ .create_assignments_and_handoffs(&[], std::slice::from_ref(&first), &[])+ .await+ .unwrap());++ // A competing plan targets the same partition (different owner and+ // id) alongside an uncontested assignment write.+ let competing = HandoffState {+ partition: 0,+ old_owner: Some("writer-0".to_string()),+ new_owner: "writer-2".to_string(),+ phase: HandoffPhase::Freezing,+ started_at: 0,+ handoff_id: "second".to_string(),+ };+ let stable = PartitionAssignment {+ partition: 1,+ owner: "writer-0".to_string(),+ status: AssignmentStatus::Active,+ };+ assert!(!store+ .create_assignments_and_handoffs(&[stable], &[competing], &[])+ .await+ .unwrap());++ // The in-flight handoff survives with its original identity, and the+ // losing plan's assignment never landed.+ let handoffs = store.list_handoffs().await.unwrap();+ assert_eq!(handoffs.len(), 1);+ assert_eq!(handoffs[0].handoff_id, "first");+ assert_eq!(handoffs[0].new_owner, "writer-1");+ assert!(store.list_assignments().await.unwrap().is_empty());+}++/// The reviewer's stale-plan scenario at the store level: a plan whose+/// snapshot predates a concurrent move (create → complete → cleanup, so+/// the handoff key is absent again) must be rejected by its assignment+/// precondition — its handoff names a superseded old_owner, and applying+/// it would drain the wrong pod while the real owner stays unfenced.+#[tokio::test]+async fn stale_plan_is_rejected_when_the_assignment_moved() {+ use personhog_coordination::types::{+ AssignmentPrecondition, AssignmentStatus, HandoffPhase, HandoffState, PartitionAssignment,+ };++ let store = test_store("stale_plan_is_rejected_when_the_assignment_moved").await;++ let assignment = |owner: &str| PartitionAssignment {+ partition: 0,+ owner: owner.to_string(),+ status: AssignmentStatus::Active,+ };+ let handoff = |old: &str, new: &str, id: &str| HandoffState {+ partition: 0,+ old_owner: Some(old.to_string()),+ new_owner: new.to_string(),+ phase: HandoffPhase::Freezing,+ started_at: 0,+ handoff_id: id.to_string(),+ };++ // The world the stale planner reads: partition 0 owned by A.+ assert!(store+ .create_assignments_and_handoffs(&[assignment("pod-a")], &[], &[])+ .await+ .unwrap());+ let snapshot = store.list_assignments_with_mod_revisions().await.unwrap();+ let (_, stale_revision) = snapshot[0];++ // Concurrently, a full move to B lands: by the time the stale plan's+ // txn arrives, the handoff key is gone and only the assignment moved.+ assert!(store+ .create_assignments_and_handoffs(&[assignment("pod-b")], &[], &[])+ .await+ .unwrap());++ // The stale plan (move A -> C, guarded by its snapshot) must fail+ // whole, creating nothing.+ let rejected = store+ .create_assignments_and_handoffs(+ &[],+ &[handoff("pod-a", "pod-c", "stale")],+ &[AssignmentPrecondition::UnchangedSince {+ partition: 0,+ mod_revision: stale_revision,+ }],+ )+ .await+ .unwrap();+ assert!(+ !rejected,+ "a plan reading a superseded owner must not apply"+ );+ assert!(store.list_handoffs().await.unwrap().is_empty());++ // A plan computed from the current snapshot applies fine.+ let snapshot = store.list_assignments_with_mod_revisions().await.unwrap();+ let (current, fresh_revision) = &snapshot[0];+ assert_eq!(current.owner, "pod-b");+ assert!(store+ .create_assignments_and_handoffs(+ &[],+ &[handoff("pod-b", "pod-c", "fresh")],+ &[AssignmentPrecondition::UnchangedSince {+ partition: 0,+ mod_revision: *fresh_revision,+ }],+ )+ .await+ .unwrap());+ let handoffs = store.list_handoffs().await.unwrap();+ assert_eq!(handoffs.len(), 1);+ assert_eq!(handoffs[0].old_owner.as_deref(), Some("pod-b"));+}++/// A fresh-partition handoff asserts the assignment is still absent: if+/// one appeared since the snapshot (the partition got born through a+/// concurrent handoff's completion), the plan's old_owner: None is a lie+/// and the plan must be rejected — and one stale precondition rejects the+/// whole plan, valid handoffs included.+#[tokio::test]+async fn fresh_plan_is_rejected_when_an_assignment_appeared() {+ use personhog_coordination::types::{+ AssignmentPrecondition, AssignmentStatus, HandoffPhase, HandoffState, PartitionAssignment,+ };++ let store = test_store("fresh_plan_is_rejected_when_an_assignment_appeared").await;++ let fresh_handoff = |partition: u32, id: &str| HandoffState {+ partition,+ old_owner: None,+ new_owner: "pod-c".to_string(),+ phase: HandoffPhase::Freezing,+ started_at: 0,+ handoff_id: id.to_string(),+ };++ // Partition 0 gained an assignment after the plan's snapshot.+ assert!(store+ .create_assignments_and_handoffs(+ &[PartitionAssignment {+ partition: 0,+ owner: "pod-b".to_string(),+ status: AssignmentStatus::Active,+ }],+ &[],+ &[],+ )+ .await+ .unwrap());++ // The plan carries one stale fresh-handoff (partition 0) and one+ // genuinely fresh one (partition 1): all-or-nothing rejection.+ let rejected = store+ .create_assignments_and_handoffs(+ &[],+ &[fresh_handoff(0, "stale"), fresh_handoff(1, "innocent")],+ &[+ AssignmentPrecondition::Absent { partition: 0 },+ AssignmentPrecondition::Absent { partition: 1 },+ ],+ )+ .await+ .unwrap();+ assert!(!rejected);+ assert!(store.list_handoffs().await.unwrap().is_empty());++ // Replanned against reality, partition 1 alone applies.+ assert!(store+ .create_assignments_and_handoffs(+ &[],+ &[fresh_handoff(1, "replanned")],+ &[AssignmentPrecondition::Absent { partition: 1 }],+ )+ .await+ .unwrap());+ assert_eq!(store.list_handoffs().await.unwrap().len(), 1);+}++/// The rebalance must never write assignment records — handoff completion+/// is their sole writer, so routers always observe owner changes as+/// Complete events and a stale plan can never restore a superseded owner.+/// Detected via mod revisions, since a redundant rewrite is byte-identical.+#[tokio::test]+async fn rebalance_never_writes_assignment_records() {+ let store = test_store("rebalance_never_writes_assignment_records").await;+ let cancel = CancellationToken::new();+ store.set_total_partitions(NUM_PARTITIONS).await.unwrap();++ let _coord = start_coordinator(+ Arc::clone(&store),+ Arc::new(StickyBalancedStrategy),+ cancel.clone(),+ );+ let _pod0 = start_pod(Arc::clone(&store), "writer-0", cancel.clone());++ 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 before: std::collections::HashMap<u32, i64> = store+ .list_assignments_with_mod_revisions()+ .await+ .unwrap()+ .into_iter()+ .map(|(a, revision)| (a.partition, revision))+ .collect();++ // A second pod joins: a rebalance runs and its handoffs complete.+ let _pod1 = start_pod(Arc::clone(&store), "writer-1", cancel.clone());+ 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();+ handoffs.is_empty() && assignments.iter().any(|a| a.owner == "writer-1")+ }+ })+ .await;++ let after = store.list_assignments_with_mod_revisions().await.unwrap();+ for (assignment, revision) in &after {+ if assignment.owner == "writer-0" {+ assert_eq!(+ before[&assignment.partition], *revision,+ "partition {} was not moved, yet its assignment record was rewritten",+ assignment.partition+ );+ } else {+ assert_ne!(+ before[&assignment.partition], *revision,+ "partition {} moved, so completion must have rewritten its record",+ assignment.partition+ );+ }+ }+}diff --git a/rust/personhog-coordination/tests/protocol_hardening.rs b/rust/personhog-coordination/tests/protocol_hardening.rsindex a13d9f931e5a..96400199e490 100644--- a/rust/personhog-coordination/tests/protocol_hardening.rs+++ b/rust/personhog-coordination/tests/protocol_hardening.rs@@ -49,10 +49,10 @@ async fn put_handoff(started_at: 0,handoff_id: format!("test-handoff-{partition}"),};- store- .create_assignments_and_handoffs(&[], &[handoff])- .await- .expect("write handoff");+ // Raw put on purpose: fixtures force arbitrary handoff states,+ // including overwriting an existing one, which the guarded+ // plan-application path rightly refuses.+ store.put_handoff(&handoff).await.expect("write handoff");}/// Wait until the pod's recorded events contain `expected`.@@ -1314,7 +1314,7 @@ async fn late_joining_router_stashes_before_populating_table() {// Pre-existing state: an assignment for partition 0 and an in-flight// Freezing handoff moving it.- store+ assert!(store.create_assignments_and_handoffs(&[PartitionAssignment {partition: 0,@@ -1322,9 +1322,10 @@ async fn late_joining_router_stashes_before_populating_table() {status: AssignmentStatus::Active,}],&[],+ &[],).await- .expect("write assignment");+ .expect("write assignment"));put_handoff(&store,0,diff --git a/rust/personhog-stateright/src/model.rs b/rust/personhog-stateright/src/model.rsindex 929962eee4b7..4776669c4773 100644--- a/rust/personhog-stateright/src/model.rs+++ b/rust/personhog-stateright/src/model.rs@@ -9,7 +9,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap};use personhog_coordination::pod::{desired_state, DesiredState};use personhog_coordination::protocol::{- drain_satisfied, freeze_quorum_met, plan_rebalance, warm_satisfied,+ drain_satisfied, freeze_quorum_met, plan_partial_rebalance, warm_satisfied,};use personhog_coordination::strategy::{AssignmentStrategy, StickyBalancedStrategy};use personhog_coordination::types::{@@ -310,6 +310,7 @@ impl Model for HandoffModel {next_write_id: 0,reads_served: 0,lost_acked_write: false,+ double_planned_handoff: false,stale_strong_read: false,}]}@@ -375,41 +376,63 @@ impl Model for HandoffModel {}// The rebalance half: create Freezing handoffs for every- // assignment diff in one transaction, only while no handoffs- // are in flight. Placement and diff semantics are the- // production `protocol::plan_rebalance` (strategy + move/fresh- // diff, old_owner from the current assignment); only the etcd- // writes are applied model-side, and assignments for- // moved/fresh partitions are deferred until Complete- // (`create_assignments_and_handoffs`).+ // assignment diff in one transaction. In-flight handoffs pin+ // their partitions — the production+ // `protocol::plan_partial_rebalance` excludes them from the+ // plan and attributes each to its target for the placement+ // computation — so rebalancing is enabled in every state and+ // the checker explores a rebalance racing every handoff+ // phase. Only the etcd writes are applied model-side, and+ // assignments for moved/fresh partitions are deferred until+ // Complete (`create_assignments_and_handoffs`). This action+ // is atomic (plan and apply in one transition); production+ // earns that abstraction by guarding the apply txn on its+ // read-set — handoff keys still absent, and each touched+ // partition's assignment unchanged since the snapshot — so a+ // stale plan fails instead of replacing an in-flight handoff+ // or draining a superseded owner.Action::Rebalance => {- if state.handoffs.is_empty() {- let current: HashMap<u32, String> = state- .assignments- .iter()- .map(|(p, owner)| (*p as u32, pod_name(*owner)))- .collect();- let mut active: Vec<String> = state- .pods- .iter()- .filter(|(_, p)| p.registered)- .map(|(id, _)| pod_name(*id))- .collect();- active.sort();- let mut plan = plan_rebalance(- &StickyBalancedStrategy,- ¤t,- &active,- self.partitions as u32,- );- // The plan's order follows HashMap iteration; sort so- // sequential handoff-id assignment is deterministic- // (next_state must be a pure function of its inputs).- plan.handoffs.sort_by_key(|h| h.partition);- for planned in plan.handoffs {- let id = state.next_handoff_id;- state.next_handoff_id += 1;- state.handoffs.insert(+ let current: HashMap<u32, String> = state+ .assignments+ .iter()+ .map(|(p, owner)| (*p as u32, pod_name(*owner)))+ .collect();+ let in_flight: Vec<HandoffState> = state+ .handoffs+ .iter()+ .map(|(p, h)| production_handoff(*p, h))+ .collect();+ let mut active: Vec<String> = state+ .pods+ .iter()+ .filter(|(_, p)| p.registered)+ .map(|(id, _)| pod_name(*id))+ .collect();+ active.sort();+ let mut plan = plan_partial_rebalance(+ &StickyBalancedStrategy,+ ¤t,+ &in_flight,+ &active,+ self.partitions as u32,+ );+ if plan.handoffs.is_empty() {+ // An empty plan is a no-op successor the checker would+ // dedup anyway; disabling the action instead skips the+ // clone-and-hash per state, which dominates once+ // Rebalance is enabled everywhere.+ return None;+ }+ // The plan's order follows HashMap iteration; sort so+ // sequential handoff-id assignment is deterministic+ // (next_state must be a pure function of its inputs).+ plan.handoffs.sort_by_key(|h| h.partition);+ for planned in plan.handoffs {+ let id = state.next_handoff_id;+ state.next_handoff_id += 1;+ let clobbered = state+ .handoffs+ .insert(planned.partition as Partition,Handoff {id,@@ -417,7 +440,14 @@ impl Model for HandoffModel {new_owner: pod_id(&planned.new_owner),phase: Phase::Freezing,},- );+ )+ .is_some();+ if clobbered {+ // Planning a pinned partition would destroy its+ // in-flight handoff (and orphan its acks); the+ // always-property flags any interleaving where+ // the exclusion fails to prevent that.+ state.double_planned_handoff = true;}}}@@ -859,6 +889,12 @@ impl Model for HandoffModel {// Variant::Current with a zombie window (the documented// residual) and PASS under Variant::EpochFenced.Property::<Self>::always("no_lost_acked_write", |_, s| !s.lost_acked_write),+ // Rebalancing is enabled concurrently with in-flight handoffs;+ // pinning must keep it from ever planning one of their+ // partitions a second time.+ Property::<Self>::always("no_double_planned_handoff", |_, s| {+ !s.double_planned_handoff+ }),// The split-brain condition: two distinct pods each capable// of accepting a write for the same partition AND each// reachable by some live, non-stashing router. Capability@@ -950,20 +986,21 @@ impl Model for HandoffModel {];if self.probes {// Two or more handoffs in flight at once (one rebalance txn- // creates them all; the deferral gate prevents a second- // rebalance from adding more).+ // creates them all; concurrent rebalances only add handoffs+ // for unpinned partitions).props.push(Property::<Self>::sometimes("concurrent_handoffs",|_, s| s.handoffs.len() >= 2,));// A pod that is old owner of one in-flight handoff and new// owner of another — simultaneously drain-side and warm-side.- // Believed unreachable under the shipped protocol: within one- // plan the sticky strategy only takes partitions from pods- // above their target and gives to pods below it (never both),- // and the deferral gate keeps handoffs from different plans- // from coexisting. The probe lets the checker confirm that- // instead of us assuming it.+ // Reachable since partial rebalancing let handoffs from+ // different plans coexist (within one plan the sticky+ // strategy never takes from and gives to the same pod). Safe+ // because every protocol mechanism the two roles touch —+ // fences, inflight counts, cache partitions, acks — is+ // partition-scoped; the probe makes the checker explore the+ // dual-role interleavings the safety properties then judge.props.push(Property::<Self>::sometimes("pod_holds_both_roles",|_, s| {diff --git a/rust/personhog-stateright/src/types.rs b/rust/personhog-stateright/src/types.rsindex 8d3e006c118c..c2be2309d465 100644--- a/rust/personhog-stateright/src/types.rs+++ b/rust/personhog-stateright/src/types.rs@@ -155,6 +155,10 @@ pub struct SystemState {/// warm cutoff and is invisible to it forever. This is the/// acked-write loss the drain/fence/HWM machinery exists to prevent.pub lost_acked_write: bool,+ /// Set when a rebalance plans a partition that already has an+ /// in-flight handoff, clobbering it — the overlap+ /// `plan_partial_rebalance`'s pinning must make unreachable.+ pub double_planned_handoff: bool,/// Set when a strong read is served by a pod whose visible prefix/// (`cutoff + accepted`) is behind the changelog — the read returned/// state missing at least one acked write.diff --git a/rust/personhog-stateright/tests/model_tests.rs b/rust/personhog-stateright/tests/model_tests.rsindex a926b5ae8121..c7e2ed50d4d9 100644--- a/rust/personhog-stateright/tests/model_tests.rs+++ b/rust/personhog-stateright/tests/model_tests.rs@@ -257,16 +257,15 @@ fn probe_concurrent_handoffs_are_reachable() {}/// Reachability probe: a pod simultaneously drain-side of one handoff-/// and warm-side of another is UNREACHABLE under the shipped protocol,-/// even with churn (crash + rejoin) at the smallest scale where the-/// strategy has real choices. The checker proves what the code only-/// implies: within one plan the sticky strategy never takes from and-/// gives to the same pod, and the rebalance deferral gate keeps handoffs-/// from different plans from coexisting. If a strategy or gate change-/// ever makes this reachable, this test fails and the dual-role case-/// needs explicit safety analysis.+/// and warm-side of another. Unreachable under the old global rebalance+/// gate; partial rebalancing (in-flight partitions pinned, everything+/// else planned) deliberately lets handoffs from different plans+/// coexist, so the state is now reachable — and must be safe, since+/// every mechanism the two roles touch is partition-scoped. The same+/// run asserts the safety properties hold across those interleavings+/// and that pinning never plans a mid-move partition a second time.#[test]-fn probe_dual_role_pod_is_unreachable() {+fn probe_dual_role_pod_is_reachable_and_safe() {let checker = HandoffModel {pods: 3,partitions: 3,@@ -281,8 +280,16 @@ fn probe_dual_role_pod_is_unreachable() {.spawn_bfs().join();assert!(- checker.discovery("pod_holds_both_roles").is_none(),- "the sticky strategy + rebalance deferral gate should make dual-role pods unreachable"+ checker.discovery("pod_holds_both_roles").is_some(),+ "partial rebalancing must reach the dual-role state the checker judges"+ );+ assert!(+ checker.discovery("no_double_planned_handoff").is_none(),+ "pinning must keep concurrent rebalances from replanning a mid-move partition"+ );+ assert!(+ checker.discovery("no_lost_acked_write").is_none(),+ "dual-role concurrency must not lose acked writes");}diff --git a/rust/personhog-test-harness/README.md b/rust/personhog-test-harness/README.mdindex 1aecf9ce3b40..12aac33a46ab 100644--- a/rust/personhog-test-harness/README.md+++ b/rust/personhog-test-harness/README.md@@ -3,7 +3,7 @@Load, consistency, and e2e correctness harness for the personhog leader path.Revived from the original personhog-cannon draft (#55581) and extended with stack orchestration, Postgres seeding, and an acked-write journal so it can gate CI, not just generate load.-The core invariant it checks: **every write acked by the leader path is visible afterwards** — in strong reads once coordination has converged (post-chaos handoffs re-driven; an already-settled run waits zero time, and failing to converge within 90s fails the gate), and in Postgres (at or above the highest acked version) once the writer drains.+The core invariant it checks: **every write acked by the leader path is visible afterwards** — in strong reads once coordination has converged (post-chaos handoffs re-driven; an already-settled run waits zero time, and failing to converge within 30s fails the gate), and in Postgres (at or above the highest acked version) once the writer drains.Every acked update is journaled under a unique property key, so the final state must contain all of them regardless of how concurrent writers interleaved.Version assignment is asserted throughout: the leader assigns each version of a person to at most one acked write, so a duplicated acked version (two writes served from the same base state), or a strong read observing a version below the highest ack, is a violation.Read-your-write recency is asserted live: `--probers` (default 2) workers run write-then-strong-read cycles alongside the blast traffic, so a staleness window during a chaos event trips a probe even if it heals before the end-of-run verification.@@ -142,8 +142,12 @@ target/debug/personhog-test-harness gate --routers 3 --leaders 3 --duration 18s--router-kill-after 4s --shutdown-after 8s --kill-handoff-target```-Verification still waits for convergence (bounded at 90s) before asserting strong reads; red here means convergence itself failed.-Remaining scope: draining pods should be excluded as rebalance targets (now mere churn rather than a black hole — a mid-drain rebalance can hand partitions to a pod that immediately re-drains them), and one stuck handoff should not defer all rebalancing.+Verification still waits for convergence (bounded at 30s — 2x the slow-crash TTL chain, the slowest legitimate recovery) before asserting strong reads; red here means convergence itself failed.+The two follow-ups once listed here are resolved: draining pods were never actually rebalance targets (`active_pod_names` has filtered to `Ready` pods since the original PoC — the earlier claim misread the wedge, whose real mechanism was the shutdown ordering fixed above), and a stuck handoff now defers only its own partition (the coordinator pins in-flight partitions and rebalances the rest — see `plan_partial_rebalance`).++**Follow-up: the guarded rebalance transaction has a partition-count budget.**+Plan application guards every handoff with two etcd compares (handoff-key absence + assignment precondition), and etcd's default `--max-txn-ops` of 128 caps the compare list — so a full-fleet plan (bootstrap, mass failover) fits in one transaction only up to 64 partitions; beyond that etcd rejects it with a hard error, not a guard failure.+Every environment today runs well under the bound, but it must be resolved as part of choosing the prod partition count: either an explicitly-set shared chart value rendered into both etcd's `--max-txn-ops` and a coordinator plan budget (so the two validate against each other), or chunked plan application — which must not ship without stateright coverage of partial application and harness scenarios at that scale.**Follow-up: coalesce changelog recovery fetches if the pool ever queues.**Recoveries check out one pooled consumer per person, so N concurrent misses on genuinely-behind persons cost N sequential Kafka point-reads once the pool saturates.diff --git a/rust/personhog-test-harness/src/scenarios/gate.rs b/rust/personhog-test-harness/src/scenarios/gate.rsindex e2781a3e0b4b..a26752580438 100644--- a/rust/personhog-test-harness/src/scenarios/gate.rs+++ b/rust/personhog-test-harness/src/scenarios/gate.rs@@ -296,13 +296,21 @@ pub async fn run(args: GateArgs) -> Result<()> {let prober_violations = probers.await.context("prober task panicked")??;// Verification asserts data visibility on a converged topology, not- // recovery speed: chaos legitimately leaves handoffs to re-drive, and- // the protocol's convergence is bounded (worst known case ~40s via the- // drained pod's lifecycle timeout). An already-settled run waits zero- // time; a run that cannot converge fails here with the stuck state.+ // recovery speed: chaos legitimately leaves handoffs to re-drive. The+ // slowest legitimate recoveries can serialize: a leader kill with+ // --kill-fast false is blind until the leader lease expires (30s+ // default), and a concurrent slow router crash appends the election+ // TTL + campaign retry + registration TTL chain (~16s) — so the+ // deadline stretches with the configured leader TTL plus that chain+ // with margin, floored at 30s. A regression toward the old+ // multi-tens-of-seconds wedges still fails loudly. An already-settled+ // run waits zero time; a run that cannot converge fails here with the+ // stuck state.if let Some(stack) = stack.as_mut() {+ let convergence_deadline =+ Duration::from_secs(30).max(Duration::from_secs(args.leader_lease_ttl as u64 + 30));let settled = stack- .wait_converged(Duration::from_secs(90))+ .wait_converged(convergence_deadline).await.context("coordination must converge before verification")?;println!(