: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
feat(personhog): rollout-aware partition placement during deployment rollouts (#82575)
José Sequeira56d0cfb81796
diff --git a/rust/common/assignment-coordination/src/strategy/mod.rs b/rust/common/assignment-coordination/src/strategy/mod.rsindex f41def6e393e..e52fb0ffec27 100644--- a/rust/common/assignment-coordination/src/strategy/mod.rs+++ b/rust/common/assignment-coordination/src/strategy/mod.rs@@ -4,6 +4,60 @@ pub use sticky_balanced::StickyBalancedStrategy;use std::collections::HashMap;+/// How a strategy may place partitions on a member.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum PlacementPolicy {+ /// Keeps existing assignments and receives new placements. When `cap`+ /// is set, the member's total partition count is bounded by it: during+ /// a Deployment rollout each new-generation pod is capped at its final+ /// share, so the first pod of the new generation is never handed the+ /// whole partition space.+ Active { cap: Option<u32> },+ /// Keeps existing assignments but receives new placements only when no+ /// capped active member has room, and sheds partitions to capped+ /// active members below their cap. Old-generation Ready pods hold+ /// during a Deployment rollout: they are alive and serving, but every+ /// partition they can shed belongs on the incoming generation.+ Hold,+}++/// A member eligible to own partitions, tagged with the placement policy+/// the caller derived for it (e.g. from K8s rollout state).+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Member {+ pub name: String,+ pub policy: PlacementPolicy,+}++impl Member {+ pub fn active(name: impl Into<String>) -> Self {+ Self {+ name: name.into(),+ policy: PlacementPolicy::Active { cap: None },+ }+ }++ pub fn active_capped(name: impl Into<String>, cap: u32) -> Self {+ Self {+ name: name.into(),+ policy: PlacementPolicy::Active { cap: Some(cap) },+ }+ }++ pub fn hold(name: impl Into<String>) -> Self {+ Self {+ name: name.into(),+ policy: PlacementPolicy::Hold,+ }+ }++ /// Wrap plain member names as uncapped active members — the shape for+ /// callers with no rollout signal, which is the pre-policy behavior.+ pub fn active_all<S: AsRef<str>>(names: &[S]) -> Vec<Member> {+ names.iter().map(|n| Member::active(n.as_ref())).collect()+ }+}+/// Trait for partition assignment strategies.////// The coordinator calls `compute_assignments` whenever the set of active@@ -14,12 +68,12 @@ pub trait AssignmentStrategy: Send + Sync {/// Compute the desired partition-to-member mapping.////// - `current`: existing partition -> member_name mapping (empty on first run)- /// - `active_members`: sorted list of member names eligible for assignment+ /// - `members`: members eligible for assignment, with placement policies/// - `num_partitions`: total number of partitions to distributefn compute_assignments(&self,current: &HashMap<u32, String>,- active_members: &[String],+ members: &[Member],num_partitions: u32,) -> HashMap<u32, String>;}diff --git a/rust/common/assignment-coordination/src/strategy/sticky_balanced.rs b/rust/common/assignment-coordination/src/strategy/sticky_balanced.rsindex 102ee3fbccd6..baee02f97eae 100644--- a/rust/common/assignment-coordination/src/strategy/sticky_balanced.rs+++ b/rust/common/assignment-coordination/src/strategy/sticky_balanced.rs@@ -1,112 +1,289 @@use std::collections::{HashMap, HashSet};-use super::AssignmentStrategy;+use super::{AssignmentStrategy, Member, PlacementPolicy};/// Assigns partitions while minimizing movement from the current state.///-/// Keeps all existing assignments where the owning member is still active,-/// then redistributes orphaned and unassigned partitions to maintain balance-/// (each member gets within +/-1 of the ideal count). When a new member-/// joins with zero partitions, steals from the most-loaded members to-/// rebalance.+/// With only uncapped active members, keeps all existing assignments where+/// the owning member is still active, then redistributes orphaned and+/// unassigned partitions to maintain balance (each member gets within +/-1+/// of the ideal count). When a new member joins with zero partitions,+/// steals from the most-loaded members to rebalance.+///+/// When any member carries a cap or a Hold policy (a Deployment rollout in+/// progress), placement switches to quota mode: capped members fill to+/// their cap — from orphaned partitions first, then by stealing from Hold+/// members — while Hold members keep whatever they cannot shed and absorb+/// overflow only when no capped member has room.pub struct StickyBalancedStrategy;impl AssignmentStrategy for StickyBalancedStrategy {fn compute_assignments(&self,current: &HashMap<u32, String>,- active_members: &[String],+ members: &[Member],num_partitions: u32,) -> HashMap<u32, String> {- if active_members.is_empty() {+ if members.is_empty() {return HashMap::new();}- let active_set: HashSet<&String> = active_members.iter().collect();- let num_members = active_members.len();- let target_min = num_partitions as usize / num_members;- let extra = num_partitions as usize % num_members;-- // Step 1: Keep valid assignments- let mut assignments: HashMap<u32, String> = current+ let plain = members.iter()- .filter(|(p, member)| **p < num_partitions && active_set.contains(member))- .map(|(p, member)| (*p, member.clone()))- .collect();+ .all(|m| m.policy == PlacementPolicy::Active { cap: None });+ if plain {+ balanced_assignments(current, members, num_partitions)+ } else {+ quota_assignments(current, members, num_partitions)+ }+ }+}- // Step 2: Build per-member partition lists- let mut member_partitions: HashMap<&String, Vec<u32>> =- active_members.iter().map(|m| (m, Vec::new())).collect();- for (partition, member) in &assignments {- if let Some(parts) = member_partitions.get_mut(member) {- parts.push(*partition);- }+/// The classic sticky-balanced algorithm: every member keeps what it has,+/// then targets are evened out to within +/-1 of the ideal count.+fn balanced_assignments(+ current: &HashMap<u32, String>,+ members: &[Member],+ num_partitions: u32,+) -> HashMap<u32, String> {+ let active_set: HashSet<&str> = members.iter().map(|m| m.name.as_str()).collect();+ let num_members = members.len();+ let target_min = num_partitions as usize / num_members;+ let extra = num_partitions as usize % num_members;++ // Step 1: Keep valid assignments+ let mut assignments: HashMap<u32, String> = current+ .iter()+ .filter(|(p, member)| **p < num_partitions && active_set.contains(member.as_str()))+ .map(|(p, member)| (*p, member.clone()))+ .collect();++ // Step 2: Build per-member partition lists+ let mut member_partitions: HashMap<&str, Vec<u32>> = members+ .iter()+ .map(|m| (m.name.as_str(), Vec::new()))+ .collect();+ for (partition, member) in &assignments {+ if let Some(parts) = member_partitions.get_mut(member.as_str()) {+ parts.push(*partition);}+ }- // Step 3: Collect unassigned partitions- let mut pool: Vec<u32> = (0..num_partitions)- .filter(|p| !assignments.contains_key(p))- .collect();+ // Step 3: Collect unassigned partitions+ let mut pool: Vec<u32> = (0..num_partitions)+ .filter(|p| !assignments.contains_key(p))+ .collect();- // Determine which members get target_min + 1 vs target_min.- // Members that already have more partitions get priority for the +1- // slot, to minimize movement.- let mut members_sorted: Vec<&String> = active_members.iter().collect();- members_sorted.sort_by(|a, b| {- let count_a = member_partitions.get(a).map_or(0, |v| v.len());- let count_b = member_partitions.get(b).map_or(0, |v| v.len());- count_b.cmp(&count_a)- });-- let mut member_targets: HashMap<&String, usize> = HashMap::new();- for (i, member) in members_sorted.iter().enumerate() {- let target = if i < extra {- target_min + 1- } else {- target_min- };- member_targets.insert(member, target);- }-- // Step 4: Strip excess from overloaded members- for member in &members_sorted {- let target = member_targets[member];- let parts = member_partitions.get_mut(member).unwrap();- if parts.len() > target {- parts.sort();- let excess: Vec<u32> = parts.drain(target..).collect();- for p in &excess {- assignments.remove(p);- }- pool.extend(excess);+ // Determine which members get target_min + 1 vs target_min.+ // Members that already have more partitions get priority for the +1+ // slot, to minimize movement.+ let mut members_sorted: Vec<&str> = members.iter().map(|m| m.name.as_str()).collect();+ members_sorted.sort_by(|a, b| {+ let count_a = member_partitions.get(a).map_or(0, |v| v.len());+ let count_b = member_partitions.get(b).map_or(0, |v| v.len());+ count_b.cmp(&count_a)+ });++ let mut member_targets: HashMap<&str, usize> = HashMap::new();+ for (i, member) in members_sorted.iter().enumerate() {+ let target = if i < extra {+ target_min + 1+ } else {+ target_min+ };+ member_targets.insert(member, target);+ }++ // Step 4: Strip excess from overloaded members+ for member in &members_sorted {+ let target = member_targets[member];+ let parts = member_partitions.get_mut(member).unwrap();+ if parts.len() > target {+ parts.sort();+ let excess: Vec<u32> = parts.drain(target..).collect();+ for p in &excess {+ assignments.remove(p);}+ pool.extend(excess);}+ }- // Step 5: Fill underloaded members from the pool (emptiest first)- pool.sort();- let mut pool_iter = pool.into_iter();- members_sorted.reverse();- for member in &members_sorted {- let target = member_targets[member];- let parts = member_partitions.get_mut(member).unwrap();- while parts.len() < target {- if let Some(partition) = pool_iter.next() {- parts.push(partition);- assignments.insert(partition, (*member).clone());- } else {- break;- }+ // Step 5: Fill underloaded members from the pool (emptiest first)+ pool.sort();+ let mut pool_iter = pool.into_iter();+ members_sorted.reverse();+ for member in &members_sorted {+ let target = member_targets[member];+ let parts = member_partitions.get_mut(member).unwrap();+ while parts.len() < target {+ if let Some(partition) = pool_iter.next() {+ parts.push(partition);+ assignments.insert(partition, (*member).to_string());+ } else {+ break;}}+ }++ assignments+}++/// Rollout placement: capped active members fill to their cap, Hold+/// members shed toward them and absorb only what nobody else can take.+///+/// A cap alone never forces shedding — a member above its cap keeps its+/// partitions unless a capped sibling sits below cap, in which case the+/// excess levels toward that sibling. With everyone at or above cap,+/// over-cap members simply receive nothing new.+///+/// Most partitions move once, straight to their final owner, but not+/// all: orphans that overflow onto Hold members (phase 3, when no capped+/// member has room) move again when capacity appears, and ceil-rounded+/// caps can leave the final post-transition balance one leveling move+/// away. Both are the cost of assigning every partition an owner at+/// every step.+fn quota_assignments(+ current: &HashMap<u32, String>,+ members: &[Member],+ num_partitions: u32,+) -> HashMap<u32, String> {+ let member_set: HashSet<&str> = members.iter().map(|m| m.name.as_str()).collect();++ // Keep valid assignments for every listed member, Hold included.+ let mut assignments: HashMap<u32, String> = current+ .iter()+ .filter(|(p, member)| **p < num_partitions && member_set.contains(member.as_str()))+ .map(|(p, member)| (*p, member.clone()))+ .collect();++ let mut owned: HashMap<&str, Vec<u32>> = members+ .iter()+ .map(|m| (m.name.as_str(), Vec::new()))+ .collect();+ for (partition, member) in &assignments {+ if let Some(parts) = owned.get_mut(member.as_str()) {+ parts.push(*partition);+ }+ }+ for parts in owned.values_mut() {+ parts.sort();+ }++ let mut pool: Vec<u32> = (0..num_partitions)+ .filter(|p| !assignments.contains_key(p))+ .collect();+ pool.sort();+ pool.reverse(); // pop() yields the lowest partition first++ // Name-sorted views for deterministic tie-breaking.+ let mut actives: Vec<(&str, Option<u32>)> = members+ .iter()+ .filter_map(|m| match m.policy {+ PlacementPolicy::Active { cap } => Some((m.name.as_str(), cap)),+ PlacementPolicy::Hold => None,+ })+ .collect();+ actives.sort();+ let mut holds: Vec<&str> = members+ .iter()+ .filter(|m| m.policy == PlacementPolicy::Hold)+ .map(|m| m.name.as_str())+ .collect();+ holds.sort();++ let has_room = |name: &str, cap: Option<u32>, owned: &HashMap<&str, Vec<u32>>| -> bool {+ match cap {+ Some(cap) => (owned[name].len() as u32) < cap,+ None => true,+ }+ };- assignments+ // Phase 1: fill active members from the pool, emptiest first.+ while !pool.is_empty() {+ let Some(&(name, _)) = actives+ .iter()+ .filter(|&&(n, cap)| has_room(n, cap, &owned))+ .min_by_key(|&&(n, _)| owned[n].len())+ else {+ break;+ };+ let partition = pool.pop().unwrap();+ owned.get_mut(name).unwrap().push(partition);+ assignments.insert(partition, name.to_string());+ }++ // Phase 2: capped active members below cap steal — from Hold members+ // first (the departing generation sheds before anything levels), then+ // from actives above their own cap, which phase 4 forcing and cap+ // shrinks create: without that second donor pool a member rejoining+ // after a crash starves at zero while its siblings sit over cap.+ // Uncapped members never steal — without a cap there is no bound on+ // how much they would strip from holders.+ loop {+ let Some(&(recipient, _)) = actives+ .iter()+ .filter(|&&(n, cap)| cap.is_some() && has_room(n, cap, &owned))+ .min_by_key(|&&(n, _)| owned[n].len())+ else {+ break;+ };+ let donor = holds+ .iter()+ .filter(|n| !owned[*n].is_empty())+ .max_by_key(|n| owned[*n].len())+ .copied()+ .or_else(|| {+ actives+ .iter()+ .filter(|&&(n, cap)| matches!(cap, Some(c) if owned[n].len() as u32 > c))+ .max_by_key(|&&(n, _)| owned[n].len())+ .map(|&(n, _)| n)+ });+ let Some(donor) = donor else {+ break;+ };+ let partition = owned.get_mut(donor).unwrap().pop().unwrap();+ owned.get_mut(recipient).unwrap().push(partition);+ assignments.insert(partition, recipient.to_string());}++ // Phase 3: leftover pool (every capped member full) goes to Hold+ // members, emptiest first — better a doomed owner than no owner.+ while !pool.is_empty() {+ let Some(&name) = holds.iter().min_by_key(|n| owned[*n].len()) else {+ break;+ };+ let partition = pool.pop().unwrap();+ owned.get_mut(name).unwrap().push(partition);+ assignments.insert(partition, name.to_string());+ }++ // Phase 4: still leftover (no holds at all) — force onto active+ // members past their caps; every partition must have an owner.+ while let Some(partition) = pool.pop() {+ let &(name, _) = actives+ .iter()+ .min_by_key(|&&(n, _)| owned[n].len())+ .expect("members is non-empty and holds is empty, so actives is non-empty");+ owned.get_mut(name).unwrap().push(partition);+ assignments.insert(partition, name.to_string());+ }++ assignments}#[cfg(test)]mod tests {use super::*;+ fn active_members(names: &[&str]) -> Vec<Member> {+ names.iter().map(|n| Member::active(*n)).collect()+ }++ fn counts(result: &HashMap<u32, String>, member: &str) -> usize {+ result.values().filter(|v| v.as_str() == member).count()+ }+#[test]fn empty_members() {let strategy = StickyBalancedStrategy;@@ -117,33 +294,29 @@ mod tests {#[test]fn initial_assignment_balanced() {let strategy = StickyBalancedStrategy;- let members = vec!["m-0".to_string(), "m-1".to_string(), "m-2".to_string()];+ let members = active_members(&["m-0", "m-1", "m-2"]);let result = strategy.compute_assignments(&HashMap::new(), &members, 12);assert_eq!(result.len(), 12);for m in &members {- let count = result.values().filter(|v| *v == m).count();- assert_eq!(count, 4, "{m} should own 4 partitions");+ assert_eq!(counts(&result, &m.name), 4, "{} should own 4", m.name);}}#[test]fn initial_assignment_uneven() {let strategy = StickyBalancedStrategy;- let members = vec!["m-0".to_string(), "m-1".to_string(), "m-2".to_string()];+ let members = active_members(&["m-0", "m-1", "m-2"]);let result = strategy.compute_assignments(&HashMap::new(), &members, 10);assert_eq!(result.len(), 10);- let mut counts: Vec<usize> = members- .iter()- .map(|m| result.values().filter(|v| *v == m).count())- .collect();- counts.sort();- assert_eq!(counts, vec![3, 3, 4]);+ let mut c: Vec<usize> = members.iter().map(|m| counts(&result, &m.name)).collect();+ c.sort();+ assert_eq!(c, vec![3, 3, 4]);}#[test]fn keeps_existing_assignments() {let strategy = StickyBalancedStrategy;- let members = vec!["m-0".to_string(), "m-1".to_string()];+ let members = active_members(&["m-0", "m-1"]);let mut current = HashMap::new();for p in 0..8 {current.insert(p, "m-0".to_string());@@ -165,12 +338,11 @@ mod tests {for p in 6..12 {current.insert(p, "m-1".to_string());}- let members = vec!["m-0".to_string(), "m-1".to_string(), "m-2".to_string()];+ let members = active_members(&["m-0", "m-1", "m-2"]);let result = strategy.compute_assignments(¤t, &members, 12);assert_eq!(result.len(), 12);for m in &members {- let count = result.values().filter(|v| *v == m).count();- assert_eq!(count, 4, "{m} should own 4 partitions");+ assert_eq!(counts(&result, &m.name), 4, "{} should own 4", m.name);}let moved = (0..12u32).filter(|p| current.get(p) != result.get(p))@@ -191,12 +363,11 @@ mod tests {for p in 8..12 {current.insert(p, "m-2".to_string());}- let members = vec!["m-0".to_string(), "m-2".to_string()];+ let members = active_members(&["m-0", "m-2"]);let result = strategy.compute_assignments(¤t, &members, 12);assert_eq!(result.len(), 12);for m in &members {- let count = result.values().filter(|v| *v == m).count();- assert_eq!(count, 6, "{m} should own 6 partitions");+ assert_eq!(counts(&result, &m.name), 6, "{} should own 6", m.name);}for p in 0..4 {assert_eq!(result[&p], "m-0");@@ -209,7 +380,7 @@ mod tests {#[test]fn single_member() {let strategy = StickyBalancedStrategy;- let members = vec!["m-0".to_string()];+ let members = active_members(&["m-0"]);let result = strategy.compute_assignments(&HashMap::new(), &members, 8);assert_eq!(result.len(), 8);for owner in result.values() {@@ -223,10 +394,240 @@ mod tests {let mut current = HashMap::new();current.insert(0, "dead".to_string());current.insert(1, "m-0".to_string());- let members = vec!["m-0".to_string()];+ let members = active_members(&["m-0"]);let result = strategy.compute_assignments(¤t, &members, 2);assert_eq!(result.len(), 2);assert_eq!(result[&0], "m-0");assert_eq!(result[&1], "m-0");}++ // ── Quota mode (Deployment rollout) ─────────────────────────────++ /// The whole partition space is on Hold members; the first+ /// new-generation pod pulls exactly its cap, never everything.+ #[test]+ fn first_new_member_capped_at_quota() {+ let strategy = StickyBalancedStrategy;+ let mut current = HashMap::new();+ for p in 0..12 {+ current.insert(p, format!("old-{}", p / 4));+ }+ let members = vec![+ Member::hold("old-0"),+ Member::hold("old-1"),+ Member::hold("old-2"),+ Member::active_capped("new-0", 4),+ ];+ let result = strategy.compute_assignments(¤t, &members, 12);+ assert_eq!(result.len(), 12);+ assert_eq!(counts(&result, "new-0"), 4);+ assert_eq!(+ counts(&result, "old-0") + counts(&result, "old-1") + counts(&result, "old-2"),+ 8+ );+ }++ /// A drained pod's orphans land on the below-cap new member; Hold+ /// members' assignments are untouched.+ #[test]+ fn orphans_go_to_new_gen_before_holds() {+ let strategy = StickyBalancedStrategy;+ let mut current = HashMap::new();+ // old-drained (not a member anymore) owned 0..4+ for p in 0..4 {+ current.insert(p, "old-drained".to_string());+ }+ for p in 4..8 {+ current.insert(p, "old-0".to_string());+ }+ for p in 8..12 {+ current.insert(p, "old-1".to_string());+ }+ let members = vec![+ Member::hold("old-0"),+ Member::hold("old-1"),+ Member::active_capped("new-0", 4),+ ];+ let result = strategy.compute_assignments(¤t, &members, 12);+ for p in 0..4 {+ assert_eq!(result[&p], "new-0");+ }+ for p in 4..8 {+ assert_eq!(result[&p], "old-0");+ }+ for p in 8..12 {+ assert_eq!(result[&p], "old-1");+ }+ }++ /// More orphans than new-generation capacity: overflow spreads over+ /// Hold members instead of blowing past the cap.+ #[test]+ fn overflow_spreads_to_holds_when_new_gen_full() {+ let strategy = StickyBalancedStrategy;+ let mut current = HashMap::new();+ for p in 8..12 {+ current.insert(p, "old-0".to_string());+ }+ let members = vec![+ Member::hold("old-0"),+ Member::hold("old-1"),+ Member::active_capped("new-0", 4),+ ];+ // 0..8 are orphans; new-0 caps at 4, so 4 overflow to holds.+ let result = strategy.compute_assignments(¤t, &members, 12);+ assert_eq!(result.len(), 12);+ assert_eq!(counts(&result, "new-0"), 4);+ // old-0 keeps its 4 and the emptier old-1 absorbs the overflow.+ assert_eq!(counts(&result, "old-0"), 4);+ assert_eq!(counts(&result, "old-1"), 4);+ }++ /// With no orphan pool, a capped new member pre-drains the fullest+ /// Hold members up to its cap.+ #[test]+ fn steals_from_fullest_hold_members() {+ let strategy = StickyBalancedStrategy;+ let mut current = HashMap::new();+ for p in 0..6 {+ current.insert(p, "old-0".to_string());+ }+ for p in 6..8 {+ current.insert(p, "old-1".to_string());+ }+ let members = vec![+ Member::hold("old-0"),+ Member::hold("old-1"),+ Member::active_capped("new-0", 4),+ ];+ let result = strategy.compute_assignments(¤t, &members, 8);+ assert_eq!(counts(&result, "new-0"), 4);+ // Fullest-first stealing drains old-0 toward old-1's level.+ assert_eq!(counts(&result, "old-0"), 2);+ assert_eq!(counts(&result, "old-1"), 2);+ }++ /// Caps under-provision the space and there are no Hold members:+ /// every partition still gets an owner.+ #[test]+ fn forces_assignment_past_caps_without_holds() {+ let strategy = StickyBalancedStrategy;+ let members = vec![+ Member::active_capped("new-0", 2),+ Member::active_capped("new-1", 2),+ ];+ let result = strategy.compute_assignments(&HashMap::new(), &members, 8);+ assert_eq!(result.len(), 8);+ assert_eq!(counts(&result, "new-0"), 4);+ assert_eq!(counts(&result, "new-1"), 4);+ }++ /// A ten-pod fleet rolls two by two, drain-led: each wave two old+ /// pods drain out and two new pods register at their final cap.+ /// The orphan pool exactly covers the fresh pods' capacity, so+ /// phase 1 absorbs it before any stealing: surviving old pods and+ /// already-placed new pods keep their exact partitions, and every+ /// partition moves exactly once, straight from a dying pod to its+ /// final owner. (Surge ordering — new pods registering before old+ /// ones drain — instead pre-drains surviving holds; still one move+ /// per partition, but not only the dying pods'.)+ #[test]+ fn wave_rollout_moves_only_the_dying_pods_partitions() {+ let strategy = StickyBalancedStrategy;+ let total: u32 = 20;+ let cap = 2u32; // 20 partitions over 10 desired replicas++ let mut assignments: HashMap<u32, String> = (0..total)+ .map(|p| (p, format!("old-{}", p / cap)))+ .collect();+ let mut moves_per_partition: HashMap<u32, u32> = HashMap::new();++ for wave in 0..5u32 {+ let dying: Vec<String> = (2 * wave..2 * wave + 2)+ .map(|i| format!("old-{i}"))+ .collect();+ let dying_partitions: HashSet<u32> = assignments+ .iter()+ .filter(|(_, owner)| dying.contains(owner))+ .map(|(p, _)| *p)+ .collect();++ let mut members: Vec<Member> = (2 * wave + 2..10)+ .map(|i| Member::hold(format!("old-{i}")))+ .collect();+ members+ .extend((0..2 * wave + 2).map(|i| Member::active_capped(format!("new-{i}"), cap)));++ let next = strategy.compute_assignments(&assignments, &members, total);+ assert_eq!(next.len(), total as usize);++ for (partition, owner) in &next {+ let previous = &assignments[partition];+ if owner != previous {+ assert!(+ dying_partitions.contains(partition),+ "wave {wave}: partition {partition} moved {previous} -> {owner} but its owner was not dying"+ );+ *moves_per_partition.entry(*partition).or_insert(0) += 1;+ }+ }+ assignments = next;+ }++ for pod in 0..10 {+ assert_eq!(+ assignments+ .values()+ .filter(|o| **o == format!("new-{pod}"))+ .count(),+ cap as usize+ );+ }+ assert_eq!(moves_per_partition.len(), total as usize);+ assert!(moves_per_partition.values().all(|moves| *moves == 1));+ }++ /// A capped member rejoining after a crash is leveled from siblings+ /// sitting above cap: with no Hold donors and no orphan pool,+ /// nothing else can feed it. (Over-cap siblings are what phase 4+ /// forcing leaves behind when the rejoiner was down.)+ #[test]+ fn below_cap_member_steals_from_over_cap_siblings() {+ let strategy = StickyBalancedStrategy;+ let mut current = HashMap::new();+ for p in 0..4 {+ current.insert(p, "new-0".to_string());+ }+ for p in 4..8 {+ current.insert(p, "new-1".to_string());+ }+ let members = vec![+ Member::active_capped("new-0", 3),+ Member::active_capped("new-1", 3),+ Member::active_capped("new-2", 3),+ ];+ let result = strategy.compute_assignments(¤t, &members, 8);+ assert_eq!(result.len(), 8);+ assert_eq!(counts(&result, "new-0"), 3);+ assert_eq!(counts(&result, "new-1"), 3);+ assert_eq!(counts(&result, "new-2"), 2);+ }++ /// A member already above a shrunken cap keeps its partitions — the+ /// cap gates new placements, it never forces shedding.+ #[test]+ fn over_cap_member_keeps_assignments() {+ let strategy = StickyBalancedStrategy;+ let mut current = HashMap::new();+ for p in 0..6 {+ current.insert(p, "new-0".to_string());+ }+ let members = vec![Member::active_capped("new-0", 4), Member::hold("old-0")];+ // 6..8 are orphans; new-0 is over cap so they land on the hold.+ let result = strategy.compute_assignments(¤t, &members, 8);+ for p in 0..6 {+ assert_eq!(result[&p], "new-0");+ }+ assert_eq!(counts(&result, "old-0"), 2);+ }}diff --git a/rust/common/k8s-awareness/src/watcher.rs b/rust/common/k8s-awareness/src/watcher.rsindex 5c954d93214d..1f68e9a6c308 100644--- a/rust/common/k8s-awareness/src/watcher.rs+++ b/rust/common/k8s-awareness/src/watcher.rs@@ -71,14 +71,41 @@ impl K8sAwareness {/// rather than pod-name discovery (the coordinator sees each pod's/// self-reported controller ref and has no pod of its own to/// discover from). Idempotent: an already-watched controller is a- /// no-op.+ /// no-op. Returns whether this call started a new watch, so callers+ /// that need intent can bound-wait for the first report instead of+ /// planning without it.pub async fn watch_controller(&self,controller: &ControllerRef,- ) -> Result<(), K8sAwarenessError> {+ ) -> Result<bool, K8sAwarenessError> {self.ensure_watching(controller).await}+ /// Like [`Self::cluster_intent`], but polls up to `deadline` for a+ /// just-started watcher's first report. A freshly elected+ /// coordinator's first evaluation otherwise plans deterministically+ /// without intent — and mid-rollout, planning without placement+ /// policies means a balanced plan that moves partitions the rollout+ /// has already placed. `None` after the deadline (API server down,+ /// or controller genuinely unwatched) degrades exactly like+ /// [`Self::cluster_intent`] returning `None`.+ pub async fn cluster_intent_within(+ &self,+ controller: &ControllerRef,+ deadline: Duration,+ ) -> Option<ClusterIntent> {+ let start = tokio::time::Instant::now();+ loop {+ if let Some(intent) = self.cluster_intent(controller).await {+ return Some(intent);+ }+ if start.elapsed() >= deadline {+ return None;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ }+/// Classify why a member is departing based on its controller's current intent.////// Returns `DepartureReason::Unknown` if the controller isn't being watched@@ -109,11 +136,25 @@ impl K8sAwareness {}}- /// Start watching a controller if not already watching.- async fn ensure_watching(&self, controller: &ControllerRef) -> Result<(), K8sAwarenessError> {+ /// The watcher's current view of a controller's intent, if watched.+ ///+ /// Returns `None` when the controller isn't being watched or hasn't+ /// reported yet — callers must treat that as "no rollout signal" and+ /// fall back to policy-free behavior. Waits for the lock (writers+ /// hold it only for map updates): a `try_read` here would blank the+ /// intent under contention, and a blanked intent flips a whole+ /// rollout's placement policies to plain balancing for that+ /// evaluation, churning partitions in both directions.+ pub async fn cluster_intent(&self, controller: &ControllerRef) -> Option<ClusterIntent> {+ self.controllers.read().await.get(controller).cloned()+ }++ /// Start watching a controller if not already watching. Returns+ /// whether a new watch was started.+ async fn ensure_watching(&self, controller: &ControllerRef) -> Result<bool, K8sAwarenessError> {let mut watching = self.watching.write().await;if watching.contains_key(controller) {- return Ok(());+ return Ok(false);}let child_cancel = self.cancel.child_token();@@ -155,7 +196,7 @@ impl K8sAwareness {}});- Ok(())+ Ok(true)}}@@ -255,7 +296,12 @@ async fn handle_deployment_event(let desired_replicas = spec.replicas.unwrap_or(1) as u32;let generation = deploy.metadata.generation.unwrap_or(0);let observed_generation = status.and_then(|s| s.observed_generation).unwrap_or(0);- let rollout_in_progress = generation != observed_generation;+ // observedGeneration catches up seconds after a spec change, long+ // before pods actually roll — on its own it only covers the window+ // until the new ReplicaSet exists. The rollout itself is in progress+ // for as long as more than one generation has desired replicas, which+ // is judged below once the ReplicaSets are listed.+ let spec_pending = generation != observed_generation;// Build a label selector from the Deployment's matchLabels to scope RS querieslet label_selector = spec@@ -280,7 +326,7 @@ async fn handle_deployment_event(let rses = match owned_rses {Ok(rses) => rses,Err(e) => {- if rollout_in_progress {+ if spec_pending {warn!(controller = %controller,error = %e,@@ -297,6 +343,9 @@ async fn handle_deployment_event(}};+ let live_generations = rses.iter().filter(|(_, _, replicas)| *replicas > 0).count();+ let rollout_in_progress = spec_pending || live_generations > 1;+let (current_gen, target_gen) = if rollout_in_progress {let target = rses.first()diff --git a/rust/kafka-assigner/src/assigner.rs b/rust/kafka-assigner/src/assigner.rsindex ba1d20115b7b..56a3de9bc382 100644--- a/rust/kafka-assigner/src/assigner.rs+++ b/rust/kafka-assigner/src/assigner.rs@@ -7,7 +7,7 @@ use tokio::sync::Mutex;use tokio_util::sync::CancellationToken;use assignment_coordination::leader_election::{self, LeaderElectionConfig};-use assignment_coordination::strategy::AssignmentStrategy;+use assignment_coordination::strategy::{AssignmentStrategy, Member};use assignment_coordination::util;use k8s_awareness::types::ControllerKind;use k8s_awareness::{DepartureReason, K8sAwareness};@@ -443,6 +443,7 @@ impl Assigner {// Use registered set for liveness: a Draining consumer is alive and// needs the handoff protocol, not a direct reassignment.let registered_set: HashSet<&str> = registered.iter().map(|s| s.as_str()).collect();+ let members = Member::active_all(&ready_consumers);for config in &topic_configs {let current_assignments = store.list_assignments_for_topic(&config.topic).await?;@@ -451,11 +452,8 @@ impl Assigner {.map(|a| (a.partition, a.owner.clone())).collect();- let desired = strategy.compute_assignments(- ¤t_map,- &ready_consumers,- config.partition_count,- );+ let desired =+ strategy.compute_assignments(¤t_map, &members, config.partition_count);let moves = util::compute_required_handoffs(¤t_map, &desired);if !moves.is_empty() || current_map.len() != desired.len() {diff --git a/rust/kafka-assigner/src/strategy/mod.rs b/rust/kafka-assigner/src/strategy/mod.rsindex abe093e568ae..035606c948e9 100644--- a/rust/kafka-assigner/src/strategy/mod.rs+++ b/rust/kafka-assigner/src/strategy/mod.rs@@ -1 +1,3 @@-pub use assignment_coordination::strategy::{AssignmentStrategy, StickyBalancedStrategy};+pub use assignment_coordination::strategy::{+ AssignmentStrategy, Member, PlacementPolicy, StickyBalancedStrategy,+};diff --git a/rust/kafka-assigner/tests/integration.rs b/rust/kafka-assigner/tests/integration.rsindex 13f72159bf62..42e82d508b00 100644--- a/rust/kafka-assigner/tests/integration.rs+++ b/rust/kafka-assigner/tests/integration.rs@@ -693,11 +693,12 @@ async fn rapid_scale_up_debounce() {.map(|a| (a.partition, a.owner.clone())).collect();let strategy = kafka_assigner::strategy::StickyBalancedStrategy;+ let members = kafka_assigner::strategy::Member::active_all(&names);let desired =assignment_coordination::strategy::AssignmentStrategy::compute_assignments(&strategy,¤t,- &names,+ &members,NUM_PARTITIONS,);let moves =diff --git a/rust/personhog-coordination/README.md b/rust/personhog-coordination/README.mdindex c6fd12735c93..34867b68804c 100644--- a/rust/personhog-coordination/README.md+++ b/rust/personhog-coordination/README.md@@ -94,6 +94,12 @@ Several failure modes are handled explicitly:- **A condemned producer heals in place.** An abort that did not land, or a commit whose outcome stayed unknown, leaves a producer no later window can be begun from. It is condemned and given up on the next write, which answers as unowned (`FailedPrecondition`, the router's bounce class) rather than as a retryable failure, and the serving-side verification re-acquires on the next convergence tick — gated on the authority stamp, which is what gives a pod the standing to bump the epoch.- **The drain commits its own window when it can.** A request cancelled mid-produce takes its handler — and the drain's in-flight count — with it, leaving the record it enqueued in a window nobody waits on; the drain waits (bounded, best-effort, never failing the drain) for that window to commit before acking, landing the cancelled write below the successor's cutoff. The successor's `init_transactions` aborts whatever could not settle — safe in either ordering, because the transaction coordinator serializes the in-flight commit against the successor's init on the shared transactional id.- **Writer progress is coupled to leader transaction liveness.** `read_committed` means the writer cannot advance past an open window: a leader that stops mid-window holds every `read_committed` consumer of that partition at the last stable offset until the broker abandons the transaction — bounded by the derived broker transaction timeout (about 6s at the production lease). The price of aborted windows never reaching Postgres.++**Rollout placement residuals** (`k8s_awareness_enabled`, default off). During a Deployment rollout the coordinator holds old-generation Ready pods and caps incoming pods at their final share, keyed on departing-generation registrations rather than the transient k8s rollout flag. Placement-behavior residuals, none affecting write safety (the handoff protocol is unchanged):++- **Some partitions move twice.** Orphans that overflow onto Hold members when no capped pod has room move again when capacity appears, and ceil-rounded caps can leave the final balance one leveling move away. The cost of every partition always having an owner.+- **Intent loss degrades to policy-free planning.** A Deployment deleted mid-rollout, a watcher stream dying between evaluations (stale intent until the lazy rewatch reports), or the k8s API being down all fall back to plain balanced placement — availability over placement. A freshly elected coordinator bound-waits (`FIRST_INTENT_WAIT`) for its first intent per controller, so failover mid-rollout does not plan policy-free unless the API server is actually unreachable.+- **A capped pod's in-flight steal counts against its cap before it lands.** Planning attributes pinned handoffs to their targets, so a capped member briefly under-fills while its steal is in flight; the next evaluation after completion levels it.- **With `KAFKA_TRANSACTIONAL_FENCING` off there is no settle equivalent.** Nothing forces a queued record to the broker before the drain acks, so it can land above the new owner's warm cutoff, and a later write for that person re-derives the same version — where the writer's first-wins guard keeps the record nobody acked and discards the one that was. The unfenced path is slated for removal once fencing proves out.**Assignment strategies are minimal**: The two bundled strategies (`JumpHashStrategy` and `StickyBalancedStrategy`) are basic implementations meant to exercise the coordination layer. `JumpHashStrategy` is stateless and deterministic but ignores current assignments entirely, causing unnecessary partition movement on every rebalance. `StickyBalancedStrategy` minimizes movement but uses a naive greedy approach without considering locality, rack awareness, or weighted pods. Both are placeholders to be replaced with a production-grade strategy as requirements become clearer.diff --git a/rust/personhog-coordination/src/coordinator.rs b/rust/personhog-coordination/src/coordinator.rsindex 283544259a66..8cfc98d357ab 100644--- a/rust/personhog-coordination/src/coordinator.rs+++ b/rust/personhog-coordination/src/coordinator.rs@@ -9,8 +9,8 @@ use tokio::sync::Notify;use tokio_util::sync::CancellationToken;use assignment_coordination::store::parse_watch_value;-use k8s_awareness::types::ControllerKind;-use k8s_awareness::{DepartureReason, K8sAwareness};+use k8s_awareness::types::{ControllerKind, ControllerRef};+use k8s_awareness::{classify_departure, ClusterIntent, DepartureReason, K8sAwareness};use crate::error::{Error, Result};use crate::protocol::{@@ -18,7 +18,7 @@ use crate::protocol::{plan_partial_rebalance, warm_satisfied,};use crate::store::{self, PersonhogStore};-use crate::strategy::AssignmentStrategy;+use crate::strategy::{AssignmentStrategy, Member, PlacementPolicy};use crate::types::{AssignmentPrecondition, HandoffPhase, HandoffReplacement, HandoffState, PodStatus,RegisteredPod, RegisteredRouter,@@ -837,12 +837,11 @@ impl Coordinator {Err(e) => return Err(e),};- let mut active_pods = active_pod_names(&pods);-- // K8s-aware pod filtering for smarter rebalancing- if let Some(k8s) = k8s_awareness {- active_pods = filter_pods_for_k8s(k8s, &pods, active_pods).await;- }+ // K8s-aware placement policies for smarter rebalancing+ let members = match k8s_awareness {+ Some(k8s) => members_for_k8s(k8s, &pods, total_partitions).await,+ None => Member::active_all(&active_pod_names(&pods)),+ };// Classify the in-flight handoffs. One whose new owner's// registration is gone can never advance (no WarmedAck will ever@@ -890,13 +889,8 @@ impl Coordinator {// model. Cancelled partitions are deliberately not pinned: the// plan is free to place them, and whatever it decides becomes// their replacement below.- let plan = plan_partial_rebalance(- strategy,- ¤t_map,- &pinned,- &active_pods,- total_partitions,- );+ let plan =+ plan_partial_rebalance(strategy, ¤t_map, &pinned, &members, total_partitions);if plan.handoffs.is_empty() && cancelled.is_empty() {tracing::debug!("no handoffs needed");@@ -1331,6 +1325,8 @@ fn record_cluster_gauges(handoffs: &[HandoffState], pods: &[RegisteredPod], rout/// coordinator's live values.fn reset_coordinator_gauges() {gauge!("personhog_coordination_is_coordinator").set(0.0);+ gauge!("personhog_coordination_generation_hold_pods").set(0.0);+ gauge!("personhog_coordination_generation_capped_pods").set(0.0);record_cluster_gauges(&[], &[], 0);}@@ -1346,80 +1342,195 @@ fn active_pod_names(pods: &[RegisteredPod]) -> Vec<String> {active.iter().map(|p| p.pod_name.clone()).collect()}-/// Adjust the active pod list based on K8s controller intent.+/// How long a first evaluation waits for a just-started controller+/// watch's initial intent (a healthy watch reports well under a second).+const FIRST_INTENT_WAIT: Duration = Duration::from_secs(3);++/// Derive assignment members and placement policies from pod+/// registrations and K8s controller intent.///+/// Outside a rollout every Ready pod is an uncapped active member./// Two adjustments during rollouts:///-/// 1. **Deployment rollout** — old-gen Ready pods are excluded from the-/// active list so the strategy never assigns partitions to them. Existing-/// assignments move to new-gen pods via handoff.+/// 1. **Deployment rollout** — old-gen Ready pods become Hold members:+/// they stay serving and keep their assignments, but shed toward the+/// incoming generation, whose Ready pods are capped at their final+/// share (`total_partitions / desired_replicas`) so the first new pod+/// up is never handed the whole partition space. Partitions actually+/// move when an old pod drains (drops out of the member list) or when+/// a below-cap new pod pre-drains a Hold member.///-/// 2. **StatefulSet rollout** — Draining pods are *added back* to the-/// active list so their assignments are held. In a StatefulSet rollout the-/// same pod name comes back with a new revision, so there's no point-/// handing off to a different pod.-async fn filter_pods_for_k8s(+/// 2. **StatefulSet rollout** — Draining pods are *kept* as members so+/// their assignments are held. In a StatefulSet rollout the same pod+/// name comes back with a new revision, so there's no point handing+/// off to a different pod.+async fn members_for_k8s(k8s: &K8sAwareness,pods: &[RegisteredPod],- mut active: Vec<String>,-) -> Vec<String> {+ total_partitions: u32,+) -> Vec<Member> {+ let mut intents: HashMap<ControllerRef, ClusterIntent> = HashMap::new();for pod in pods {- let (Some(controller), generation) = (&pod.controller, &pod.generation) else {+ let Some(controller) = pod.controller.as_ref() else {continue;};-- if generation.is_empty() {+ if pod.generation.is_empty() || intents.contains_key(controller) {continue;}-// Lazily start the controller watch from the registration's own// ref — the coordinator has no pod of its own to discover from,// and without a watch `classify_departure` has no intent to- // consult. Idempotent, so calling per evaluation is cheap; the- // first evaluation after a watch starts may still classify- // Unknown, which safely leaves the pod active until intent- // arrives.- if let Err(e) = k8s.watch_controller(controller).await {- tracing::warn!(- controller = %controller,- error = %e,- "failed to start controller watch; treating pod as active"- );- continue;+ // consult. Idempotent, so calling per evaluation is cheap.+ let newly_watched = match k8s.watch_controller(controller).await {+ Ok(newly_watched) => newly_watched,+ Err(e) => {+ tracing::warn!(+ controller = %controller,+ error = %e,+ "failed to start controller watch; using status-only policy"+ );+ continue;+ }+ };+ // A just-started watch reports no intent yet, and a freshly+ // elected coordinator would otherwise deterministically plan its+ // first evaluation policy-free — mid-rollout, that's a balanced+ // plan moving partitions the rollout already placed. Bound-wait+ // for the first report; on timeout (API server down) fall back+ // to status-only membership, availability over placement.+ let intent = if newly_watched {+ k8s.cluster_intent_within(controller, FIRST_INTENT_WAIT)+ .await+ } else {+ k8s.cluster_intent(controller).await+ };+ if let Some(intent) = intent {+ intents.insert(controller.clone(), intent);}+ }- let reason = k8s.classify_departure(controller, generation).await;-- match (&controller.kind, pod.status, reason) {- // Deployment rollout: old-gen Ready pod → exclude- (ControllerKind::Deployment, PodStatus::Ready, DepartureReason::Rollout) => {- tracing::info!(- pod = %pod.pod_name,- controller = %controller,- generation = %generation,- "excluding old-gen deployment pod from active list"+ let members = derive_members(pods, &intents, total_partitions);+ let mut holds = 0u64;+ let mut capped = 0u64;+ for member in &members {+ match member.policy {+ PlacementPolicy::Hold => {+ holds += 1;+ tracing::debug!(+ pod = %member.name,+ "holding old-gen deployment pod during generation transition");- active.retain(|name| name != &pod.pod_name);}- // StatefulSet rollout: Draining pod → add back (hold assignment)- (ControllerKind::StatefulSet, PodStatus::Draining, DepartureReason::Rollout) => {- tracing::info!(- pod = %pod.pod_name,- controller = %controller,- generation = %generation,- "holding assignment for statefulset pod during rollout"+ PlacementPolicy::Active { cap: Some(cap) } => {+ capped += 1;+ tracing::debug!(+ pod = %member.name,+ cap,+ "capping new-gen pod at its rollout quota");- if !active.contains(&pod.pod_name) {- active.push(pod.pod_name.clone());+ }+ PlacementPolicy::Active { cap: None } => {}+ }+ }+ gauge!("personhog_coordination_generation_hold_pods").set(holds as f64);+ gauge!("personhog_coordination_generation_capped_pods").set(capped as f64);+ members+}++/// Derive placement policies from pod registrations and controller+/// intents. Pure so the policy rules are unit-testable.+///+/// The cap is keyed on departing-generation *siblings*, not on the+/// controller's rollout flag: a Deployment reports the rollout complete+/// the moment its last new-gen pod is up, while the old-gen pods are+/// still registered, still serving, and about to be SIGTERMed. The+/// transition is live — and new-gen pods must keep pulling, capped at+/// their final share — for exactly as long as any departing-generation+/// pod of the same controller remains registered. Otherwise partitions+/// sit on the old generation until termination forces every transfer+/// into the pods' termination grace window.+fn derive_members(+ pods: &[RegisteredPod],+ intents: &HashMap<ControllerRef, ClusterIntent>,+ total_partitions: u32,+) -> Vec<Member> {+ let transitioning: HashSet<&ControllerRef> = pods+ .iter()+ .filter_map(|pod| {+ let (controller, intent) = pod_intent(pod, intents)?;+ (controller.kind == ControllerKind::Deployment+ && classify_departure(intent, &pod.generation) == DepartureReason::Rollout)+ .then_some(controller)+ })+ .collect();++ let mut members: Vec<Member> = Vec::new();+ for pod in pods {+ let policy = match pod_intent(pod, intents) {+ None => base_policy(pod.status),+ Some((controller, intent)) => {+ let reason = classify_departure(intent, &pod.generation);+ match (&controller.kind, pod.status, reason) {+ // Old-gen Ready pod keeps serving and keeps its+ // assignments, but receives nothing new and sheds+ // toward the incoming generation.+ (ControllerKind::Deployment, PodStatus::Ready, DepartureReason::Rollout) => {+ Some(PlacementPolicy::Hold)+ }+ // Incoming-generation Ready pod is capped at its+ // final share while the transition is live, computed+ // fresh each evaluation so an HPA change mid-rollout+ // adjusts the quota.+ (ControllerKind::Deployment, PodStatus::Ready, _)+ if transitioning.contains(controller) && intent.desired_replicas > 0 =>+ {+ Some(PlacementPolicy::Active {+ cap: Some(total_partitions.div_ceil(intent.desired_replicas)),+ })+ }+ // StatefulSet rollout: Draining pod stays a member+ // (hold assignment) — the same pod name comes back+ // with a new revision.+ (+ ControllerKind::StatefulSet,+ PodStatus::Draining,+ DepartureReason::Rollout,+ ) => Some(PlacementPolicy::Active { cap: None }),+ _ => base_policy(pod.status),}}- _ => {}+ };+ if let Some(policy) = policy {+ members.push(Member {+ name: pod.pod_name.clone(),+ policy,+ });}}+ members.sort_by(|a, b| a.name.cmp(&b.name));+ members+}++/// A pod's controller ref and watched intent, when both are usable.+fn pod_intent<'p, 'i>(+ pod: &'p RegisteredPod,+ intents: &'i HashMap<ControllerRef, ClusterIntent>,+) -> Option<(&'p ControllerRef, &'i ClusterIntent)> {+ let controller = pod.controller.as_ref()?;+ if pod.generation.is_empty() {+ return None;+ }+ let intent = intents.get(controller)?;+ Some((controller, intent))+}- active.sort();- active.dedup();- active+/// Membership when there is no K8s signal: Ready pods are uncapped+/// active members, Draining pods are not members at all.+fn base_policy(status: PodStatus) -> Option<PlacementPolicy> {+ match status {+ PodStatus::Ready => Some(PlacementPolicy::Active { cap: None }),+ PodStatus::Draining => None,+ }}#[cfg(test)]@@ -1446,4 +1557,202 @@ mod tests {let names = active_pod_names(&pods);assert_eq!(names, vec!["pod-1", "pod-2"]);}++ fn rollout_intent(+ desired: u32,+ rollout: bool,+ current: &str,+ target: Option<&str>,+ ) -> ClusterIntent {+ ClusterIntent {+ desired_replicas: desired,+ previous_replicas: None,+ rollout_in_progress: rollout,+ current_generation: current.to_string(),+ target_generation: target.map(String::from),+ }+ }++ fn deploy_ref() -> ControllerRef {+ ControllerRef {+ kind: ControllerKind::Deployment,+ name: "deploy".to_string(),+ }+ }++ fn ss_ref() -> ControllerRef {+ ControllerRef {+ kind: ControllerKind::StatefulSet,+ name: "ss".to_string(),+ }+ }++ fn k8s_pod(+ name: &str,+ generation: &str,+ status: PodStatus,+ controller: ControllerRef,+ ) -> RegisteredPod {+ RegisteredPod {+ pod_name: name.to_string(),+ generation: generation.to_string(),+ status,+ registered_at: 0,+ last_heartbeat: 0,+ controller: Some(controller),+ advertise_address: None,+ }+ }++ fn policy_of(members: &[Member], name: &str) -> Option<PlacementPolicy> {+ members.iter().find(|m| m.name == name).map(|m| m.policy)+ }++ #[test]+ fn deployment_rollout_holds_old_gen_and_caps_new_gen() {+ let intents = HashMap::from([(deploy_ref(), rollout_intent(3, true, "old", Some("new")))]);+ let pods = vec![+ k8s_pod("old-0", "old", PodStatus::Ready, deploy_ref()),+ k8s_pod("new-0", "new", PodStatus::Ready, deploy_ref()),+ ];+ let members = derive_members(&pods, &intents, 12);+ assert_eq!(policy_of(&members, "old-0"), Some(PlacementPolicy::Hold));+ assert_eq!(+ policy_of(&members, "new-0"),+ Some(PlacementPolicy::Active { cap: Some(4) })+ );+ }++ /// The regression the k3s rollout test caught: after k8s reports the+ /// rollout complete, still-registered old-gen pods must keep the+ /// caps alive or the placement freezes with everything on the old+ /// generation until termination.+ #[test]+ fn caps_survive_rollout_completion_while_old_gen_registered() {+ let intents = HashMap::from([(deploy_ref(), rollout_intent(2, false, "new", None))]);+ let pods = vec![+ k8s_pod("old-0", "old", PodStatus::Ready, deploy_ref()),+ k8s_pod("old-1", "old", PodStatus::Ready, deploy_ref()),+ k8s_pod("new-0", "new", PodStatus::Ready, deploy_ref()),+ k8s_pod("new-1", "new", PodStatus::Ready, deploy_ref()),+ ];+ let members = derive_members(&pods, &intents, 8);+ assert_eq!(policy_of(&members, "old-0"), Some(PlacementPolicy::Hold));+ assert_eq!(policy_of(&members, "old-1"), Some(PlacementPolicy::Hold));+ assert_eq!(+ policy_of(&members, "new-0"),+ Some(PlacementPolicy::Active { cap: Some(4) })+ );+ assert_eq!(+ policy_of(&members, "new-1"),+ Some(PlacementPolicy::Active { cap: Some(4) })+ );+ }++ /// A draining old-gen pod is not a member but still marks the+ /// transition as live, so its incoming replacements stay capped.+ #[test]+ fn draining_old_gen_pod_keeps_the_transition_live() {+ let intents = HashMap::from([(deploy_ref(), rollout_intent(2, false, "new", None))]);+ let pods = vec![+ k8s_pod("old-0", "old", PodStatus::Draining, deploy_ref()),+ k8s_pod("new-0", "new", PodStatus::Ready, deploy_ref()),+ ];+ let members = derive_members(&pods, &intents, 8);+ assert_eq!(policy_of(&members, "old-0"), None);+ assert_eq!(+ policy_of(&members, "new-0"),+ Some(PlacementPolicy::Active { cap: Some(4) })+ );+ }++ #[test]+ fn deployment_steady_state_is_uncapped() {+ let intents = HashMap::from([(deploy_ref(), rollout_intent(2, false, "gen", None))]);+ let pods = vec![+ k8s_pod("pod-0", "gen", PodStatus::Ready, deploy_ref()),+ k8s_pod("pod-1", "gen", PodStatus::Ready, deploy_ref()),+ ];+ let members = derive_members(&pods, &intents, 8);+ assert_eq!(+ policy_of(&members, "pod-0"),+ Some(PlacementPolicy::Active { cap: None })+ );+ assert_eq!(+ policy_of(&members, "pod-1"),+ Some(PlacementPolicy::Active { cap: None })+ );+ }++ #[test]+ fn zero_desired_replicas_leaves_new_gen_uncapped() {+ let intents = HashMap::from([(deploy_ref(), rollout_intent(0, true, "old", Some("new")))]);+ let pods = vec![+ k8s_pod("old-0", "old", PodStatus::Ready, deploy_ref()),+ k8s_pod("new-0", "new", PodStatus::Ready, deploy_ref()),+ ];+ let members = derive_members(&pods, &intents, 12);+ assert_eq!(+ policy_of(&members, "new-0"),+ Some(PlacementPolicy::Active { cap: None })+ );+ }++ #[test]+ fn missing_intent_falls_back_to_status_only_membership() {+ let intents = HashMap::new();+ let pods = vec![+ k8s_pod("pod-0", "old", PodStatus::Ready, deploy_ref()),+ k8s_pod("pod-1", "old", PodStatus::Draining, deploy_ref()),+ ];+ let members = derive_members(&pods, &intents, 8);+ assert_eq!(+ policy_of(&members, "pod-0"),+ Some(PlacementPolicy::Active { cap: None })+ );+ assert_eq!(policy_of(&members, "pod-1"), None);+ }++ #[test]+ fn statefulset_draining_held_only_during_rollout() {+ let rollout = HashMap::from([(ss_ref(), rollout_intent(3, true, "old", Some("new")))]);+ let pods = vec![k8s_pod("ss-0", "old", PodStatus::Draining, ss_ref())];+ let members = derive_members(&pods, &rollout, 8);+ assert_eq!(+ policy_of(&members, "ss-0"),+ Some(PlacementPolicy::Active { cap: None })+ );++ let steady = HashMap::from([(ss_ref(), rollout_intent(3, false, "gen", None))]);+ let pods = vec![k8s_pod("ss-0", "gen", PodStatus::Draining, ss_ref())];+ let members = derive_members(&pods, &steady, 8);+ assert_eq!(policy_of(&members, "ss-0"), None);+ }++ /// Old-gen pods of one controller must not cap pods of another.+ #[test]+ fn transition_is_scoped_per_controller() {+ let other = ControllerRef {+ kind: ControllerKind::Deployment,+ name: "other".to_string(),+ };+ let intents = HashMap::from([+ (deploy_ref(), rollout_intent(2, false, "new", None)),+ (other.clone(), rollout_intent(2, false, "gen", None)),+ ]);+ let pods = vec![+ k8s_pod("old-0", "old", PodStatus::Ready, deploy_ref()),+ k8s_pod("new-0", "new", PodStatus::Ready, deploy_ref()),+ k8s_pod("other-0", "gen", PodStatus::Ready, other),+ ];+ let members = derive_members(&pods, &intents, 8);+ assert_eq!(+ policy_of(&members, "new-0"),+ Some(PlacementPolicy::Active { cap: Some(4) })+ );+ assert_eq!(+ policy_of(&members, "other-0"),+ Some(PlacementPolicy::Active { cap: None })+ );+ }}diff --git a/rust/personhog-coordination/src/protocol.rs b/rust/personhog-coordination/src/protocol.rsindex b3e8c5d1b845..bc5a3ee1158f 100644--- a/rust/personhog-coordination/src/protocol.rs+++ b/rust/personhog-coordination/src/protocol.rs@@ -15,7 +15,7 @@ use std::time::Duration;use assignment_coordination::util::compute_required_handoffs;-use crate::strategy::AssignmentStrategy;+use crate::strategy::{AssignmentStrategy, Member};use crate::types::{HandoffPhase, HandoffState, PodDrainedAck, PodWarmedAck, RegisteredPod, RegisteredRouter,RouterFreezeAck,@@ -58,10 +58,10 @@ pub struct RebalancePlan {pub fn plan_rebalance<S: AssignmentStrategy + ?Sized>(strategy: &S,current: &HashMap<u32, String>,- active_pods: &[String],+ members: &[Member],total_partitions: u32,) -> RebalancePlan {- let desired = strategy.compute_assignments(current, active_pods, total_partitions);+ let desired = strategy.compute_assignments(current, members, total_partitions);let moves = compute_required_handoffs(current, &desired);let moved: HashSet<u32> = moves.iter().map(|(p, _, _)| *p).collect();@@ -99,7 +99,7 @@ pub fn plan_partial_rebalance<S: AssignmentStrategy + ?Sized>(strategy: &S,current: &HashMap<u32, String>,in_flight: &[HandoffState],- active_pods: &[String],+ members: &[Member],total_partitions: u32,) -> RebalancePlan {let pinned: HashSet<u32> = in_flight.iter().map(|h| h.partition).collect();@@ -107,7 +107,7 @@ pub fn plan_partial_rebalance<S: AssignmentStrategy + ?Sized>(for handoff in in_flight {effective.insert(handoff.partition, handoff.new_owner.clone());}- let mut plan = plan_rebalance(strategy, &effective, active_pods, total_partitions);+ let mut plan = plan_rebalance(strategy, &effective, members, total_partitions);plan.handoffs.retain(|h| !pinned.contains(&h.partition));plan.desired.retain(|partition, _| !pinned.contains(partition));@@ -451,11 +451,7 @@ mod tests {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 active = Member::active_all(&["pod-a", "pod-b", "pod-c"]);let plan =plan_partial_rebalance(&StickyBalancedStrategy, ¤t, &in_flight, &active, 4);@@ -487,7 +483,7 @@ mod tests {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 active = Member::active_all(&["pod-a", "pod-b"]);let plan =plan_partial_rebalance(&StickyBalancedStrategy, ¤t, &in_flight, &active, 4);diff --git a/rust/personhog-coordination/src/strategy/jump_hash.rs b/rust/personhog-coordination/src/strategy/jump_hash.rsindex f6b813ec42ee..5360f94a240b 100644--- a/rust/personhog-coordination/src/strategy/jump_hash.rs+++ b/rust/personhog-coordination/src/strategy/jump_hash.rs@@ -2,7 +2,7 @@ use std::collections::HashMap;use crate::hash::jump_consistent_hash;-use super::AssignmentStrategy;+use super::{AssignmentStrategy, Member};/// Assigns partitions using jump consistent hash.///@@ -10,6 +10,10 @@ use super::AssignmentStrategy;/// from scratch every time. Good for initial deployment or when you want/// reproducible, hash-based placement.///+/// Ignores placement policies — hash placement has no notion of holding or+/// capping a member, so rollout-aware callers should prefer the sticky+/// strategy.+////// Minimal disruption property: when going from N to N+1 pods, only ~1/(N+1)/// of partitions change owners.pub struct JumpHashStrategy;@@ -18,19 +22,19 @@ impl AssignmentStrategy for JumpHashStrategy {fn compute_assignments(&self,_current: &HashMap<u32, String>,- active_pods: &[String],+ members: &[Member],num_partitions: u32,) -> HashMap<u32, String> {- if active_pods.is_empty() {+ if members.is_empty() {return HashMap::new();}- let num_pods = active_pods.len() as i32;+ let num_pods = members.len() as i32;let mut assignments = HashMap::with_capacity(num_partitions as usize);for partition in 0..num_partitions {let pod_index = jump_consistent_hash(partition as u64, num_pods);- assignments.insert(partition, active_pods[pod_index as usize].clone());+ assignments.insert(partition, members[pod_index as usize].name.clone());}assignments@@ -51,7 +55,7 @@ mod tests {#[test]fn single_pod() {let strategy = JumpHashStrategy;- let pods = vec!["pod-0".to_string()];+ let pods = Member::active_all(&["pod-0"]);let result = strategy.compute_assignments(&HashMap::new(), &pods, 16);assert_eq!(result.len(), 16);for owner in result.values() {@@ -62,7 +66,7 @@ mod tests {#[test]fn two_pods_balanced() {let strategy = JumpHashStrategy;- let pods = vec!["pod-0".to_string(), "pod-1".to_string()];+ let pods = Member::active_all(&["pod-0", "pod-1"]);let result = strategy.compute_assignments(&HashMap::new(), &pods, 16);assert_eq!(result.len(), 16);let pod0 = result.values().filter(|v| v.as_str() == "pod-0").count();@@ -74,7 +78,7 @@ mod tests {#[test]fn ignores_current_assignments() {let strategy = JumpHashStrategy;- let pods = vec!["pod-0".to_string(), "pod-1".to_string()];+ let pods = Member::active_all(&["pod-0", "pod-1"]);let mut current = HashMap::new();for p in 0..16 {current.insert(p, "pod-0".to_string());@@ -87,11 +91,7 @@ mod tests {#[test]fn deterministic() {let strategy = JumpHashStrategy;- let pods = vec![- "pod-0".to_string(),- "pod-1".to_string(),- "pod-2".to_string(),- ];+ let pods = Member::active_all(&["pod-0", "pod-1", "pod-2"]);let a = strategy.compute_assignments(&HashMap::new(), &pods, 16);let b = strategy.compute_assignments(&HashMap::new(), &pods, 16);assert_eq!(a, b);diff --git a/rust/personhog-coordination/src/strategy/mod.rs b/rust/personhog-coordination/src/strategy/mod.rsindex edaa4ae5a975..9dc7d0ae2613 100644--- a/rust/personhog-coordination/src/strategy/mod.rs+++ b/rust/personhog-coordination/src/strategy/mod.rs@@ -1,4 +1,6 @@mod jump_hash;-pub use assignment_coordination::strategy::{AssignmentStrategy, StickyBalancedStrategy};+pub use assignment_coordination::strategy::{+ AssignmentStrategy, Member, PlacementPolicy, StickyBalancedStrategy,+};pub use jump_hash::JumpHashStrategy;diff --git a/rust/personhog-coordination/src/util.rs b/rust/personhog-coordination/src/util.rsindex afd0fde01ece..f48ee2df5b4f 100644--- a/rust/personhog-coordination/src/util.rs+++ b/rust/personhog-coordination/src/util.rs@@ -293,6 +293,8 @@ pub fn preregister_coordinator_metrics() {}metrics::counter!("personhog_coordination_elections_won_total").increment(0);metrics::counter!("personhog_coordination_partition_releases_total").increment(0);+ metrics::gauge!("personhog_coordination_generation_hold_pods").set(0.0);+ metrics::gauge!("personhog_coordination_generation_capped_pods").set(0.0);}/// Same as [`preregister_coordinator_metrics`], for the counters thediff --git a/rust/personhog-coordination/tests/integration.rs b/rust/personhog-coordination/tests/integration.rsindex 448ba252e119..e9aa6e40928e 100644--- a/rust/personhog-coordination/tests/integration.rs+++ b/rust/personhog-coordination/tests/integration.rs@@ -770,7 +770,8 @@ async fn rapid_pod_joins(.iter().map(|a| (a.partition, a.owner.clone())).collect();- let desired = strategy.compute_assignments(¤t, &pods, MANY_PARTITIONS);+ let members = personhog_coordination::strategy::Member::active_all(&pods);+ let desired = strategy.compute_assignments(¤t, &members, MANY_PARTITIONS);assignment_coordination::util::compute_required_handoffs(¤t, &desired).is_empty()}})@@ -1058,7 +1059,8 @@ async fn debounce_batches_rapid_pod_changes(.iter().map(|a| (a.partition, a.owner.clone())).collect();- let desired = strategy.compute_assignments(¤t, &pods, MANY_PARTITIONS);+ let members = personhog_coordination::strategy::Member::active_all(&pods);+ let desired = strategy.compute_assignments(¤t, &members, MANY_PARTITIONS);assignment_coordination::util::compute_required_handoffs(¤t, &desired).is_empty()}})diff --git a/rust/personhog-coordination/tests/k3s_integration.rs b/rust/personhog-coordination/tests/k3s_integration.rsindex 906124c7f266..9687cc22fe74 100644--- a/rust/personhog-coordination/tests/k3s_integration.rs+++ b/rust/personhog-coordination/tests/k3s_integration.rs@@ -305,6 +305,66 @@ async fn trigger_deployment_rollout(client: &Client, name: &str) {.expect("failed to patch deployment");}+/// Patch the deployment to an image tag that cannot be pulled. The new+/// ReplicaSet scales up but its pods never run, so the rollout stays in+/// progress for the rest of the test instead of completing within+/// seconds — quota placement only applies inside that window.+async fn trigger_stuck_deployment_rollout(client: &Client, name: &str) {+ let deployments: Api<Deployment> = Api::namespaced(client.clone(), NAMESPACE);+ let patch = serde_json::json!({+ "spec": {+ "template": {+ "spec": {+ "containers": [{+ "name": "pause",+ "image": "registry.k8s.io/pause:no-such-tag"+ }]+ }+ }+ }+ });+ deployments+ .patch(name, &PatchParams::default(), &Patch::Merge(&patch))+ .await+ .expect("failed to patch deployment");+}++/// Wait for new pod *names* in any phase — a stuck rollout's pods never+/// reach Running, but their pod-template-hash label and owner refs are+/// set at creation, which is all generation discovery needs.+async fn wait_for_new_pod_names(+ client: &Client,+ label_selector: &str,+ old_names: &[String],+ count: usize,+) -> Vec<String> {+ let pods: Api<k8s_openapi::api::core::v1::Pod> = Api::namespaced(client.clone(), NAMESPACE);+ let timeout = Duration::from_secs(120);+ let start = std::time::Instant::now();+ loop {+ let list = pods+ .list(&ListParams::default().labels(label_selector))+ .await+ .expect("failed to list pods");+ let new: Vec<String> = list+ .items+ .iter()+ .filter_map(|p| p.metadata.name.clone())+ .filter(|n| !old_names.contains(n))+ .collect();+ if new.len() >= count {+ return new;+ }+ if start.elapsed() > timeout {+ panic!(+ "timed out waiting for {count} new pod names, got {}",+ new.len()+ );+ }+ tokio::time::sleep(Duration::from_secs(2)).await;+ }+}+async fn trigger_statefulset_rollout(client: &Client, name: &str) {let statefulsets: Api<StatefulSet> = Api::namespaced(client.clone(), NAMESPACE);let patch = serde_json::json!({@@ -640,6 +700,223 @@ async fn deployment_rollout_reassigns_partitions() {k8s_cancel.cancel();}+/// Deployment rollout with new-gen pods arriving one at a time: the+/// first new-generation pod is capped at its final share instead of+/// being handed the whole partition space and losing half of it again+/// when its peer arrives.+///+/// The rollout is wedged on an unpullable image so it stays in progress+/// for the whole test, and the coordination pods register manually so+/// the test controls arrival order.+///+/// Flow:+/// 1. Two old-gen pods share all 8 partitions+/// 2. Wedge a rollout → coordinator holds old-gen instead of excluding it+/// 3. new-0 registers alone → receives exactly its quota (4); old-gen+/// pods keep serving the other 4+/// 4. new-1 registers → takes the remaining 4; new-0's partitions are+/// untouched, so every partition moved exactly once+#[tokio::test(flavor = "multi_thread")]+#[serial]+async fn deployment_rollout_caps_first_new_pod_at_quota() {+ let (_container, k8s_client, _tmp) = setup_k3s().await;++ let deploy_name = "test-quota-deploy";+ create_deployment(&k8s_client, deploy_name, 2).await;+ wait_for_ready_pods(&k8s_client, &format!("app={deploy_name}"), 2).await;++ let k8s_cancel = CancellationToken::new();+ let awareness = Arc::new(K8sAwareness::new(+ k8s_client.clone(),+ NAMESPACE.to_string(),+ k8s_cancel.clone(),+ ));++ let old_names = get_running_pod_names(&k8s_client, &format!("app={deploy_name}")).await;+ assert_eq!(old_names.len(), 2, "expected 2 running pods");+ let pod_info = awareness+ .discover_controller(&old_names[0])+ .await+ .expect("discover failed");+ let old_generation = pod_info.generation.clone();++ tokio::time::sleep(Duration::from_secs(3)).await;++ let store = test_store("deploy-quota-k3s").await;+ store.set_total_partitions(NUM_PARTITIONS).await.unwrap();++ // Fresh awareness for the coordinator so the test exercises the lazy+ // watch bootstrap from pod registrations (see+ // deployment_rollout_reassigns_partitions for why sharing the+ // scaffolding instance would mask that path).+ let coordinator_awareness = Arc::new(K8sAwareness::new(+ k8s_client.clone(),+ NAMESPACE.to_string(),+ k8s_cancel.clone(),+ ));+ let cancel = CancellationToken::new();+ let _coord = start_coordinator_k8s(+ Arc::clone(&store),+ Some(coordinator_awareness),+ cancel.clone(),+ );+ let _router = start_router(Arc::clone(&store), "router-0", cancel.clone());++ let old_config = |name: &str| PodConfig {+ pod_name: name.to_string(),+ generation: old_generation.clone(),+ controller: Some(pod_info.controller.clone()),+ lease_ttl: 10,+ heartbeat_interval: Duration::from_secs(3),+ ..Default::default()+ };+ let (_old0_events, _old0_handle) = start_pod_k8s(+ Arc::clone(&store),+ old_config("old-0"),+ None,+ cancel.clone(),+ );+ let (_old1_events, _old1_handle) = start_pod_k8s(+ Arc::clone(&store),+ old_config("old-1"),+ None,+ cancel.clone(),+ );++ // Initial assignment across both old pods+ let check_store = Arc::clone(&store);+ wait_for_condition(E2E_TIMEOUT, POLL_INTERVAL, || {+ let store = Arc::clone(&check_store);+ async move {+ let a = store.list_assignments().await.unwrap_or_default();+ let r = store.list_routers().await.unwrap_or_default();+ let h = store.list_handoffs().await.unwrap_or_default();+ a.len() == NUM_PARTITIONS as usize+ && r.len() == 1+ && h.is_empty()+ && a.iter().any(|x| x.owner == "old-0")+ && a.iter().any(|x| x.owner == "old-1")+ }+ })+ .await;++ // Wedge a rollout and wait until the old generation classifies as+ // departing; the coordinator's own watcher sees the same events.+ trigger_stuck_deployment_rollout(&k8s_client, deploy_name).await;+ wait_for_departure_reason(+ &awareness,+ &pod_info.controller,+ &old_generation,+ DepartureReason::Rollout,+ )+ .await;++ // The stuck pods never run, but they carry the new generation label.+ let new_k8s_names =+ wait_for_new_pod_names(&k8s_client, &format!("app={deploy_name}"), &old_names, 1).await;+ let new_pod_info = awareness+ .discover_controller(&new_k8s_names[0])+ .await+ .expect("discover new pod failed");+ let new_generation = new_pod_info.generation;+ assert_ne!(new_generation, old_generation);++ let new_config = |name: &str| PodConfig {+ pod_name: name.to_string(),+ generation: new_generation.clone(),+ controller: Some(pod_info.controller.clone()),+ lease_ttl: 10,+ heartbeat_interval: Duration::from_secs(3),+ ..Default::default()+ };++ // First new-gen pod registers alone. Quota = 8 partitions / 2+ // desired replicas = 4: it must end up with exactly its final share+ // while the old generation keeps serving the rest.+ let (_new0_events, _new0_handle) = start_pod_k8s(+ Arc::clone(&store),+ new_config("new-0"),+ None,+ cancel.clone(),+ );++ let quota = (NUM_PARTITIONS / 2) as usize;+ let check_store = Arc::clone(&store);+ wait_for_condition(E2E_TIMEOUT, POLL_INTERVAL, || {+ let store = Arc::clone(&check_store);+ async move {+ let a = store.list_assignments().await.unwrap_or_default();+ let h = store.list_handoffs().await.unwrap_or_default();+ let new0 = a.iter().filter(|x| x.owner == "new-0").count();+ let old = a+ .iter()+ .filter(|x| x.owner == "old-0" || x.owner == "old-1")+ .count();+ a.len() == NUM_PARTITIONS as usize+ && h.is_empty()+ && new0 == (NUM_PARTITIONS / 2) as usize+ && old == (NUM_PARTITIONS / 2) as usize+ }+ })+ .await;++ // Let any further (wrong) rebalance run before asserting the state+ // held: with the pre-quota behavior new-0 would keep pulling until+ // it owned everything.+ tokio::time::sleep(Duration::from_secs(3)).await;+ let assignments = store.list_assignments().await.unwrap();+ let new0_partitions: std::collections::BTreeSet<u32> = assignments+ .iter()+ .filter(|a| a.owner == "new-0")+ .map(|a| a.partition)+ .collect();+ assert_eq!(+ new0_partitions.len(),+ quota,+ "first new-gen pod must hold exactly its quota, got {new0_partitions:?}"+ );+ assert!(store.list_handoffs().await.unwrap().is_empty());++ // Second new-gen pod takes the remainder.+ let (_new1_events, _new1_handle) = start_pod_k8s(+ Arc::clone(&store),+ new_config("new-1"),+ None,+ cancel.clone(),+ );++ let check_store = Arc::clone(&store);+ wait_for_condition(E2E_TIMEOUT, POLL_INTERVAL, || {+ let store = Arc::clone(&check_store);+ async move {+ let a = store.list_assignments().await.unwrap_or_default();+ let h = store.list_handoffs().await.unwrap_or_default();+ let new0 = a.iter().filter(|x| x.owner == "new-0").count();+ let new1 = a.iter().filter(|x| x.owner == "new-1").count();+ a.len() == NUM_PARTITIONS as usize+ && h.is_empty()+ && new0 == (NUM_PARTITIONS / 2) as usize+ && new1 == (NUM_PARTITIONS / 2) as usize+ }+ })+ .await;++ // new-0 kept the same partitions — each one moved exactly once.+ let assignments = store.list_assignments().await.unwrap();+ let new0_after: std::collections::BTreeSet<u32> = assignments+ .iter()+ .filter(|a| a.owner == "new-0")+ .map(|a| a.partition)+ .collect();+ assert_eq!(+ new0_after, new0_partitions,+ "second arrival must not churn the first pod's partitions"+ );++ cancel.cancel();+ k8s_cancel.cancel();+}+/// StatefulSet rollout: pod skips drain and exits immediately.////// In a StatefulSet rolling update, K8s terminates pods one at a time anddiff --git a/rust/personhog-stateright/src/main.rs b/rust/personhog-stateright/src/main.rsindex 7b2c9274594a..e001576694f9 100644--- a/rust/personhog-stateright/src/main.rs+++ b/rust/personhog-stateright/src/main.rs@@ -58,6 +58,7 @@ fn main() {rejoins: 0,router_joins: 0,zombie_window,+ hold_pods: 0,cancels: 0,probes: false,};diff --git a/rust/personhog-stateright/src/model.rs b/rust/personhog-stateright/src/model.rsindex e12f16503ce1..3f5c38173c83 100644--- a/rust/personhog-stateright/src/model.rs+++ b/rust/personhog-stateright/src/model.rs@@ -11,7 +11,7 @@ use personhog_coordination::pod::{desired_state, DesiredState};use personhog_coordination::protocol::{drain_satisfied, freeze_quorum_met, plan_partial_rebalance, warm_satisfied,};-use personhog_coordination::strategy::{AssignmentStrategy, StickyBalancedStrategy};+use personhog_coordination::strategy::{AssignmentStrategy, Member, StickyBalancedStrategy};use personhog_coordination::types::{AssignmentStatus, HandoffState, PartitionAssignment, PodDrainedAck, PodStatus, PodWarmedAck,RegisteredPod, RegisteredRouter, RouterFreezeAck,@@ -141,6 +141,11 @@ pub struct HandoffModel {/// Writes a lease-expired pod may still accept before its keepalive/// self-fences it. Zero disables the zombie window entirely.pub zombie_window: u8,+ /// Pods below this id form a departing generation for the planner:+ /// they are Hold members, and every other pod is capped at its final+ /// share (the coordinator's rollout policies). Zero models the+ /// steady state, where every pod is an uncapped active member.+ pub hold_pods: u8,/// Adds reachability probes (`sometimes` properties) for scenario/// shapes that only exist at larger scale — used to measure, rather/// than assume, which configurations actually reach them. Off in the@@ -213,14 +218,41 @@ impl HandoffModel {.iter().map(|(p, owner)| (*p as u32, pod_name(*owner))).collect();- let mut active: Vec<String> = state+ let members = self.planner_members(state);+ StickyBalancedStrategy.compute_assignments(¤t, &members, self.partitions as u32)+ }++ /// Planner membership with the model's placement policies applied —+ /// shared by target computation and rebalance planning so every+ /// property judges the same placement mode.+ fn planner_members(&self, state: &SystemState) -> Vec<Member> {+ let mut ids: Vec<PodId> = state.pods.iter().filter(|(_, p)| p.registered)- .map(|(id, _)| pod_name(*id))+ .map(|(id, _)| *id).collect();- active.sort();- StickyBalancedStrategy.compute_assignments(¤t, &active, self.partitions as u32)+ ids.sort();+ if self.hold_pods == 0 {+ return ids+ .into_iter()+ .map(|id| Member::active(pod_name(id)))+ .collect();+ }+ // The cap mirrors the coordinator's: total over the incoming+ // fleet's *desired* size, not its live count, so a crashed+ // incoming pod does not inflate its peers' quota.+ let incoming = self.pods.saturating_sub(self.hold_pods).max(1);+ let cap = (self.partitions as u32).div_ceil(incoming as u32);+ ids.into_iter()+ .map(|id| {+ if id < self.hold_pods {+ Member::hold(pod_name(id))+ } else {+ Member::active_capped(pod_name(id), cap)+ }+ })+ .collect()}fn target_owner(&self, state: &SystemState, partition: Partition) -> Option<PodId> {@@ -675,18 +707,12 @@ impl HandoffModel {.iter().map(|(p, h)| production_handoff(*p, h)).collect();- let mut active: Vec<String> = last- .pods- .iter()- .filter(|(_, p)| p.registered)- .map(|(id, _)| pod_name(*id))- .collect();- active.sort();+ let members = self.planner_members(last);let mut plan = plan_partial_rebalance(&StickyBalancedStrategy,¤t,&in_flight,- &active,+ &members,self.partitions as u32,);if plan.handoffs.is_empty() {diff --git a/rust/personhog-stateright/tests/model_tests.rs b/rust/personhog-stateright/tests/model_tests.rsindex 1c1c1cea6df7..8ab7a586133a 100644--- a/rust/personhog-stateright/tests/model_tests.rs+++ b/rust/personhog-stateright/tests/model_tests.rs@@ -129,6 +129,7 @@ fn base() -> HandoffModel {rejoins: 0,router_joins: 0,zombie_window: 0,+ hold_pods: 0,cancels: 0,probes: false,}@@ -843,3 +844,27 @@ fn prompt_detection_is_what_makes_the_read_gate_hold() {"dropping the claim with the registration must close them");}++/// Rollout quota mode: pod-0 is a departing-generation Hold member and+/// the incoming pods are capped at their final share, the membership+/// the coordinator derives mid-rollout. The checker drives the quota+/// planner through every interleaving with a crash and a rejoin+/// available — pinning that quota-mode plans never double-plan a+/// partition, never strand one, and converge (the frozen-placement+/// failure shape is a liveness violation here). The rejoin covers the+/// capped pod that comes back at zero partitions and must be leveled+/// from its siblings, including when the crashed-and-returned pod is+/// the Hold member and phase-4 forcing pushed a survivor over cap.+#[test]+fn rollout_quota_mode_is_safe_and_live() {+ HandoffModel {+ pods: 3,+ partitions: 2,+ crashes: 1,+ rejoins: 1,+ hold_pods: 1,+ ..base()+ }+ .explore("rollout_quota_mode_is_safe_and_live")+ .assert_properties();+}