: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
chore(personhog): add stateright modeling (#69521)
Zach Brown01a7ba65743c
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 67a06619742f..4bf3d8f915b0 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -240,6 +240,12 @@ version = "0.7.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"+[[package]]+name = "ascii"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16"+[[package]]name = "ascii-canvas"version = "3.0.0"@@ -1985,6 +1991,12 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"+[[package]]+name = "choice"+version = "0.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a3b71fc821deaf602a933ada5c845d088156d0cdf2ebf43ede390afe93466553"+[[package]]name = "chrono"version = "0.4.44"@@ -2009,6 +2021,12 @@ dependencies = ["phf 0.12.1",]+[[package]]+name = "chunked_transfer"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901"+[[package]]name = "ciborium"version = "0.2.2"@@ -5050,6 +5068,12 @@ version = "2.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"+[[package]]+name = "id-set"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9633fadf6346456cf8531119ba4838bc6d82ac4ce84d9852126dd2aa34d49264"+[[package]]name = "ident_case"version = "1.0.1"@@ -6591,6 +6615,12 @@ version = "0.4.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b93853da6d84c2e3c7d730d6473e8817692dd89be387eb01b94d7f108ecb5b8c"+[[package]]+name = "nohash-hasher"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"+[[package]]name = "nom"version = "7.1.3"@@ -7520,6 +7550,15 @@ dependencies = ["tracing-subscriber",]+[[package]]+name = "personhog-stateright"+version = "0.1.0"+dependencies = [+ "clap",+ "personhog-coordination",+ "stateright",+]+[[package]]name = "personhog-writer"version = "0.1.0"@@ -10373,6 +10412,26 @@ dependencies = ["windows-sys 0.59.0",]+[[package]]+name = "stateright"+version = "0.31.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd1157f21b11916f90fe1f2ac9a8d0e09a8813b28701584141060f414eedf6ba"+dependencies = [+ "ahash 0.8.12",+ "choice",+ "crossbeam-utils",+ "dashmap 6.1.0",+ "id-set",+ "log",+ "nohash-hasher",+ "parking_lot",+ "rand 0.9.2",+ "serde",+ "serde_json",+ "tiny_http",+]+[[package]]name = "static_assertions"version = "1.1.0"@@ -11119,6 +11178,18 @@ dependencies = ["crunchy",]+[[package]]+name = "tiny_http"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "389915df6413a2e74fb181895f933386023c71110878cd0825588928e64cdc82"+dependencies = [+ "ascii",+ "chunked_transfer",+ "httpdate",+ "log",+]+[[package]]name = "tinystr"version = "0.8.2"diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex 527ee9571e70..66d10dc9f37b 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -56,6 +56,7 @@ members = ["personhog-proto","personhog-replica","personhog-router",+ "personhog-stateright","affected-services","property-vals-rs",]@@ -93,6 +94,19 @@ js-source-scopes = { git = "https://github.com/getsentry/js-source-scopes", rev[profile.release]debug = "line-tables-only"+# The stateright model checker exhaustively explores millions of protocol+# states; its hot loop (state hashing, BTreeMap clones) is ~11x slower+# unoptimized, which would put the exhaustive tests at ~25 minutes in+# debug-profile CI runs instead of ~2. Compile the checker and the model+# crate with release-grade codegen even in dev builds — this changes+# nothing about behavior (debug assertions and overflow checks stay on),+# only how hard LLVM optimizes these two packages.+[profile.dev.package.personhog-stateright]+opt-level = 3++[profile.dev.package.stateright]+opt-level = 3+[workspace.dependencies]aho-corasick = "1.1"anyhow = "1.0"diff --git a/rust/affected-services/tests/integration.rs b/rust/affected-services/tests/integration.rsindex c9242eb8f5b7..f0b6e12dec73 100644--- a/rust/affected-services/tests/integration.rs+++ b/rust/affected-services/tests/integration.rs@@ -111,6 +111,7 @@ fn every_deployable_binary_has_an_image_entry() {"stl_dump","run", // hogvm dev/diff CLI, not a service"hermes",+ "personhog-stateright", // model-checker explorer CLI, not a service].into();diff --git a/rust/personhog-coordination/src/coordinator.rs b/rust/personhog-coordination/src/coordinator.rsindex d885f97e70f6..6384a8499995 100644--- a/rust/personhog-coordination/src/coordinator.rs+++ b/rust/personhog-coordination/src/coordinator.rs@@ -6,11 +6,11 @@ use etcd_client::{EventType, WatchStream};use tokio_util::sync::CancellationToken;use assignment_coordination::store::parse_watch_value;-use assignment_coordination::util::compute_required_handoffs;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::store::{self, PersonhogStore};use crate::strategy::AssignmentStrategy;use crate::types::{@@ -408,30 +408,9 @@ impl Coordinator {let routers = store.list_routers().await?;let freeze_acks = store.list_freeze_acks(partition).await?;- // Identity-based quorum: every currently registered router- // must have acked this partition's freeze. A count- // comparison would let a stale ack from a departed router- // (acks are not lease-bound) stand in for a live router- // that hasn't stashed yet — advancing to Draining while- // that router still forwards writes to the old owner.- // Only acks echoing this handoff's id count: an ack left- // over from a previous handoff of the same partition- // proves nothing about this one.- //- // With zero routers there is no traffic to stash, so the- // freeze quorum is vacuously met. This keeps bootstrap and- // router-less configurations (e.g. tests exercising only- // the coordinator+pod) unblocked.- let acked: HashSet<&str> = freeze_acks- .iter()- .filter(|a| a.handoff_id == handoff.handoff_id)- .map(|a| a.router_name.as_str())- .collect();- let all_routers_frozen = routers- .iter()- .all(|r| acked.contains(r.router_name.as_str()));-- if all_routers_frozen {+ // Quorum semantics live in `protocol::freeze_quorum_met`+ // (shared with the stateright model).+ if freeze_quorum_met(&routers, &freeze_acks, &handoff) {// Initial assignments (no old owner) skip Draining// entirely — there's no inflight to wait for. Advance// straight to Warming.@@ -455,38 +434,11 @@ impl Coordinator {}}HandoffPhase::Draining => {- let old_owner_condition = match &handoff.old_owner {- // Defensive: a handoff that reached Draining without- // an old owner shouldn't exist (Freezing skips- // Draining when old_owner is None), but if it does,- // there's nothing to drain.- None => true,- Some(name) => {- // "Alive" here means the pod's etcd registration key- // still exists (its lease hasn't expired) — not just- // that it's `Ready`. A `Draining` pod is shutting- // down gracefully but is still capable of running its- // handoff handler and writing a `DrainedAck`, and may- // still have inflight handlers. Bypassing the drain- // requirement for such a pod would let the- // coordinator advance to Warming while the old owner- // is still producing — breaking the protocol's core- // invariant. Only treat the old owner as drained- // when its key is genuinely absent.- let pods = store.list_pods().await?;- let old_owner_present = pods.iter().any(|p| p.pod_name == *name);- if !old_owner_present {- true- } else {- let drained_acks = store.list_drained_acks(partition).await?;- drained_acks- .iter()- .any(|a| a.pod_name == *name && a.handoff_id == handoff.handoff_id)- }- }- };-- if old_owner_condition {+ // Drain semantics live in `protocol::drain_satisfied`+ // (shared with the stateright model).+ let pods = store.list_pods().await?;+ let drained_acks = store.list_drained_acks(partition).await?;+ if drain_satisfied(&pods, &drained_acks, &handoff) {let advanced = store.cas_handoff_phase(partition, HandoffPhase::Draining, HandoffPhase::Warming).await?;@@ -501,11 +453,7 @@ impl Coordinator {}HandoffPhase::Warming => {let warmed = store.list_warmed_acks(partition).await?;- let new_owner_warmed = warmed- .iter()- .any(|a| a.pod_name == handoff.new_owner && a.handoff_id == handoff.handoff_id);-- if new_owner_warmed {+ if warm_satisfied(&warmed, &handoff) {tracing::info!(partition,new_owner = %handoff.new_owner,@@ -617,63 +565,38 @@ impl Coordinator {.map(|a| (a.partition, a.owner.clone())).collect();- let new_assignments =- strategy.compute_assignments(¤t_map, &active_pods, total_partitions);- let reassignments = compute_required_handoffs(¤t_map, &new_assignments);-- // Every partition that has a new owner goes through the handoff- // protocol, including partitions that had no prior owner (initial- // assignment). This guarantees routers never route to a pod whose- // cache hasn't been warmed.- //- // Partitions that already have the correct owner are skipped.- let assigned_partitions: HashSet<u32> = new_assignments.keys().copied().collect();- let reassignment_partitions: HashSet<u32> =- reassignments.iter().map(|(p, _, _)| *p).collect();-- // Fresh partitions = assigned but neither in current nor being reassigned.- let fresh_partitions: Vec<u32> = assigned_partitions- .iter()- .copied()- .filter(|p| !current_map.contains_key(p) && !reassignment_partitions.contains(p))- .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);- if reassignments.is_empty() && fresh_partitions.is_empty() {+ if plan.handoffs.is_empty() {tracing::debug!("no handoffs needed");return Ok(());}let now = util::now_seconds();- let mut handoff_objects: Vec<HandoffState> = Vec::new();-- // Reassignments: old_owner = Some(prior owner)- for (partition, old_owner, new_owner) in &reassignments {- handoff_objects.push(HandoffState {- partition: *partition,- old_owner: Some(old_owner.clone()),- new_owner: new_owner.clone(),- phase: HandoffPhase::Freezing,- started_at: now,- handoff_id: util::new_handoff_id(),- });- }-- // Fresh assignments: old_owner = None (skip drain, skip release)- for partition in &fresh_partitions {- let new_owner = &new_assignments[partition];- handoff_objects.push(HandoffState {- partition: *partition,- old_owner: None,- new_owner: new_owner.clone(),+ let handoff_objects: Vec<HandoffState> = plan+ .handoffs+ .iter()+ .map(|h| HandoffState {+ partition: h.partition,+ old_owner: h.old_owner.clone(),+ new_owner: h.new_owner.clone(),phase: HandoffPhase::Freezing,started_at: now,handoff_id: util::new_handoff_id(),- });- }+ })+ .collect();+ let moves = plan+ .handoffs+ .iter()+ .filter(|h| h.old_owner.is_some())+ .count();tracing::info!(- reassignments = reassignments.len(),- fresh = fresh_partitions.len(),+ reassignments = moves,+ fresh = plan.handoffs.len() - moves,"creating handoffs");@@ -683,16 +606,14 @@ impl Coordinator {// handoff reaches Complete.let handoff_partitions: HashSet<u32> =handoff_objects.iter().map(|h| h.partition).collect();- let assignment_objects: Vec<PartitionAssignment> = new_assignments+ let stable_assignments: Vec<PartitionAssignment> = plan+ .desired.iter().map(|(&partition, owner)| PartitionAssignment {partition,owner: owner.clone(),status: AssignmentStatus::Active,})- .collect();- let stable_assignments: Vec<PartitionAssignment> = assignment_objects- .into_iter().filter(|a| !handoff_partitions.contains(&a.partition)).collect();diff --git a/rust/personhog-coordination/src/lib.rs b/rust/personhog-coordination/src/lib.rsindex 370764b96731..91ec551f4ddf 100644--- a/rust/personhog-coordination/src/lib.rs+++ b/rust/personhog-coordination/src/lib.rs@@ -2,6 +2,7 @@ pub mod coordinator;pub mod error;pub mod hash;pub mod pod;+pub mod protocol;pub mod routing_table;pub mod store;pub mod strategy;diff --git a/rust/personhog-coordination/src/pod.rs b/rust/personhog-coordination/src/pod.rsindex f2daf30c46b0..b88bd0265c9b 100644--- a/rust/personhog-coordination/src/pod.rs+++ b/rust/personhog-coordination/src/pod.rs@@ -26,8 +26,12 @@ use crate::util;/// crash-restart inside its lease TTL, which preserves its registration/// and assignments but wipes its cache and fences) is repaired by/// re-deriving rather than by replaying remembered events.+/// Public because the stateright model (`personhog-stateright`) drives+/// its pod transitions through this exact function — the model checks+/// the code production runs, so the pod state machine cannot drift from+/// its verified form.#[derive(Debug, Clone, Copy, PartialEq, Eq)]-enum DesiredState {+pub enum DesiredState {/// This pod owns the partition and no handoff constrains it: cache/// warm, writes admitted. Also the old owner's state during Freezing/// (routers are still collecting the freeze quorum; writes keep@@ -56,7 +60,7 @@ enum DesiredState {/// when it involves this pod, takes precedence over the assignment: the/// assignment names the *old* owner (or nobody) for the whole life of a/// handoff and only flips to the new owner atomically at Complete.-fn desired_state(+pub fn desired_state(pod: &str,assignment: Option<&PartitionAssignment>,handoff: Option<&HandoffState>,diff --git a/rust/personhog-coordination/src/protocol.rs b/rust/personhog-coordination/src/protocol.rsnew file mode 100644index 000000000000..8655f608fd8b--- /dev/null+++ b/rust/personhog-coordination/src/protocol.rs@@ -0,0 +1,147 @@+//! Pure protocol decision functions, shared between the coordinator and+//! the stateright model (`personhog-stateright`).+//!+//! The coordinator calls these on state it reads from etcd; the model+//! calls them on checker state. One implementation on both sides means+//! the logic the checker verifies is the logic production runs — the+//! phase-advancement rules cannot drift from their verified form.+//!+//! Every function is a pure predicate over partition-scoped inputs: the+//! caller supplies the acks already filtered to one partition (as+//! `list_*_acks(partition)` returns them).++use std::collections::{HashMap, HashSet};++use assignment_coordination::util::compute_required_handoffs;++use crate::strategy::AssignmentStrategy;+use crate::types::{+ HandoffState, PodDrainedAck, PodWarmedAck, RegisteredPod, RegisteredRouter, RouterFreezeAck,+};++/// One handoff a rebalance has decided to create. `old_owner` is `None`+/// for a fresh assignment (no prior owner), which skips the drain.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct PlannedHandoff {+ pub partition: u32,+ pub old_owner: Option<String>,+ pub new_owner: String,+}++/// A rebalance decision: the full desired placement, and the handoffs+/// required to reach it from the current placement.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct RebalancePlan {+ /// partition → owner for every assigned partition (the strategy's+ /// output, verbatim).+ pub desired: HashMap<u32, String>,+ /// Handoffs to create: moves (owner changed) carry the prior owner;+ /// fresh partitions (assigned for the first time) carry none.+ /// Partitions already owned by their target appear in `desired` only.+ pub handoffs: Vec<PlannedHandoff>,+}++/// Plan a rebalance: compute the desired placement via `strategy`, then+/// diff it against the current assignments. Every planned handoff starts+/// 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.+pub fn plan_rebalance<S: AssignmentStrategy + ?Sized>(+ strategy: &S,+ current: &HashMap<u32, String>,+ active_pods: &[String],+ total_partitions: u32,+) -> RebalancePlan {+ let desired = strategy.compute_assignments(current, active_pods, total_partitions);+ let moves = compute_required_handoffs(current, &desired);+ let moved: HashSet<u32> = moves.iter().map(|(p, _, _)| *p).collect();++ let mut handoffs: Vec<PlannedHandoff> = moves+ .into_iter()+ .map(|(partition, old_owner, new_owner)| PlannedHandoff {+ partition,+ old_owner: Some(old_owner),+ new_owner,+ })+ .collect();+ for (partition, new_owner) in &desired {+ if !current.contains_key(partition) && !moved.contains(partition) {+ handoffs.push(PlannedHandoff {+ partition: *partition,+ old_owner: None,+ new_owner: new_owner.clone(),+ });+ }+ }+ RebalancePlan { desired, handoffs }+}++/// Whether the freeze quorum for `handoff` is met.+///+/// Identity-based: every currently registered router must have acked+/// this partition's freeze. A count comparison would let a stale ack+/// from a departed router (acks are not lease-bound) stand in for a live+/// router that hasn't stashed yet — advancing to Draining while that+/// router still forwards writes to the old owner. Only acks echoing this+/// handoff's id count: an ack left over from a previous handoff of the+/// same partition proves nothing about this one.+///+/// With zero routers there is no traffic to stash, so the freeze quorum+/// is vacuously met. This keeps bootstrap and router-less configurations+/// (e.g. tests exercising only the coordinator+pod) unblocked.+pub fn freeze_quorum_met(+ routers: &[RegisteredRouter],+ freeze_acks: &[RouterFreezeAck],+ handoff: &HandoffState,+) -> bool {+ let acked: HashSet<&str> = freeze_acks+ .iter()+ .filter(|a| a.handoff_id == handoff.handoff_id)+ .map(|a| a.router_name.as_str())+ .collect();+ routers+ .iter()+ .all(|r| acked.contains(r.router_name.as_str()))+}++/// Whether the drain requirement for `handoff` is satisfied.+///+/// "Alive" here means the old owner's etcd registration key still exists+/// (its lease hasn't expired) — not just that it's `Ready`. A `Draining`+/// pod is shutting down gracefully but is still capable of running its+/// handoff handler and writing a `DrainedAck`, and may still have+/// inflight handlers. Bypassing the drain requirement for such a pod+/// would let the coordinator advance to Warming while the old owner is+/// still producing — breaking the protocol's core invariant. Only treat+/// the old owner as drained when its key is genuinely absent, or when it+/// has acked this handoff attempt.+pub fn drain_satisfied(+ registered_pods: &[RegisteredPod],+ drained_acks: &[PodDrainedAck],+ handoff: &HandoffState,+) -> bool {+ match &handoff.old_owner {+ // Defensive: a handoff that reached Draining without an old owner+ // shouldn't exist (Freezing skips Draining when old_owner is+ // None), but if it does, there's nothing to drain.+ None => true,+ Some(name) => {+ let old_owner_present = registered_pods.iter().any(|p| p.pod_name == *name);+ !old_owner_present+ || drained_acks+ .iter()+ .any(|a| a.pod_name == *name && a.handoff_id == handoff.handoff_id)+ }+ }+}++/// Whether the new owner has warmed for this handoff attempt.+pub fn warm_satisfied(warmed_acks: &[PodWarmedAck], handoff: &HandoffState) -> bool {+ warmed_acks+ .iter()+ .any(|a| a.pod_name == handoff.new_owner && a.handoff_id == handoff.handoff_id)+}diff --git a/rust/personhog-coordination/src/types.rs b/rust/personhog-coordination/src/types.rsindex df4fd3e2c2f0..c919b1795671 100644--- a/rust/personhog-coordination/src/types.rs+++ b/rust/personhog-coordination/src/types.rs@@ -119,7 +119,7 @@ pub struct HandoffState {/// - `Warming → Complete`: the new owner has written a `PodWarmedAck`,/// meaning its cache has been populated up to the stable HWM. The/// phase write and the new `PartitionAssignment` happen atomically.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]pub enum HandoffPhase {/// Routers are establishing per-partition stash queues. While in this/// phase, the old owner continues to serve writes — the gate thatdiff --git a/rust/personhog-stateright/Cargo.toml b/rust/personhog-stateright/Cargo.tomlnew file mode 100644index 000000000000..e186b529dfae--- /dev/null+++ b/rust/personhog-stateright/Cargo.toml@@ -0,0 +1,12 @@+[package]+name = "personhog-stateright"+version = "0.1.0"+edition = "2021"+publish = false++[dependencies]+clap = { workspace = true }+stateright = "0.31"++[dependencies.personhog-coordination]+path = "../personhog-coordination"diff --git a/rust/personhog-stateright/README.md b/rust/personhog-stateright/README.mdnew file mode 100644index 000000000000..d41b42acc547--- /dev/null+++ b/rust/personhog-stateright/README.md@@ -0,0 +1,191 @@+# personhog-stateright++Formal verification of the personhog partition handoff protocol using+[Stateright](https://github.com/stateright/stateright), an exhaustive+model checker for distributed systems.++An earlier incarnation of this crate modeled the pre-2026 three-phase+protocol, found its split-brain window, and recommended the+stash-and-release design that evolved into today's production protocol.+This version models the shipped protocol — the four-phase handoff with+identity freeze quorum, ack-to-handoff correlation, and desired-state+pod convergence — and uses the checker to (a) verify the shipped+invariants under every failure interleaving at model scale, (b)+characterize the one accepted residual precisely, and (c) validate the+epoch-fencing design that closes it, before it is built.++## How it works++The entire distributed system — etcd contents, each pod's process+memory, each router's table and stash, the Kafka changelog — is one+plain-data `SystemState`. Every actor behavior and every failure is an+`Action`. The checker explores every reachable state under every+possible interleaving of actions (BFS with state deduplication),+checking every property at every state. A violated safety property+yields the minimal counterexample trace, browsable step by step in a+web explorer.++Configurations are deliberately small — state spaces grow+combinatorially, and protocol bugs are structural, showing up at+minimum viable scale or not at all. Measured sizes (release mode):++| Configuration (writes=2, reads=1) | Unique states | Wall time |+|---|---|---|+| 2 pods / 2 routers / 1 partition, 1 failure | ~26k | 0.2s |+| 2 pods / 2 routers / 1 partition, 2 failures | ~230k | 1.4s |+| 2 pods / 2 routers / 2 partitions, 1 failure | ~900k | 9s |+| 2 pods / 2 routers / 2 partitions, 2 failures | ~8.9M | 110s |+| 3 pods / 2 routers / 2 partitions, 2 failures | ~24M | 300s |++The test suite (twelve scenarios, ~2min total in release) runs the full+verdict matrix — the 1-partition scenarios, the 2-partition cases+including both double-zombie verdicts, the 3-pod rejoin, and the+reachability probes. Two partitions matter for the coordinator's+cross-partition scheduling (rebalancing defers while any handoff is in+flight); the safety invariants themselves are per-partition, which is+why every violation class reproduces at one. The `--ignored`+state-space report is the sizing tool for new configurations.++## Coupling to production (drift prevention)++The protocol's *decision logic* is single-sourced: the model calls the+same functions the coordinator and pods execute, on production-typed+views of the checker state. A change to any of these changes what the+checker verifies, automatically:++| Shared (called directly, cannot drift) | Where it lives |+|---|---|+| `pod::desired_state` + `DesiredState` | the pod's entire state machine — `Action::Converge` derives through the real function |+| `protocol::freeze_quorum_met` / `drain_satisfied` / `warm_satisfied` | the phase-advancement rules (identity quorum, id-correlated acks, vacuous drain) — `Action::AdvancePhase` calls them |+| `protocol::plan_rebalance` | the rebalance decision (placement via `StickyBalancedStrategy` + the move/fresh diff, old_owner from the current assignment) — `Action::Rebalance` calls it, as does the coordinator |+| `types::HandoffPhase` | used directly as the model's phase enum, so adding a phase breaks the model's exhaustive matches at compile time |++What remains model-side is the *environment and effect application* —+what warming does to a cache, what leases and zombies mean, how stashes+queue — mapped to named production behavior for review:++| Model | Production behavior modeled |+|---|---|+| `Action::CleanupStale` | `cleanup_stale_handoffs` (mod_revision-guarded delete, modeled as atomic check-and-delete) |+| `Action::AdvancePhase` Warming→Complete | `complete_handoff` (phase write + assignment flip as one txn) |+| `Action::Converge` effect application | `PodHandle::apply` (warm installs at HWM and unfences, drain fences, acks echo the handoff id and are phase-gated) |+| `Action::Observe` | Router watch handlers: `begin_stash` + FreezeAck (Freezing only), cutover + stash drain at Complete, drain-back on cancellation |+| `Action::ClientWrite` | The raw proxy leader path: stash if stashing, else forward to the table entry; leader admission = warmed + unfenced (`try_begin`) |+| `Action::CrashRestartWithinTtl` | Process death + same-name restart before lease expiry: registration and assignments survive, memory wiped |+| `Action::LeaseExpire` / `SelfFence` | Lease loss with the bounded zombie window before the keepalive self-fences (fix 1); same pair for routers, where lease loss also drops them from the freeze quorum |+| `Changelog.epoch` under `Variant::EpochFenced` | Kafka transactional-producer fencing: warming = `init_transactions`, bumping the broker epoch; stale-epoch produces are rejected before any client ack |++Full elimination of the second table would mean deterministic+simulation — a trait seam over `PersonhogStore` with an in-memory+implementation so the model executes `converge` and+`check_phase_advance` themselves. Held as a possible later investment.++## Properties++| Property | Meaning |+|---|---|+| `no_lost_acked_write` (safety) | No write is acked by a pod after a different designated owner has warmed — i.e. no acked write ever sits beyond the warm HWM of the pod that will serve |+| `no_split_write_acceptance` (safety) | No two pods are simultaneously capable of accepting writes for one partition **and** each reachable via a live, non-stashing router — the real split-brain condition |+| `drained_ack_is_final` (safety) | A pod that wrote a DrainedAck for the current handoff attempt cannot accept another write in that incarnation |+| `some_handoff_completes`, `some_write_accepted` (sanity) | The interesting states are actually reachable |+| `converges_to_stable` (liveness) | Every full run ends quiescent: no handoffs, every partition served warm and unfenced by its sticky target, all live routers agreeing, no stashed traffic |++## Results++| Scenario | `no_lost_acked_write` | `no_split_write_acceptance` | `strong_reads_complete` |+|---|---|---|---|+| Current protocol, no failures | holds | holds | holds |+| Current, crash-restart within TTL / clean lease expiry | holds | holds | holds |+| Current, pod death past TTL + rejoin (3 pods) | holds | holds | holds |+| Current, single zombie pod | **holds** | **holds** | holds |+| Current, double zombie (router + pod) | **violated** — counterexample found | **violated** | — |+| Epoch-fenced, double zombie | holds | holds | holds |+| Current, strong reads + one failure | holds | holds | holds |++Two results worth calling out:++**A single zombie pod is provably safe.** The manual protocol review+treated any zombie pod as the residual risk; the checker refused to+find a counterexample, and the reason is structural: the identity+freeze quorum means every registered router is stashing before the+drain begins, so no live router can route to the zombie after the new+owner warms — and anything the zombie accepts *before* the warm sits+below the warm HWM and is captured. The checker sharpened the+documented residual from "a zombie pod" to "a zombie router feeding a+zombie pod, simultaneously."++**Epoch fencing closes the double zombie.** Under the `EpochFenced`+variant, warming bumps the broker's producer epoch, and the zombie's+produce is rejected before any client ack. This is the design+validation gating the transactional-producer implementation.++**Read stashing was machine-validated before it shipped.** A+direct-read variant of this model (strong reads forwarding to the table+entry even mid-handoff, the pre-#69456 behavior) produced the cutover+race as a counterexample: a slow router serving a strong read from the+old owner's frozen cache after a fast router already delivered writes+to the new owner. With reads parking in the same per-key FIFO as writes+— the shipped design — every property holds under the identical failure+budget. The variant was removed once the change merged, so the model+tracks only the shipped protocol; `strong_reads_complete` remains+checked in every scenario as the standing guarantee.++**Scenario reachability is measured, not assumed.** Two `sometimes`+probes (enabled via the model's `probes` flag) answer "does more scale+open scenarios the small configs can't reach?" with checker facts:+**concurrent handoffs are reachable** (one rebalance transaction creates+a handoff per moved/fresh partition, and safety is verified at every+such state), and **a dual-role pod — drain-side of one handoff while+warm-side of another — is machine-proven unreachable** under the+shipped protocol, even with crash-and-rejoin churn at 3 pods / 3+partitions: 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 it reachable, the probe test fails and the dual-role case needs+explicit analysis. The rejoin scenario runs at 3 pods because that is+the smallest scale where the strategy genuinely chooses a placement+target rather than having it forced — the one axis a 2-pod world+under-exercises; the per-partition safety relations themselves are+two-party (old owner ↔ new owner, zombie ↔ successor).++## Usage++```sh+# Exhaustive checks with expected verdicts per scenario (~2min):+cargo test -p personhog-stateright --release++# State-space sizing report — run when adding a new configuration to+# judge its tractability before wiring it into a test:+cargo test -p personhog-stateright --release -- --ignored --nocapture++# Interactive state-space explorer (http://localhost:3000), for+# stepping through the double-zombie counterexample trace:+cargo run -p personhog-stateright --release -- current-zombie+```++Explorer variants: `current` (failures without zombie windows),+`current-zombie` (the residual, with counterexamples), `epoch-fenced`+(the fix).++## Coverage notes++Now in the explored space: pod rejoin after TTL expiry (at 3 pods, so+placement is genuinely chosen); coordinator concurrency (cleanup,+rebalance, phase advance, and completion cleanup are independently+scheduled actions, which also covers an overlapping outgoing+coordinator — every coordinator write is a guarded+check-on-current-state, so two coordinators are just more interleavings+of the same actions); strong reads (stashing with writes, per the+shipped design); two routers draining stashed FIFOs concurrently at+cutover (thaw ordering); multi-partition rebalance gating; concurrent+handoffs (probed reachable, safety checked throughout); the dual-role+pod shape (probed unreachable — see Results).++Known remaining abstractions: warming is instant and atomic (production+streams from Kafka with retries — availability, not safety); stash+deadlines/bounds are not modeled (availability policies); the+mod_revision cleanup guard is encoded as atomic check-and-delete rather+than itself verified (an unguarded-cleanup variant could demonstrate+its necessity). Full elimination of the environment layer would mean+deterministic simulation behind a `PersonhogStore` trait seam — held as+a later investment.diff --git a/rust/personhog-stateright/src/lib.rs b/rust/personhog-stateright/src/lib.rsnew file mode 100644index 000000000000..a84db41b4001--- /dev/null+++ b/rust/personhog-stateright/src/lib.rs@@ -0,0 +1,2 @@+pub mod model;+pub mod types;diff --git a/rust/personhog-stateright/src/main.rs b/rust/personhog-stateright/src/main.rsnew file mode 100644index 000000000000..9f2082e2ddfc--- /dev/null+++ b/rust/personhog-stateright/src/main.rs@@ -0,0 +1,55 @@+//! Interactive explorer for the handoff-protocol model.+//!+//! ```sh+//! cargo run -p personhog-stateright -- current+//! cargo run -p personhog-stateright -- current-zombie+//! cargo run -p personhog-stateright -- epoch-fenced+//! ```+//!+//! Serves the Stateright web UI at http://localhost:3000 for stepping+//! through counterexample traces state by state.++use clap::{Parser, ValueEnum};++use personhog_stateright::model::{HandoffModel, Variant};+use stateright::Model;++#[derive(Parser)]+struct Args {+ #[arg(value_enum)]+ scenario: Scenario,+}++#[derive(Clone, Copy, Debug, ValueEnum)]+enum Scenario {+ /// Failures without zombie windows.+ Current,+ /// The double-zombie residual, with counterexamples.+ CurrentZombie,+ /// The epoch-fencing fix.+ EpochFenced,+}++fn main() {+ let args = Args::parse();+ let (variant, crashes, zombie_window) = match args.scenario {+ Scenario::Current => (Variant::Current, 1, 0),+ Scenario::CurrentZombie => (Variant::Current, 1, 1),+ Scenario::EpochFenced => (Variant::EpochFenced, 1, 1),+ };++ let model = HandoffModel {+ pods: 2,+ routers: 2,+ partitions: 1,+ variant,+ writes: 2,+ reads: 1,+ crashes,+ rejoins: 0,+ zombie_window,+ probes: false,+ };+ println!("exploring {:?} at http://localhost:3000 …", args.scenario);+ model.checker().serve("localhost:3000");+}diff --git a/rust/personhog-stateright/src/model.rs b/rust/personhog-stateright/src/model.rsnew file mode 100644index 000000000000..929962eee4b7--- /dev/null+++ b/rust/personhog-stateright/src/model.rs@@ -0,0 +1,979 @@+//! Stateright `Model` for the personhog partition handoff protocol.+//!+//! Each action's transition logic mirrors a specific production code path+//! (named in comments) so a divergence between model and code is+//! reviewable line by line. The checker exhaustively interleaves every+//! action from every reachable state and verifies the properties at each.++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,+};+use personhog_coordination::strategy::{AssignmentStrategy, StickyBalancedStrategy};+use personhog_coordination::types::{+ AssignmentStatus, HandoffState, PartitionAssignment, PodDrainedAck, PodStatus, PodWarmedAck,+ RegisteredPod, RegisteredRouter, RouterFreezeAck,+};+use stateright::{Model, Property};++use crate::types::{+ Action, Changelog, Handoff, Partition, Phase, Pod, PodId, Router, RouterId, StashedRequest,+ SystemState, WarmState,+};++/// Deterministic names bridging the model's compact u8 ids to the+/// string-keyed production types.+fn pod_name(x: PodId) -> String {+ format!("p{x}")+}+fn pod_id(name: &str) -> PodId {+ name.trim_start_matches('p').parse().expect("pod name")+}+fn router_name(r: RouterId) -> String {+ format!("r{r}")+}++/// Materialize the production `HandoffState` view of a model handoff, so+/// shared production functions can be called on checker state.+fn production_handoff(p: Partition, h: &Handoff) -> HandoffState {+ HandoffState {+ partition: p as u32,+ old_owner: h.old_owner.map(pod_name),+ new_owner: pod_name(h.new_owner),+ phase: h.phase,+ started_at: 0,+ handoff_id: h.id.to_string(),+ }+}++/// Which produce-path protection the model runs with.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Variant {+ /// The shipped protocol: leases + self-fencing bound the zombie+ /// window but nothing rejects a zombie's produce at the broker.+ Current,+ /// The proposed fix: per-partition Kafka transactional producers.+ /// Warming bumps the broker's producer epoch (`init_transactions`),+ /// and the broker rejects produces bearing a stale epoch.+ EpochFenced,+}++/// Model parameters. Small numbers — state spaces explode; protocol bugs+/// are structural and show up at minimum viable scale.+#[derive(Clone, Debug)]+pub struct HandoffModel {+ pub pods: u8,+ pub routers: u8,+ pub partitions: u8,+ pub variant: Variant,+ /// Total client writes the checker may inject.+ pub writes: u8,+ /// Total strong reads the checker may inject.+ pub reads: u8,+ /// Total failure events (crash-restarts + lease expiries).+ pub crashes: u8,+ /// Times a dead pod may rejoin under its old name.+ pub rejoins: u8,+ /// Writes a lease-expired pod may still accept before its keepalive+ /// self-fences it. Zero disables the zombie window entirely.+ pub zombie_window: u8,+ /// 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+ /// verdict tests: an unreached probe would fail `assert_properties`.+ pub probes: bool,+}++/// Derive one pod's desired state by calling the production+/// `pod::desired_state` on production-typed views of the checker state —+/// the model checks the exact function production executes.+fn model_desired_state(pod: PodId, state: &SystemState, partition: Partition) -> DesiredState {+ let assignment = state+ .assignments+ .get(&partition)+ .map(|owner| PartitionAssignment {+ partition: partition as u32,+ owner: pod_name(*owner),+ status: AssignmentStatus::Active,+ });+ let handoff = state+ .handoffs+ .get(&partition)+ .map(|h| production_handoff(partition, h));+ desired_state(&pod_name(pod), assignment.as_ref(), handoff.as_ref())+}++impl HandoffModel {+ fn pod_ids(&self) -> impl Iterator<Item = PodId> {+ 0..self.pods+ }+ fn router_ids(&self) -> impl Iterator<Item = RouterId> {+ 0..self.routers+ }+ fn partition_ids(&self) -> impl Iterator<Item = Partition> {+ 0..self.partitions+ }++ /// The production `StickyBalancedStrategy`, called on+ /// production-typed views of the checker state — placement logic is+ /// single-sourced with the coordinator.+ fn target_assignments(&self, state: &SystemState) -> HashMap<u32, String> {+ 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();+ StickyBalancedStrategy.compute_assignments(¤t, &active, self.partitions as u32)+ }++ fn target_owner(&self, state: &SystemState, partition: Partition) -> Option<PodId> {+ self.target_assignments(state)+ .get(&(partition as u32))+ .map(|name| pod_id(name))+ }++ /// Whether pod `x` would accept a write for `partition` — the leader+ /// data plane's admission: process serving, partition warmed+ /// (`PartitionNotOwned` otherwise), not write-fenced (`try_begin`),+ /// and under `EpochFenced` the broker additionally rejects produces+ /// whose transactional epoch is stale.+ fn write_capable(&self, state: &SystemState, x: PodId, partition: Partition) -> bool {+ let pod = &state.pods[&x];+ if !pod.running {+ return false;+ }+ // A zombie (lease lost, keepalive not yet fired) keeps serving+ // only within its bounded window.+ if !pod.registered && pod.zombie_writes_left == 0 {+ return false;+ }+ let Some(warm) = pod.warmed.get(&partition) else {+ return false;+ };+ if pod.fenced.contains(&partition) {+ return false;+ }+ match self.variant {+ Variant::Current => true,+ Variant::EpochFenced => warm.epoch == state.changelogs[&partition].epoch,+ }+ }++ /// Serve a strong read at pod `x`, if it can (running, partition+ /// warmed). Sets the staleness flag when the pod's visible prefix+ /// (warm cutoff + own accepted writes) is behind the changelog — the+ /// read returned state missing at least one acked write. Returns+ /// whether the read was served.+ fn serve_read(&self, state: &mut SystemState, x: PodId, partition: Partition) -> bool {+ let pod = &state.pods[&x];+ if !pod.running {+ return false;+ }+ let Some(warm) = pod.warmed.get(&partition) else {+ return false;+ };+ let visible = warm.cutoff.saturating_add(warm.accepted);+ if visible < state.changelogs[&partition].len {+ state.stale_strong_read = true;+ }+ state.reads_served = state.reads_served.saturating_add(1);+ true+ }++ /// Append one acked write to the changelog, tracking the loss flag:+ /// if the protocol has designated a *different* pod as the (incoming+ /// or current) owner and that pod has already warmed, this write sits+ /// beyond its warm cutoff and is invisible to it forever.+ fn accept_write(&self, state: &mut SystemState, x: PodId, partition: Partition) {+ let designated_other = match state.handoffs.get(&partition) {+ Some(h) if h.new_owner != x => state.pods[&h.new_owner].warmed.contains_key(&partition),+ Some(_) => false,+ None => match state.assignments.get(&partition) {+ Some(owner) if *owner != x => state.pods[owner].warmed.contains_key(&partition),+ _ => false,+ },+ };+ if designated_other {+ state.lost_acked_write = true;+ }++ let log = state.changelogs.get_mut(&partition).unwrap();+ log.len = log.len.saturating_add(1);++ let pod = state.pods.get_mut(&x).unwrap();+ if let Some(warm) = pod.warmed.get_mut(&partition) {+ warm.accepted = warm.accepted.saturating_add(1);+ }+ if !pod.registered {+ pod.zombie_writes_left = pod.zombie_writes_left.saturating_sub(1);+ }+ }++ /// Route one write through router `r` exactly as the raw proxy does:+ /// park it if the partition is stashing, otherwise forward to the+ /// table entry and let the leader's admission decide.+ fn route_write(&self, state: &mut SystemState, r: RouterId, partition: Partition) -> bool {+ let router = &state.routers[&r];+ if !router.running {+ return false;+ }+ if router.stashing.contains(&partition) {+ let id = state.next_write_id;+ state.next_write_id += 1;+ state+ .routers+ .get_mut(&r)+ .unwrap()+ .stash+ .entry(partition)+ .or_default()+ .push(StashedRequest::Write(id));+ return true;+ }+ let Some(target) = router.table.get(&partition).copied() else {+ // No route: the request is rejected; nothing changes.+ return false;+ };+ if self.write_capable(state, target, partition) {+ self.accept_write(state, target, partition);+ true+ } else {+ // Rejected fail-closed at the leader; nothing changes.+ false+ }+ }+}++impl Model for HandoffModel {+ type State = SystemState;+ type Action = Action;++ fn init_states(&self) -> Vec<Self::State> {+ let pods: BTreeMap<PodId, Pod> = self+ .pod_ids()+ .map(|id| {+ (+ id,+ Pod {+ registered: true,+ running: true,+ warmed: BTreeMap::new(),+ fenced: BTreeSet::new(),+ zombie_writes_left: 0,+ },+ )+ })+ .collect();+ let routers: BTreeMap<RouterId, Router> = self+ .router_ids()+ .map(|id| {+ (+ id,+ Router {+ registered: true,+ running: true,+ table: BTreeMap::new(),+ stashing: BTreeSet::new(),+ stash: BTreeMap::new(),+ },+ )+ })+ .collect();+ let changelogs: BTreeMap<Partition, Changelog> = self+ .partition_ids()+ .map(|p| (p, Changelog::default()))+ .collect();++ vec![SystemState {+ assignments: BTreeMap::new(),+ handoffs: BTreeMap::new(),+ freeze_acks: BTreeMap::new(),+ drained_acks: BTreeMap::new(),+ warmed_acks: BTreeMap::new(),+ next_handoff_id: 0,+ pods,+ routers,+ changelogs,+ writes_left: self.writes,+ reads_left: self.reads,+ crashes_left: self.crashes,+ rejoins_left: self.rejoins,+ next_write_id: 0,+ reads_served: 0,+ lost_acked_write: false,+ stale_strong_read: false,+ }]+ }++ fn actions(&self, state: &Self::State, actions: &mut Vec<Self::Action>) {+ actions.push(Action::Rebalance);+ for p in self.partition_ids() {+ actions.push(Action::CleanupStale(p));+ actions.push(Action::AdvancePhase(p));+ actions.push(Action::CleanupComplete(p));+ for pod in self.pod_ids() {+ actions.push(Action::Converge(pod, p));+ }+ for r in self.router_ids() {+ actions.push(Action::Observe(r, p));+ if state.writes_left > 0 {+ actions.push(Action::ClientWrite(r, p));+ }+ if state.reads_left > 0 {+ actions.push(Action::ClientStrongRead(r, p));+ }+ }+ }+ if state.crashes_left > 0 {+ for pod in self.pod_ids() {+ actions.push(Action::CrashRestartWithinTtl(pod));+ actions.push(Action::LeaseExpire(pod));+ }+ for r in self.router_ids() {+ actions.push(Action::RouterLeaseExpire(r));+ }+ }+ for pod in self.pod_ids() {+ actions.push(Action::SelfFence(pod));+ if state.rejoins_left > 0 {+ actions.push(Action::Join(pod));+ }+ }+ for r in self.router_ids() {+ actions.push(Action::RouterSelfFence(r));+ }+ }++ fn next_state(&self, last: &Self::State, action: Self::Action) -> Option<Self::State> {+ let mut state = last.clone();+ match action {+ // ── coordinator ────────────────────────────────────+ // The cleanup half of `handle_pod_change_static` for one+ // partition. The mod_revision-guarded delete lets the model+ // treat check-and-delete as atomic; scheduling it freely+ // against Rebalance/AdvancePhase/CleanupComplete covers the+ // concurrency of the pod watch, handoff watch, tick, and an+ // overlapping outgoing coordinator.+ Action::CleanupStale(p) => {+ match state.handoffs.get(&p) {+ Some(h) if !state.pods[&h.new_owner].registered => {}+ _ => return None,+ }+ state.handoffs.remove(&p);+ state.freeze_acks.retain(|(fp, _), _| fp != &p);+ state.drained_acks.retain(|(dp, _), _| dp != &p);+ state.warmed_acks.retain(|(wp, _), _| wp != &p);+ }++ // 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`).+ 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(+ planned.partition as Partition,+ Handoff {+ id,+ old_owner: planned.old_owner.as_deref().map(pod_id),+ new_owner: pod_id(&planned.new_owner),+ phase: Phase::Freezing,+ },+ );+ }+ }+ }++ // Mirror of `check_phase_advance`, with the identity quorum+ // and handoff_id ack correlation.+ Action::AdvancePhase(p) => {+ let h = state.handoffs.get(&p).cloned()?;+ match h.phase {+ Phase::Freezing => {+ // The production quorum predicate on+ // production-typed views: registered routers only+ // (which is what admits the zombie-router half of+ // the double-zombie residual), id-correlated acks,+ // vacuous at zero routers.+ let routers: Vec<RegisteredRouter> = self+ .router_ids()+ .filter(|r| state.routers[r].registered)+ .map(|r| RegisteredRouter {+ router_name: router_name(r),+ registered_at: 0,+ last_heartbeat: 0,+ })+ .collect();+ let acks: Vec<RouterFreezeAck> = self+ .router_ids()+ .filter_map(|r| {+ state.freeze_acks.get(&(p, r)).map(|id| RouterFreezeAck {+ router_name: router_name(r),+ partition: p as u32,+ acked_at: 0,+ handoff_id: id.to_string(),+ })+ })+ .collect();+ if !freeze_quorum_met(&routers, &acks, &production_handoff(p, &h)) {+ return None;+ }+ // Initial assignments (no old owner) skip the+ // drain entirely.+ let next = match h.old_owner {+ None => Phase::Warming,+ Some(_) => Phase::Draining,+ };+ state.handoffs.get_mut(&p).unwrap().phase = next;+ }+ Phase::Draining => {+ let registered: Vec<RegisteredPod> = self+ .pod_ids()+ .filter(|x| state.pods[x].registered)+ .map(|x| RegisteredPod {+ pod_name: pod_name(x),+ generation: String::new(),+ status: PodStatus::Ready,+ registered_at: 0,+ last_heartbeat: 0,+ controller: None,+ })+ .collect();+ let acks: Vec<PodDrainedAck> = self+ .pod_ids()+ .filter_map(|x| {+ state.drained_acks.get(&(p, x)).map(|id| PodDrainedAck {+ pod_name: pod_name(x),+ partition: p as u32,+ acked_at: 0,+ handoff_id: id.to_string(),+ })+ })+ .collect();+ if !drain_satisfied(®istered, &acks, &production_handoff(p, &h)) {+ return None;+ }+ state.handoffs.get_mut(&p).unwrap().phase = Phase::Warming;+ }+ Phase::Warming => {+ let acks: Vec<PodWarmedAck> = self+ .pod_ids()+ .filter_map(|x| {+ state.warmed_acks.get(&(p, x)).map(|id| PodWarmedAck {+ pod_name: pod_name(x),+ partition: p as u32,+ acked_at: 0,+ handoff_id: id.to_string(),+ })+ })+ .collect();+ if !warm_satisfied(&acks, &production_handoff(p, &h)) {+ return None;+ }+ // `complete_handoff`: phase write and assignment+ // flip are one etcd transaction.+ state.handoffs.get_mut(&p).unwrap().phase = Phase::Complete;+ state.assignments.insert(p, h.new_owner);+ }+ Phase::Complete => return None,+ }+ }++ // Mirror of the Complete arm of `handle_handoff_update_static`+ // (guarded delete of the record and its acks).+ Action::CleanupComplete(p) => {+ match state.handoffs.get(&p) {+ Some(h) if h.phase == Phase::Complete => {}+ _ => return None,+ }+ state.handoffs.remove(&p);+ state.freeze_acks.retain(|(fp, _), _| fp != &p);+ state.drained_acks.retain(|(dp, _), _| dp != &p);+ state.warmed_acks.retain(|(wp, _), _| wp != &p);+ }++ // ── pod converge ───────────────────────────────────+ // Mirror of `PodHandle::apply` — one idempotent transition+ // toward the desired state. Startup reconcile after a crash+ // is these same actions running against wiped local state.+ Action::Converge(x, p) => {+ let pod = &state.pods[&x];+ if !pod.running || !pod.registered {+ return None;+ }+ match model_desired_state(x, &state, p) {+ DesiredState::Serving => {+ let pod = &state.pods[&x];+ if !pod.warmed.contains_key(&p) {+ // `warm_partition`: atomic install at the+ // current HWM; unfences. Under EpochFenced,+ // warming is also `init_transactions`, which+ // bumps the broker epoch and fences every+ // earlier producer for the partition.+ let warm = {+ let log = state.changelogs.get_mut(&p).unwrap();+ if self.variant == Variant::EpochFenced {+ log.epoch = log.epoch.wrapping_add(1);+ }+ WarmState {+ epoch: log.epoch,+ cutoff: log.len,+ accepted: 0,+ }+ };+ let pod = state.pods.get_mut(&x).unwrap();+ pod.warmed.insert(p, warm);+ pod.fenced.remove(&p);+ } else if pod.fenced.contains(&p) {+ // `resume_partition`.+ state.pods.get_mut(&x).unwrap().fenced.remove(&p);+ } else {+ return None;+ }+ }+ DesiredState::Drained { ack } => {+ let h_id = state.handoffs[&p].id;+ let pod = state.pods.get_mut(&x).unwrap();+ let newly_fenced = pod.fenced.insert(p);+ // `put_drained_ack`, only while the phase is+ // Draining, echoing the handoff id.+ let ack_needed = ack && state.drained_acks.get(&(p, x)) != Some(&h_id);+ if ack_needed {+ state.drained_acks.insert((p, x), h_id);+ }+ if !newly_fenced && !ack_needed {+ return None;+ }+ }+ DesiredState::Acquiring => {+ let h_id = state.handoffs[&p].id;+ let mut changed = false;+ if !state.pods[&x].warmed.contains_key(&p) {+ let warm = {+ let log = state.changelogs.get_mut(&p).unwrap();+ if self.variant == Variant::EpochFenced {+ log.epoch = log.epoch.wrapping_add(1);+ }+ WarmState {+ epoch: log.epoch,+ cutoff: log.len,+ accepted: 0,+ }+ };+ let pod = state.pods.get_mut(&x).unwrap();+ pod.warmed.insert(p, warm);+ pod.fenced.remove(&p);+ changed = true;+ }+ // `put_warmed_ack`, echoing the handoff id.+ if state.warmed_acks.get(&(p, x)) != Some(&h_id) {+ state.warmed_acks.insert((p, x), h_id);+ changed = true;+ }+ if !changed {+ return None;+ }+ }+ DesiredState::Released => {+ let pod = state.pods.get_mut(&x).unwrap();+ let held = pod.warmed.remove(&p).is_some();+ let fenced = pod.fenced.remove(&p);+ if !held && !fenced {+ return None;+ }+ }+ }+ }++ // ── router ─────────────────────────────────────────+ // Mirror of the routing-table watch handler + stash handler.+ // The router acts on the CURRENT durable state — the same+ // semantics its event handlers converge to, since a late+ // router processes events up to the present (load_initial /+ // anchored watches guarantee it misses nothing).+ Action::Observe(r, p) => {+ {+ let router = &state.routers[&r];+ if !router.registered || !router.running {+ return None;+ }+ }+ let mut changed = false;+ match state.handoffs.get(&p).cloned() {+ Some(h) if h.phase != Phase::Complete => {+ // begin_stash on every non-terminal phase;+ // FreezeAck only while Freezing, echoing the id.+ if state.routers.get_mut(&r).unwrap().stashing.insert(p) {+ changed = true;+ }+ if h.phase == Phase::Freezing+ && state.freeze_acks.get(&(p, r)) != Some(&h.id)+ {+ state.freeze_acks.insert((p, r), h.id);+ changed = true;+ }+ }+ Some(h) => {+ // Complete: cutover the table, then drain the+ // stash to the new owner in FIFO order.+ let router = state.routers.get_mut(&r).unwrap();+ if router.table.get(&p) != Some(&h.new_owner) {+ router.table.insert(p, h.new_owner);+ changed = true;+ }+ if router.stashing.remove(&p) {+ changed = true;+ }+ let parked = state+ .routers+ .get_mut(&r)+ .unwrap()+ .stash+ .remove(&p)+ .unwrap_or_default();+ for entry in parked {+ changed = true;+ match entry {+ StashedRequest::Write(_) => {+ if self.write_capable(&state, h.new_owner, p) {+ self.accept_write(&mut state, h.new_owner, p);+ }+ // Rejected drains surface UNAVAILABLE+ // to the client (never acked).+ }+ StashedRequest::StrongRead => {+ self.serve_read(&mut state, h.new_owner, p);+ }+ }+ }+ }+ None => {+ // No handoff: converge the table to the+ // assignment; a cancellation drains the stash+ // back to the assignment owner.+ let assignment = state.assignments.get(&p).copied();+ let router = state.routers.get_mut(&r).unwrap();+ match assignment {+ Some(owner) => {+ if router.table.get(&p) != Some(&owner) {+ router.table.insert(p, owner);+ changed = true;+ }+ }+ None => {+ if router.table.remove(&p).is_some() {+ changed = true;+ }+ }+ }+ if router.stashing.remove(&p) {+ changed = true;+ }+ let parked = state+ .routers+ .get_mut(&r)+ .unwrap()+ .stash+ .remove(&p)+ .unwrap_or_default();+ for entry in parked {+ changed = true;+ let Some(owner) = assignment else { continue };+ match entry {+ StashedRequest::Write(_) => {+ if self.write_capable(&state, owner, p) {+ self.accept_write(&mut state, owner, p);+ }+ }+ StashedRequest::StrongRead => {+ self.serve_read(&mut state, owner, p);+ }+ }+ }+ }+ }+ if !changed {+ return None;+ }+ }++ // ── workload ───────────────────────────────────────+ Action::ClientWrite(r, p) => {+ if state.writes_left == 0 {+ return None;+ }+ state.writes_left -= 1;+ if !self.route_write(&mut state, r, p) {+ // The write was rejected everywhere — the state may+ // still have changed (budget), keep the transition+ // so rejected paths are explored too.+ }+ }++ Action::ClientStrongRead(r, p) => {+ if state.reads_left == 0 {+ return None;+ }+ state.reads_left -= 1;+ let router = &state.routers[&r];+ if !router.running {+ // Router process gone; request fails at the client.+ } else if router.stashing.contains(&p) {+ // Strong reads park in the same per-partition FIFO as+ // writes while the partition is stashing (the shipped+ // read-stashing design, #69456) — which is what keeps+ // them complete across cutover.+ state+ .routers+ .get_mut(&r)+ .unwrap()+ .stash+ .entry(p)+ .or_default()+ .push(StashedRequest::StrongRead);+ } else if let Some(target) = router.table.get(&p).copied() {+ // Outside a handoff: forward to the table entry.+ // Rejected reads fail closed at the leader.+ self.serve_read(&mut state, target, p);+ }+ }++ // ── failures ───────────────────────────────────────+ Action::Join(x) => {+ let pod = &state.pods[&x];+ if state.rejoins_left == 0 || pod.registered || pod.running {+ return None;+ }+ state.rejoins_left -= 1;+ let pod = state.pods.get_mut(&x).unwrap();+ pod.registered = true;+ pod.running = true;+ pod.warmed.clear();+ pod.fenced.clear();+ pod.zombie_writes_left = 0;+ }+ Action::CrashRestartWithinTtl(x) => {+ let pod = &state.pods[&x];+ if state.crashes_left == 0 || !pod.running || !pod.registered {+ return None;+ }+ state.crashes_left -= 1;+ let pod = state.pods.get_mut(&x).unwrap();+ pod.warmed.clear();+ pod.fenced.clear();+ }+ Action::LeaseExpire(x) => {+ let pod = &state.pods[&x];+ if state.crashes_left == 0 || !pod.registered {+ return None;+ }+ state.crashes_left -= 1;+ let zombie_window = self.zombie_window;+ let pod = state.pods.get_mut(&x).unwrap();+ pod.registered = false;+ if pod.running {+ pod.zombie_writes_left = zombie_window;+ }+ }+ Action::SelfFence(x) => {+ let pod = &state.pods[&x];+ if pod.registered || !pod.running {+ return None;+ }+ let pod = state.pods.get_mut(&x).unwrap();+ pod.running = false;+ pod.warmed.clear();+ pod.fenced.clear();+ pod.zombie_writes_left = 0;+ }+ Action::RouterLeaseExpire(r) => {+ if state.crashes_left == 0 || !state.routers[&r].registered {+ return None;+ }+ state.crashes_left -= 1;+ state.routers.get_mut(&r).unwrap().registered = false;+ }+ Action::RouterSelfFence(r) => {+ let router = &state.routers[&r];+ if router.registered || !router.running {+ return None;+ }+ // The process exits; parked stash requests die with it+ // (their clients get errors — the writes were never+ // acked).+ let router = state.routers.get_mut(&r).unwrap();+ router.running = false;+ router.stashing.clear();+ router.stash.clear();+ }+ }++ if state == *last {+ return None;+ }+ Some(state)+ }++ fn properties(&self) -> Vec<Property<Self>> {+ let mut props = vec![+ // The acked-write-loss invariant the drain/fence/HWM+ // machinery exists to uphold. Expected to FAIL under+ // 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),+ // 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+ // alone is not enough — a zombie pod behind a fully-stashing+ // router fleet can accept nothing, which is exactly why a+ // single zombie is safe and only the double zombie violates+ // this.+ Property::<Self>::always("no_split_write_acceptance", |m, s| {+ m.partition_ids().all(|p| {+ let acceptors: BTreeSet<_> = m+ .router_ids()+ .filter_map(|r| {+ let router = &s.routers[&r];+ if !router.running || router.stashing.contains(&p) {+ return None;+ }+ router.table.get(&p).copied()+ })+ .filter(|x| m.write_capable(s, *x, p))+ .collect();+ acceptors.len() <= 1+ })+ }),+ // A pod that has written a DrainedAck for the current+ // handoff attempt never accepts another write for that+ // partition in the same process incarnation (the ack asserts+ // all its acked writes are durable below the warm HWM).+ Property::<Self>::always("drained_ack_is_final", |m, s| {+ s.drained_acks.iter().all(|((p, x), id)| {+ match s.handoffs.get(p) {+ Some(h) if h.id == *id => !m.write_capable(s, *x, *p),+ // Ack belongs to a finished/cancelled attempt —+ // correlation makes it inert.+ _ => true,+ }+ })+ }),+ // Strong reads reflect every acked write at serve time.+ // This holds because reads stash with writes during handoffs+ // (#69456); before that change, a direct-read variant of this+ // model found the cutover race as a counterexample — the+ // machine validation that motivated shipping read stashing.+ Property::<Self>::always("strong_reads_complete", |_, s| !s.stale_strong_read),+ // Sanity: the interesting states are actually reachable.+ Property::<Self>::sometimes("some_handoff_completes", |_, s| {+ s.handoffs.values().any(|h| h.phase == Phase::Complete)+ }),+ Property::<Self>::sometimes("some_write_accepted", |_, s| {+ s.changelogs.values().any(|log| log.len > 0)+ }),+ Property::<Self>::sometimes("some_strong_read_served", |m, s| {+ // Vacuously discoverable in configs without reads, so+ // `assert_properties` stays usable across the matrix.+ m.reads == 0 || s.reads_served > 0+ }),+ // Liveness: every full run ends quiescent and converged —+ // no handoffs in flight, every assignment served by a warm,+ // unfenced, registered pod, all routers agreeing, nothing+ // parked in a stash.+ Property::<Self>::eventually("converges_to_stable", |m, s| {+ let no_capacity = s.pods.values().all(|p| !p.registered);+ s.handoffs.is_empty()+ && (no_capacity+ || (!s.assignments.is_empty()+ && m.partition_ids().all(|p| {+ let Some(target) = m.target_owner(s, p) else {+ return true;+ };+ let assigned = s.assignments.get(&p) == Some(&target);+ let pod = &s.pods[&target];+ assigned+ && pod.running+ && pod.registered+ && pod.warmed.contains_key(&p)+ && !pod.fenced.contains(&p)+ })))+ && m.router_ids().all(|r| {+ let router = &s.routers[&r];+ if !router.registered || !router.running {+ return true;+ }+ router.stashing.is_empty()+ && router.stash.values().all(|q| q.is_empty())+ && s.assignments+ .iter()+ .all(|(p, owner)| router.table.get(p) == Some(owner))+ })+ }),+ ];+ 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).+ 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.+ props.push(Property::<Self>::sometimes(+ "pod_holds_both_roles",+ |_, s| {+ s.handoffs.values().any(|h1| {+ h1.old_owner+ .is_some_and(|x| s.handoffs.values().any(|h2| h2.new_owner == x))+ })+ },+ ));+ }+ props+ }+}diff --git a/rust/personhog-stateright/src/types.rs b/rust/personhog-stateright/src/types.rsnew file mode 100644index 000000000000..8d3e006c118c--- /dev/null+++ b/rust/personhog-stateright/src/types.rs@@ -0,0 +1,235 @@+//! State types for the personhog handoff-protocol model.+//!+//! Every field maps to a production counterpart (see the README mapping+//! table). The whole distributed system — etcd, coordinator, routers,+//! leader pods, and the Kafka changelog — is one plain-data `SystemState`+//! so the checker can hash, compare, and exhaustively explore it.++use std::collections::{BTreeMap, BTreeSet};++pub type PodId = u8;+pub type RouterId = u8;+pub type Partition = u8;+/// Identity of one handoff attempt — production `HandoffState.handoff_id`.+/// Acks echo it and quorum checks only count matching acks.+pub type HandoffId = u8;+pub type WriteId = u8;++/// The production phase enum, used directly: a new phase added to the+/// protocol breaks the model's exhaustive matches at compile time.+pub use personhog_coordination::types::HandoffPhase as Phase;++/// Production `HandoffState`, in compact model form (u8 ids; the model+/// materializes production-typed views when calling shared logic).+#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub struct Handoff {+ pub id: HandoffId,+ pub old_owner: Option<PodId>,+ pub new_owner: PodId,+ pub phase: Phase,+}++/// Per-partition warm state on a pod — everything the invariants need to+/// know about one warmed partition.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub struct WarmState {+ /// The Kafka transactional-producer epoch held (production:+ /// `init_transactions` under the `EpochFenced` variant; the broker+ /// rejects produces bearing a stale epoch).+ pub epoch: u8,+ /// The changelog HWM captured at warm time — everything below it is+ /// visible to this pod's cache.+ pub cutoff: u8,+ /// Writes this pod itself accepted since warming. `cutoff + accepted`+ /// is the pod's visible prefix of the changelog; a strong read served+ /// while `changelog.len` exceeds it returns stale data.+ pub accepted: u8,+}++/// One leader pod. `registered` is the etcd lease-bound registration key;+/// everything else is process memory and dies with the process.+#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub struct Pod {+ /// The etcd registration key exists (production: lease alive).+ pub registered: bool,+ /// The process is running and its data plane serves requests.+ pub running: bool,+ /// Partitions warmed by this process incarnation (production:+ /// `warmed_partitions` on the pod handle).+ pub warmed: BTreeMap<Partition, WarmState>,+ /// Write-fenced partitions (production: `InflightTracker` fences ++ /// the pod handle's `fenced_partitions`).+ pub fenced: BTreeSet<Partition>,+ /// Remaining writes this pod may accept after losing its lease before+ /// its keepalive notices and the process self-fences (production: the+ /// bounded zombie window; fix 1 bounds it to ~one heartbeat tick).+ pub zombie_writes_left: u8,+}++/// One router. A clean router restart is indistinguishable from a+/// delayed `Observe` (production `load_initial` rebuilds everything from+/// etcd before serving), so restarts need no modeling — but lease expiry+/// does: an unregistered router is excluded from the freeze quorum while+/// its process may keep routing with a stale table until its keepalive+/// self-fences it (the zombie-router half of the double-zombie residual).+#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub struct Router {+ /// The etcd registration key exists (production: lease alive). Only+ /// registered routers count toward the freeze quorum.+ pub registered: bool,+ /// The process is running and forwards traffic.+ pub running: bool,+ /// partition → pod the router forwards to (production: the shared+ /// routing table, edge-updated from handoff Complete events).+ pub table: BTreeMap<Partition, PodId>,+ /// Partitions currently buffering leader-path requests (production:+ /// the `StashTable`).+ pub stashing: BTreeSet<Partition>,+ /// Parked leader-path requests in arrival order (production:+ /// `StashedRequest` queues, which carry their gRPC method so writes+ /// and strong reads share one per-partition FIFO).+ pub stash: BTreeMap<Partition, Vec<StashedRequest>>,+}++/// One parked leader-path request.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub enum StashedRequest {+ Write(WriteId),+ StrongRead,+}++/// The Kafka changelog for one partition, reduced to what the safety+/// invariants need: an append counter (the HWM) and the producer epoch+/// the broker currently accepts.+#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub struct Changelog {+ /// Number of records appended (the HWM).+ pub len: u8,+ /// Broker-side producer epoch. Bumped by each warm under the+ /// `EpochFenced` variant (production: `init_transactions` fencing);+ /// ignored by `Current`.+ pub epoch: u8,+}++/// The entire distributed system. One value = one node in the explored+/// state graph.+#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub struct SystemState {+ // ── durable (etcd) ─────────────────────────────────────────+ /// partition → owning pod (production: `PartitionAssignment`; flips+ /// only atomically with a handoff reaching Complete).+ pub assignments: BTreeMap<Partition, PodId>,+ /// In-flight handoffs, at most one per partition.+ pub handoffs: BTreeMap<Partition, Handoff>,+ /// (partition, router) → handoff id acked (production:+ /// `RouterFreezeAck` with `handoff_id`).+ pub freeze_acks: BTreeMap<(Partition, RouterId), HandoffId>,+ /// (partition, pod) → handoff id acked (production: `PodDrainedAck`).+ pub drained_acks: BTreeMap<(Partition, PodId), HandoffId>,+ /// (partition, pod) → handoff id acked (production: `PodWarmedAck`).+ pub warmed_acks: BTreeMap<(Partition, PodId), HandoffId>,+ /// Monotonic handoff id allocator (production: `new_handoff_id`).+ pub next_handoff_id: HandoffId,++ // ── processes ──────────────────────────────────────────────+ pub pods: BTreeMap<PodId, Pod>,+ pub routers: BTreeMap<RouterId, Router>,++ // ── kafka ──────────────────────────────────────────────────+ pub changelogs: BTreeMap<Partition, Changelog>,++ // ── failure/workload budgets (bound the state space) ───────+ pub writes_left: u8,+ pub reads_left: u8,+ pub crashes_left: u8,+ pub rejoins_left: u8,+ pub next_write_id: WriteId,+ /// Count of strong reads actually served (reachability evidence for+ /// the read properties).+ pub reads_served: u8,++ // ── violation flags (history-free invariant encoding) ──────+ /// Set when a write is acked by a pod while a *different* pod that+ /// the protocol has designated as the (incoming or current) owner+ /// has already warmed — the acked write sits beyond that owner's+ /// 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 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.+ pub stale_strong_read: bool,+}++/// Everything that can happen, from every actor, including failures.+/// The checker interleaves these exhaustively.+#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub enum Action {+ // ── coordinator (pure derivation over etcd state) ──────────+ /// The cleanup half of `handle_pod_change` for one partition:+ /// atomically check-and-delete a handoff whose new owner is+ /// unregistered (the mod_revision guard is what makes modeling this+ /// as atomic faithful). Scheduled independently of `Rebalance` and+ /// `AdvancePhase` — the coordinator's watch handlers and tick run+ /// concurrently in production, and an overlapping outgoing+ /// coordinator is just more interleavings of the same guarded+ /// actions.+ CleanupStale(Partition),+ /// The rebalance half of `handle_pod_change`: when no handoffs are+ /// in flight, create Freezing handoffs for every assignment diff in+ /// one transaction.+ Rebalance,+ /// `check_phase_advance` for one partition (watch nudge or tick).+ AdvancePhase(Partition),+ /// Post-Complete cleanup: delete the handoff record and its acks+ /// (guarded on the record still being the same attempt).+ CleanupComplete(Partition),++ // ── pods (the converge model) ──────────────────────────────+ /// One convergence step for (pod, partition): derive the desired+ /// state from durable state and apply the next transition toward it+ /// (warm / fence+ack / warm+ack / release / unfence).+ Converge(PodId, Partition),++ // ── routers ────────────────────────────────────────────────+ /// The router observes the current durable state of one partition+ /// and reacts: stash+ack during a handoff, cutover+drain at+ /// Complete, drain-back on cancellation. A stale router is modeled+ /// by the checker simply not scheduling this action for a while.+ Observe(RouterId, Partition),++ // ── workload ───────────────────────────────────────────────+ /// A client write for (router, partition): stashes if the router is+ /// stashing, otherwise forwards to the router's table entry.+ ClientWrite(RouterId, Partition),+ /// A strong read for (router, partition): parks with the writes in+ /// the per-partition FIFO when the partition is stashing (the shipped+ /// read-stashing design), otherwise forwards to the table entry.+ ClientStrongRead(RouterId, Partition),++ // ── failures ───────────────────────────────────────────────+ /// The pod process dies and instantly restarts under the same name+ /// before its lease expires: registration and assignments survive,+ /// all process memory (warmed, fenced) is wiped.+ CrashRestartWithinTtl(PodId),+ /// The pod's lease expires while the process is still running: the+ /// registration disappears, but the data plane keeps serving for a+ /// bounded number of writes (the zombie window) until `SelfFence`.+ LeaseExpire(PodId),+ /// The zombie's keepalive notices the dead lease and the process+ /// exits (production fix 1).+ SelfFence(PodId),+ /// A previously-dead pod rejoins under its old name: fresh+ /// registration, fresh lease, empty memory (production: normal pod+ /// startup; its partitions come back via Warming handoffs from the+ /// rebalance its registration triggers).+ Join(PodId),+ /// The router's lease expires while its process keeps running: it+ /// drops out of the freeze quorum but continues routing with its+ /// current table, and stops processing events (its watch loop is on+ /// its way down).+ RouterLeaseExpire(RouterId),+ /// The zombie router's keepalive notices the dead lease and the+ /// process exits (production fix 1).+ RouterSelfFence(RouterId),+}diff --git a/rust/personhog-stateright/tests/model_tests.rs b/rust/personhog-stateright/tests/model_tests.rsnew file mode 100644index 000000000000..a926b5ae8121--- /dev/null+++ b/rust/personhog-stateright/tests/model_tests.rs@@ -0,0 +1,362 @@+//! Exhaustive model-checking runs with the expected verdicts per+//! variant. These are the durable record of what the protocol does and+//! does not guarantee:+//!+//! | scenario | no_lost_acked_write | no_split_acceptance |+//! |------------------------------|---------------------|----------------------|+//! | Current, no failures | holds | holds |+//! | Current, crash/lease loss | holds | holds |+//! | Current, single zombie pod | holds | holds |+//! | Current, double zombie | VIOLATED (residual) | VIOLATED (residual) |+//! | EpochFenced, double zombie | holds | holds |+//!+//! The single-zombie row is a result the checker sharpened beyond what+//! the manual review claimed: a zombie *pod* alone cannot lose an acked+//! write, because the identity freeze quorum has every registered router+//! stashing before the drain (no honest router routes to the zombie+//! post-warm) and anything the zombie accepts pre-warm sits below the+//! warm HWM and is captured. Loss requires the double zombie — a+//! lease-expired router (outside the quorum, stale table) feeding a+//! lease-expired pod. That is the documented residual epoch fencing+//! closes; the checker finds the exact interleaving as a counterexample.++use std::time::Instant;++use personhog_stateright::model::{HandoffModel, Variant};+use stateright::{Checker, Model};++/// Baseline configuration; tests override fields with struct-update+/// syntax. Reads default on so every scenario also exercises the read+/// path under the shipped (stashed) design.+fn base() -> HandoffModel {+ HandoffModel {+ pods: 2,+ routers: 2,+ partitions: 1,+ variant: Variant::Current,+ writes: 2,+ reads: 1,+ crashes: 0,+ rejoins: 0,+ zombie_window: 0,+ probes: false,+ }+}++fn model(variant: Variant, crashes: u8, zombie_window: u8) -> HandoffModel {+ HandoffModel {+ variant,+ crashes,+ zombie_window,+ ..base()+ }+}++/// The shipped protocol with no failures: every safety property holds at+/// every reachable state, the liveness property holds on every full run,+/// and the interesting states are genuinely reachable.+#[test]+fn current_protocol_without_failures_is_safe_and_live() {+ model(Variant::Current, 0, 0)+ .checker()+ .spawn_bfs()+ .join()+ .assert_properties();+}++/// Crash-restart within the lease TTL and clean lease expiry (no zombie+/// data plane): the convergence machinery repairs wiped pod memory and+/// the dead-owner paths reassign, with no safety violation anywhere.+#[test]+fn current_protocol_with_crashes_is_safe_and_live() {+ model(Variant::Current, 1, 0)+ .checker()+ .spawn_bfs()+ .join()+ .assert_properties();+}++/// A single zombie pod is provably safe: the freeze quorum has every+/// registered router stashing before the drain, so nothing routes to the+/// zombie after the new owner warms, and pre-warm zombie writes land+/// below the warm HWM. This is a stronger guarantee than the manual+/// review claimed — found by the checker refusing to produce a+/// counterexample for the weaker claim.+#[test]+fn current_protocol_single_zombie_pod_is_safe() {+ model(Variant::Current, 1, 1)+ .checker()+ .spawn_bfs()+ .join()+ .assert_properties();+}++/// The documented residual, now precisely characterized: a lease-expired+/// router (excluded from the freeze quorum, never stashing, stale table)+/// routes a write to a lease-expired pod (coordination loop dead, never+/// fenced) after the partition's new owner warmed — the write is acked+/// but sits beyond the warm HWM, invisible to the new owner forever.+#[test]+fn current_protocol_double_zombie_loses_acked_writes() {+ let checker = model(Variant::Current, 2, 1).checker().spawn_bfs().join();+ assert!(+ checker.discovery("no_lost_acked_write").is_some(),+ "the double zombie must produce an acked-write-loss counterexample"+ );+ assert!(+ checker.discovery("no_split_write_acceptance").is_some(),+ "the double zombie must produce a dual-capability counterexample"+ );+}++/// Epoch fencing closes the residual: warming bumps the broker's+/// producer epoch, so the zombie's produce is rejected before any ack.+/// All safety properties hold again, zombie window and all.+#[test]+fn epoch_fenced_double_zombie_is_safe() {+ let checker = model(Variant::EpochFenced, 2, 1)+ .checker()+ .spawn_bfs()+ .join();+ assert!(+ checker.discovery("no_lost_acked_write").is_none(),+ "epoch fencing must eliminate acked-write loss"+ );+ assert!(+ checker.discovery("no_split_write_acceptance").is_none(),+ "epoch fencing must restore single-writer capability"+ );+ assert!(+ checker.discovery("drained_ack_is_final").is_none(),+ "a drained ack must remain final under fencing"+ );+}++/// Two partitions bring the cross-partition coordinator logic into+/// play: rebalancing defers while any handoff is in flight, so one+/// partition's failure handling gates the other's reassignment. All+/// safety and liveness properties must still hold, including under a+/// single zombie.+#[test]+fn current_two_partitions_single_zombie_is_safe() {+ HandoffModel {+ partitions: 2,+ crashes: 1,+ zombie_window: 1,+ ..base()+ }+ .checker()+ .spawn_bfs()+ .join()+ .assert_properties();+}++/// A pod that dies past its lease TTL and later rejoins under the same+/// name must come back cleanly: fresh registration triggers a rebalance,+/// partitions return via Warming handoffs, and every safety and liveness+/// property holds across the departure, the interim, and the return.+/// Three pods, deliberately: with two, a departed pod's partition has+/// only one place to go — a third pod is the smallest scale at which the+/// sticky strategy genuinely chooses a target, so the rebalance paths+/// exercised here aren't placement-forced. That is the one axis a 2-pod+/// world under-exercises; the per-partition safety relations themselves+/// are two-party (see the probe tests below).+#[test]+fn current_with_rejoin_is_safe_and_live() {+ HandoffModel {+ pods: 3,+ crashes: 1,+ rejoins: 1,+ ..base()+ }+ .checker()+ .spawn_bfs()+ .join()+ .assert_properties();+}++/// Strong reads park in the same per-partition FIFO as writes while the+/// partition is stashing (#69456), so they drain to the warmed new owner+/// and always reflect every acked write across cutover. Before that+/// change shipped, a direct-read variant of this model produced the+/// cutover-race counterexample under this exact failure budget — the+/// machine validation that motivated it.+#[test]+fn strong_reads_are_complete_across_cutover() {+ HandoffModel {+ writes: 1,+ reads: 1,+ crashes: 1,+ ..base()+ }+ .checker()+ .spawn_bfs()+ .join()+ .assert_properties();+}++/// The double-zombie residual must also reproduce at two partitions —+/// guards against the cross-partition coordinator logic (rebalance+/// deferral, per-partition cleanup) accidentally masking or altering the+/// single-partition verdict.+#[test]+fn two_partitions_double_zombie_loses_acked_writes() {+ let checker = HandoffModel {+ partitions: 2,+ crashes: 2,+ zombie_window: 1,+ ..base()+ }+ .checker()+ .spawn_bfs()+ .join();+ assert!(checker.discovery("no_lost_acked_write").is_some());+}++/// Epoch fencing must close the residual at two partitions too — each+/// partition's producer epoch is independent, and this pins that the+/// fix doesn't rely on single-partition structure.+#[test]+fn epoch_fenced_two_partitions_double_zombie_is_safe() {+ let checker = HandoffModel {+ partitions: 2,+ variant: Variant::EpochFenced,+ crashes: 2,+ zombie_window: 1,+ ..base()+ }+ .checker()+ .spawn_bfs()+ .join();+ assert!(checker.discovery("no_lost_acked_write").is_none());+ assert!(checker.discovery("no_split_write_acceptance").is_none());+}++/// Reachability probe: concurrent handoffs are a real scenario — one+/// rebalance transaction creates a handoff per moved/fresh partition, so+/// the phase machinery is genuinely exercised with multiple handoffs in+/// flight (safety is checked at every such state in the same run).+/// Workload budgets are zero: reachability of coordination shapes+/// doesn't need writes, and the space stays tiny.+#[test]+fn probe_concurrent_handoffs_are_reachable() {+ let checker = HandoffModel {+ partitions: 2,+ writes: 0,+ reads: 0,+ probes: true,+ ..base()+ }+ .checker()+ .spawn_bfs()+ .join();+ assert!(+ checker.discovery("concurrent_handoffs").is_some(),+ "two in-flight handoffs must be reachable (one rebalance txn creates both)"+ );+}++/// 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.+#[test]+fn probe_dual_role_pod_is_unreachable() {+ let checker = HandoffModel {+ pods: 3,+ partitions: 3,+ writes: 0,+ reads: 0,+ crashes: 1,+ rejoins: 1,+ probes: true,+ ..base()+ }+ .checker()+ .spawn_bfs()+ .join();+ assert!(+ checker.discovery("pod_holds_both_roles").is_none(),+ "the sticky strategy + rebalance deferral gate should make dual-role pods unreachable"+ );+}++/// Prints the explored state-space size per configuration. Not a+/// verdict test — run manually to judge config tractability:+/// `cargo test -p personhog-stateright --release -- --ignored --nocapture state_space`+#[test]+#[ignore = "informational; prints state counts"]+fn state_space_report() {+ let configs = [+ (+ "2 pods / 2 routers / 1 partition, w2 c1 z1",+ 2u8,+ 2u8,+ 1u8,+ 2u8,+ 1u8,+ 1u8,+ ),+ (+ "2 pods / 2 routers / 1 partition, w2 c2 z1",+ 2,+ 2,+ 1,+ 2,+ 2,+ 1,+ ),+ (+ "2 pods / 2 routers / 2 partitions, w2 c1 z1",+ 2,+ 2,+ 2,+ 2,+ 1,+ 1,+ ),+ (+ "2 pods / 2 routers / 2 partitions, w2 c2 z1",+ 2,+ 2,+ 2,+ 2,+ 2,+ 1,+ ),+ (+ "3 pods / 2 routers / 2 partitions, w2 c2 z1",+ 3,+ 2,+ 2,+ 2,+ 2,+ 1,+ ),+ ];+ for (label, pods, routers, partitions, writes, crashes, zombie) in configs {+ let start = Instant::now();+ let checker = HandoffModel {+ pods,+ routers,+ partitions,+ writes,+ crashes,+ zombie_window: zombie,+ ..base()+ }+ .checker()+ .spawn_bfs()+ .join();+ println!(+ "{label}: {} unique states, {:?}",+ checker.unique_state_count(),+ start.elapsed()+ );+ }+}