: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): gate serving on a published lease claim (#76169)
Zach Brown5177b56c5959
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.ymlindex 9a76a4e49d1e..1eb6ebe57c50 100644--- a/.github/workflows/ci-rust.yml+++ b/.github/workflows/ci-rust.yml@@ -633,6 +633,10 @@ jobs:# write path's error mapping — ships with no end-to-end# coverage at all.#+ # The gate rides along because startup refuses fencing without+ # it: acquisition moves a partition's broker epoch, and a pod+ # that has stopped renewing has no standing to do that.+ ## Guarded on the flag existing so a branch that predates# --leader-env skips it rather than failing before its own# tests run.@@ -647,18 +651,20 @@ jobs:exit 0fi# The freeze has to outlive the lease, or the woken pod- # still holds a valid claim and the broker fence is- # never asked anything. 27s is the lowest TTL- # validate_fencing_timescales accepts with fencing on- # (the write budget pays the drain's settle slack first),- # so the freeze runs past it and the run is sized to- # leave the woken zombie time to try. The gate asserts- # rejection by consequence (an unfenced landing fails- # the verifier; a crash fails the liveness check), not- # by scraping fence metrics — the deterministic- # fencing_integration tests carry the per-arm coverage.+ # still holds a valid claim and neither the lease gate+ # nor the broker fence is ever asked anything. 27s is+ # the lowest TTL validate_fencing_timescales accepts+ # with fencing on (the write budget pays the drain's+ # settle slack first), so the freeze runs past it and+ # the run is sized to leave the woken zombie time to+ # try. The gate asserts rejection by consequence (an+ # unfenced landing fails the verifier; a crash fails+ # the liveness check), not by scraping fence metrics —+ # the deterministic fencing_integration tests carry the+ # per-arm coverage../target/debug/personhog-test-harness gate \--leader-env KAFKA_TRANSACTIONAL_FENCING=true \+ --leader-env LEASE_GATED_AUTHORITY=true \--leaders 3 --partitions 8 --persons 100 --concurrency 10 --duration 45s \--leader-lease-ttl 27 \--zombie-after 5s --zombie-duration 32s \diff --git a/rust/personhog-coordination/Cargo.toml b/rust/personhog-coordination/Cargo.tomlindex d84705fe9d61..c83b99d0e2e9 100644--- a/rust/personhog-coordination/Cargo.toml+++ b/rust/personhog-coordination/Cargo.toml@@ -19,6 +19,14 @@ tokio-util = { version = "0.7", features = ["rt"] }tracing = { workspace = true }uuid = { workspace = true }++[features]+# States the tests need to construct but that no production caller may+# reach — an authority clock whose renewals stopped long enough ago to+# have lapsed, which otherwise takes a real wait to reproduce.+# Consumed by personhog-leader's dev-dependency on this crate.+test-support = []+[dev-dependencies]k8s-openapi = { version = "0.24", features = ["latest"] }kube = { version = "0.98", features = ["client"] }diff --git a/rust/personhog-coordination/README.md b/rust/personhog-coordination/README.mdindex e8d77984d1f2..c6fd12735c93 100644--- a/rust/personhog-coordination/README.md+++ b/rust/personhog-coordination/README.md@@ -87,10 +87,11 @@ Several failure modes are handled explicitly:**The double-zombie residual — status by half.** A lease-expired router (excluded from the freeze quorum, still routing on a stale table) feeding a lease-expired pod (coordination loop dead, never fenced) can ack a write after the partition's new owner warmed; the write lands beyond the warm HWM, invisible to the new owner forever. Both zombie windows are bounded by lease self-fencing to roughly one heartbeat tick, so the loss needs both to coincide — but nothing rejects the zombie's produce at the broker. The stateright model reproduces the exact interleaving (`current_protocol_double_zombie_loses_acked_writes`) and machine-validates the fix (`Variant::EpochFenced`). Where each piece stands, one bullet per residual:-- **Zombie writes: closed here, behind `KAFKA_TRANSACTIONAL_FENCING` (default off).** A partition's owner acquires its transactional id before the warm read, so a predecessor that missed its drain is fenced at the broker and its produce fails instead of landing. Changelog consumers read `read_committed`, so aborted windows are never visible. The guarantee binds per binary, not per flag flip: a pod still running the old build produces non-transactionally and no epoch can fence it, so enable the flag only once the whole fleet is on a build that carries it — which the default-off flag and enable-after-rollout ordering already encode.-- **Zombie reads: open on this branch.** Fencing rejects a zombie's writes, not its reads: a zombie pod whose coordination loop is wedged keeps answering strong reads from a cache the new owner is already mutating, and the model still reports `strong_reads_complete` violated under the double zombie with fencing on. Closing it needs a lease-validity check on read admission — the keepalive publishing its last confirmed renewal, and the read path refusing once that stamp is older than the renewal margin. The model confirms the two are complementary rather than alternative: with a read gate but no fencing, stale reads persist because the *legitimate* owner is the one missing the zombie's lost write.-- **Acquisition is not gated on holding the lease — the reason this flag must not be enabled from this branch alone.** A zombie waking inside its lease window re-acquires the partition's transactional id on its way to noticing it is dead, which fences the legitimate owner: the broker grants the epoch to whoever initializes last, not to whoever the protocol says owns the partition. The legitimate owner's writes then bounce until a handoff moves the partition. The e2e zombie gate reproduces this. The same lease-validity publication that closes the stale-read half also gates acquisition; both ship on the stacked lease-validity branch, which additionally refuses `KAFKA_TRANSACTIONAL_FENCING` at startup without the gate. Enable the flag only with both branches deployed.-- **A condemned producer stays down until a restart or handoff, on this branch.** 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 — but nothing on this branch re-acquires in place; the serving-side re-acquisition ships with the stacked branch, gated on the authority stamp that gives it standing.+- **Zombie writes: closed behind `KAFKA_TRANSACTIONAL_FENCING` (default off).** A partition's owner acquires its transactional id before the warm read, so a predecessor that missed its drain is fenced at the broker and its produce fails instead of landing. Changelog consumers read `read_committed`, so aborted windows are never visible. The guarantee binds per binary, not per flag flip: a pod still running the old build produces non-transactionally and no epoch can fence it, so enable the flag only once the whole fleet is on a build that carries it — which the default-off flag and enable-after-rollout ordering already encode.+- **Zombie reads: closed behind `LEASE_GATED_AUTHORITY` (default off).** The keepalive publishes its last confirmed renewal and the request path refuses once that stamp is older than the renewal margin — checked at admission and again before answering, since the claim can lapse while a read is served. A stalled keepalive therefore fences implicitly. The model confirms fencing and the gate are complementary rather than alternative: each alone leaves stale reads; only together does every safety property hold.+ - *Residual, recorded because the model's `serve_read` points here:* the closure is only as prompt as the claim's lapse. Natural expiry always lapses the stamp before etcd deletes anything, but an out-of-band *revocation* removes the registration while the stamp is still fresh, and only the deliberately best-effort registration watch converts that into an immediate surrender. With the watch dead, the stamp stays valid for up to one heartbeat (`prompt_detection_is_what_makes_the_read_gate_hold` pins exactly this). No production path revokes another pod's lease, so reaching the window takes an operator.+- **Acquisition is gated on the same claim.** A zombie waking inside its lease window would otherwise re-acquire the partition's transactional id on its way to noticing it is dead, fencing the legitimate owner — the broker grants the epoch to whoever initializes last. Warming and resume consult the authority stamp before acquiring and again after, dropping the fence rather than building on a claim they no longer hold. The e2e zombie gate manufactures the waking-zombie shape and asserts by consequence; the per-arm rejection coverage lives in the deterministic fencing integration tests. Because the two mechanisms only work together, `KAFKA_TRANSACTIONAL_FENCING` is refused at startup without `LEASE_GATED_AUTHORITY`.+- **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.- **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.diff --git a/rust/personhog-coordination/src/authority.rs b/rust/personhog-coordination/src/authority.rsnew file mode 100644index 000000000000..3589def761c5--- /dev/null+++ b/rust/personhog-coordination/src/authority.rs@@ -0,0 +1,291 @@+//! Serving authority, published for the data plane to consult.+//!+//! A pod's right to serve a partition rests on its etcd lease. The+//! keepalive already detects loss and self-fences, but that detection is+//! itself a running task: a process that is stopped, starved, or wedged+//! stops renewing *and* stops noticing, and keeps answering requests out+//! of a cache the new owner is already mutating. A fence nobody is alive+//! to apply is not a fence.+//!+//! So the keepalive publishes rather than only reacts. It stamps this+//! clock on every confirmed renewal; the request path compares the stamp+//! against now and refuses once the lease could have expired at etcd. A+//! stalled keepalive then fences implicitly — the stamp simply stops+//! advancing — and the guarantee no longer depends on the liveness of+//! the component whose failure it exists to survive.+//!+//! The margin is the same two thirds of the TTL the keepalive uses to+//! declare loss, and stamps are anchored at the instant the renewal was+//! *sent* — before etcd could have restarted its countdown — so the+//! stamp always ages faster than the lease. Together those place the+//! refusal strictly before the moment the coordinator could treat the+//! lease as expired and hand the partition to someone else. Requests+//! are therefore refused while ownership is still merely *doubtful*,+//! ahead of it becoming wrong.++use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};+use std::time::{Duration, Instant};++/// A lease-backed claim to serve, readable from the request path.+///+/// Cheap by construction: publishing is one relaxed atomic store on the+/// keepalive's path, and checking is one load plus a comparison, so the+/// hot path pays no lock and no syscall.+#[derive(Debug)]+pub struct AuthorityClock {+ /// Fixed origin for the millisecond stamps below; `Instant` is not+ /// representable in an atomic, and absolute time would drag wall+ /// clock skew into a purely local measurement.+ origin: Instant,+ /// Milliseconds since `origin` at the last confirmed renewal.+ confirmed_ms: AtomicU64,+ /// How long a stamp stays good — the keepalive's renewal margin,+ /// in milliseconds. Supplied by the session rather than at+ /// construction: the lease TTL is coordination's business, and the+ /// data plane holding this handle should not have to know it, let+ /// alone agree with it. Zero until the first session claims it,+ /// which reads as no authority.+ margin_ms: AtomicU64,+ /// Set when authority is known to be gone, which is stronger than a+ /// stale stamp and never recovers within this session.+ surrendered: AtomicBool,+}++impl AuthorityClock {+ /// A clock holding no authority yet.+ ///+ /// Constructed once per process and shared: the data plane can hold+ /// it from startup and read it without coordinating with whichever+ /// session happens to be current. Before the first lease is granted+ /// it reads as invalid, which is the right answer for a pod that has+ /// not registered.+ pub fn unclaimed() -> Self {+ Self {+ origin: Instant::now(),+ confirmed_ms: AtomicU64::new(0),+ margin_ms: AtomicU64::new(0),+ surrendered: AtomicBool::new(true),+ }+ }++ /// Claim authority for a newly granted lease.+ ///+ /// A session boundary is deliberately a reset rather than a fresh+ /// object: the data plane holds one handle for the life of the+ /// process, so a new claim has to be expressible through the handle+ /// it already has.+ /// `granted_at` is when the lease's countdown started at the server,+ /// which is earlier than this call by however long the grant and+ /// registration took. Anchoring on it rather than on now keeps a slow+ /// registration from silently extending the first window — the same+ /// reasoning the keepalive applies to its own first deadline.+ ///+ /// The stores are ordered so every torn view fails closed: until the+ /// final `surrendered` flip a reader refuses outright, and the+ /// Release/Acquire pair on that flag makes the margin and stamp+ /// written above visible to any reader that observes it cleared —+ /// so no interleaving can pair the new claim with the old session's+ /// numbers.+ pub fn begin_session(&self, margin: Duration, granted_at: Instant) {+ self.margin_ms+ .store(margin.as_millis() as u64, Ordering::Relaxed);+ self.confirm_at(granted_at);+ self.surrendered.store(false, Ordering::Release);+ }++ /// The keepalive's renewal margin for a lease TTL: two thirds,+ /// leaving the final third for the fence to land before the+ /// coordinator can act on the expiry.+ ///+ /// The single definition of that fraction. The keepalive's own+ /// deadline, the pod's heartbeat assertion, and this clock all read+ /// it from here, because a data plane that stopped serving at a+ /// different point than the keepalive declares loss would mean one+ /// of the two is wrong.+ pub fn renewal_margin(lease_ttl: i64) -> Duration {+ Duration::from_secs(lease_ttl.max(0) as u64).mul_f64(2.0 / 3.0)+ }++ /// Record a confirmed renewal. Called by the keepalive, and only by+ /// the keepalive: a renewal is the one event that proves the lease+ /// was alive at a known instant.+ ///+ /// `at` is when the renewal was *sent*, not when the response+ /// arrived. etcd restarts the lease countdown when it processes the+ /// request, which is after the send and before the receipt — so the+ /// send instant is the latest moment guaranteed not to overstate how+ /// much lease is left. Stamping receipt would let a slow round keep+ /// the claim valid past the lease's actual expiry.+ pub fn confirm(&self, at: Instant) {+ self.confirm_at(at);+ }++ /// Record a renewal confirmed at a known instant.+ fn confirm_at(&self, at: Instant) {+ self.confirmed_ms.store(+ at.saturating_duration_since(self.origin).as_millis() as u64,+ Ordering::Relaxed,+ );+ }++ /// Give up authority permanently for this session. Lease loss is+ /// authoritative in a way a stale stamp is not, so it latches.+ pub fn surrender(&self) {+ self.surrendered.store(true, Ordering::Relaxed);+ }++ /// Whether this pod may still act as the partition owner.+ ///+ /// The Acquire pairs with `begin_session`'s Release: a reader that+ /// sees the surrender cleared also sees that session's margin and+ /// stamp. The remaining Relaxed loads are safe because every stale+ /// view they can produce — an old stamp, a zero margin — reads as+ /// invalid.+ pub fn is_valid(&self) -> bool {+ if self.surrendered.load(Ordering::Acquire) {+ return false;+ }+ self.since_confirmed() < self.margin()+ }++ /// How long since the last confirmed renewal — the number the+ /// request path is really asking about, exposed for metrics and for+ /// error messages that have to explain a refusal.+ pub fn since_confirmed(&self) -> Duration {+ let confirmed = Duration::from_millis(self.confirmed_ms.load(Ordering::Relaxed));+ self.origin.elapsed().saturating_sub(confirmed)+ }++ pub fn margin(&self) -> Duration {+ Duration::from_millis(self.margin_ms.load(Ordering::Relaxed))+ }++ /// Whether authority was given up outright, as opposed to merely+ /// aging out. The two are different operational events — one is a+ /// drain or a lease loss the operator expects, the other is a+ /// keepalive that stopped running — and reporting them under one+ /// name makes the second invisible among the first.+ pub fn is_surrendered(&self) -> bool {+ self.surrendered.load(Ordering::Relaxed)+ }++ /// A clock whose last confirmed renewal is `age` old.+ ///+ /// The stamp is stored relative to a fixed origin, so a test cannot+ /// age it by writing to it — it would have to go below the origin,+ /// and `confirm_at` saturates there. Ageing the origin is the only+ /// way to express "renewals stopped this long ago" without sleeping+ /// through the margin, and a sleep long enough to be reliable on a+ /// loaded runner is long enough to slow every run.+ #[cfg(any(test, feature = "test-support"))]+ pub fn stale_for(margin: Duration, age: Duration) -> Self {+ let now = Instant::now();+ Self {+ origin: now.checked_sub(age).unwrap_or(now),+ confirmed_ms: AtomicU64::new(0),+ margin_ms: AtomicU64::new(margin.as_millis() as u64),+ surrendered: AtomicBool::new(false),+ }+ }++ /// Whether any session has claimed this clock yet. Before the first+ /// grant there is no margin to compare against, so age is not a+ /// meaningful reading.+ pub fn is_claimed(&self) -> bool {+ self.margin_ms.load(Ordering::Relaxed) > 0+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn granted(margin: Duration) -> AuthorityClock {+ let clock = AuthorityClock::unclaimed();+ clock.begin_session(margin, Instant::now());+ clock+ }++ /// A pod that has not registered holds nothing, and must not serve+ /// on the strength of a clock that merely has not aged out yet.+ #[test]+ fn an_unclaimed_clock_is_invalid() {+ assert!(!AuthorityClock::unclaimed().is_valid());+ }++ #[test]+ fn a_fresh_grant_is_valid() {+ assert!(granted(Duration::from_secs(20)).is_valid());+ }++ /// A pod that loses its lease and registers again is serving under a+ /// new claim; the handle the data plane holds has to carry that.+ #[test]+ fn a_new_session_restores_surrendered_authority() {+ let clock = granted(Duration::from_secs(20));+ clock.surrender();+ assert!(!clock.is_valid());+ clock.begin_session(Duration::from_secs(20), Instant::now());+ assert!(clock.is_valid());+ }++ /// The stamp honors the instant the caller anchors it at — the+ /// renewal's send — rather than when the confirmation call happens.+ /// Stamping at the call would credit the round-trip delay to the+ /// lease and keep the claim valid past the lease's actual expiry.+ #[test]+ fn a_confirmation_is_anchored_at_its_send_not_its_receipt() {+ let margin = Duration::from_secs(8);+ let clock = AuthorityClock::stale_for(margin, Duration::from_secs(20));+ // A renewal whose response only just arrived, but which was sent+ // ten seconds ago — longer than the margin. Anchoring at the+ // call instead of the send would revalidate the claim here.+ let sent = Instant::now()+ .checked_sub(Duration::from_secs(10))+ .expect("test instants are boot-relative");+ clock.confirm(sent);+ assert!(+ !clock.is_valid(),+ "a renewal sent 10s ago must not back an 8s margin, however \+ recently its response arrived"+ );+ clock.confirm(Instant::now());+ assert!(clock.is_valid(), "a fresh send backs the margin");+ }++ /// The point of the clock: authority lapses on its own once renewals+ /// stop, with nothing running to notice they have.+ ///+ /// Anchored in the past rather than slept through — `begin_session`+ /// takes the instant the lease's countdown started precisely so a+ /// caller can say "this session is already old", and a sleep would+ /// make the test a race against a loaded runner for no added+ /// coverage.+ #[test]+ fn authority_lapses_without_renewal() {+ let margin = Duration::from_secs(20);+ let clock = AuthorityClock::stale_for(margin, margin + Duration::from_secs(1));+ assert!(!clock.is_valid());+ }++ #[test]+ fn a_confirmed_renewal_extends_authority() {+ let margin = Duration::from_secs(20);+ let clock = AuthorityClock::stale_for(margin, margin + Duration::from_secs(1));+ assert!(!clock.is_valid(), "stale before the renewal");++ clock.confirm(Instant::now());+ assert!(clock.is_valid(), "the renewal should have moved the stamp");+ }++ /// Lease loss is final for the session: a renewal cannot arrive+ /// afterwards, and treating one as valid would resurrect a claim the+ /// coordinator has already reassigned.+ #[test]+ fn surrendered_authority_never_returns() {+ let clock = granted(Duration::from_secs(20));+ clock.surrender();+ clock.confirm(Instant::now());+ assert!(!clock.is_valid());+ }+}diff --git a/rust/personhog-coordination/src/coordinator.rs b/rust/personhog-coordination/src/coordinator.rsindex 37042b2be4c8..a1f0c8758c52 100644--- a/rust/personhog-coordination/src/coordinator.rs+++ b/rust/personhog-coordination/src/coordinator.rs@@ -234,6 +234,9 @@ impl Coordinator {lease_ttl,granted_at,"coordinator",+ // The coordinator serves no partition data; there is+ // no request path to gate on its lease.+ None,token.clone(),));let failure = match inner.await {diff --git a/rust/personhog-coordination/src/lib.rs b/rust/personhog-coordination/src/lib.rsindex a40ab89cbd1e..d0f696f6182e 100644--- a/rust/personhog-coordination/src/lib.rs+++ b/rust/personhog-coordination/src/lib.rs@@ -1,3 +1,4 @@+pub mod authority;pub mod coordinator;pub mod error;pub mod hash;diff --git a/rust/personhog-coordination/src/pod.rs b/rust/personhog-coordination/src/pod.rsindex d4e5aad286d8..89fa6adf2e9b 100644--- a/rust/personhog-coordination/src/pod.rs+++ b/rust/personhog-coordination/src/pod.rs@@ -18,6 +18,7 @@ use assignment_coordination::store::parse_watch_value;use k8s_awareness::types::{ControllerKind, ControllerRef};use k8s_awareness::{DepartureReason, K8sAwareness};+use crate::authority::AuthorityClock;use crate::error::{Error, Result};use crate::store::{self, PersonhogStore};use crate::types::{@@ -127,6 +128,25 @@ pub trait HandoffHandler: Send + Sync {/// released: the pod only tracks a warm once this returns.async fn warm_partition(&self, partition: u32) -> Result<()>;+ /// Owner: confirm this pod still holds whatever a partition needs in+ /// order to serve it, and re-take anything missing.+ ///+ /// Called on every convergence to `Serving`, including reconcile+ /// ticks, so it is the repair path for state the handoff protocol has+ /// no way back from — the leader uses it to re-take a changelog fence+ /// evicted by a broker rejection or lost to a failed abort. Running+ /// under `Serving` is what makes it safe: the pod re-takes only what+ /// the durable assignment says it owns, rather than what its local+ /// caches happen to still hold.+ ///+ /// Idempotent and cheap when nothing is missing, since it runs+ /// per-partition on every tick.+ /// Returns whether repair work was applied, so the convergence can+ /// count it as progress.+ async fn verify_serving(&self, _partition: u32) -> Result<bool> {+ Ok(false)+ }+/// Old owner: release the partition from this pod's local state (drop cache,/// close consumers, etc.).///@@ -248,18 +268,25 @@ pub struct PodHandle {/// not reflect lost ownership, so the run supervisor must not retry/// in place — only a process restart clears this.fence_poisoned: AtomicBool,+ /// This pod's claim to serve, shared with the data plane and reset+ /// at each lease grant. Reads as invalid until the first grant.+ authority: Arc<AuthorityClock>,/// Optional K8s awareness for departure classification during shutdown.k8s_awareness: Option<Arc<K8sAwareness>>,}impl PodHandle {+ #[allow(clippy::too_many_arguments)]pub fn new(store: Arc<PersonhogStore>,config: PodConfig,handler: Arc<dyn HandoffHandler>,k8s_awareness: Option<Arc<K8sAwareness>>,+ // Shared with the data plane, which holds it from process start+ // and consults it per request.+ authority: Arc<AuthorityClock>,) -> Self {- let renewal_margin = Duration::from_secs(config.lease_ttl.max(0) as u64).mul_f64(2.0 / 3.0);+ let renewal_margin = AuthorityClock::renewal_margin(config.lease_ttl);assert!(config.heartbeat_interval < renewal_margin,"heartbeat_interval ({:?}) must be well under the keepalive renewal margin \@@ -277,10 +304,17 @@ impl PodHandle {drain_notify: Notify::new(),warm_slots,fence_poisoned: AtomicBool::new(false),+ authority,k8s_awareness,}}+ /// This pod's claim to serve, for the data plane to consult on the+ /// request path. Invalid until the first lease is granted.+ pub fn authority(&self) -> Arc<AuthorityClock> {+ Arc::clone(&self.authority)+ }+/// Run the pod's coordination, supervised at two levels so a/// failure costs exactly the authority it invalidates and nothing/// more. The **session** level owns the lease: grant, register,@@ -339,15 +373,59 @@ impl PodHandle {// session split exists to close. It keeps running through the// drain phase too, so the coordinator sees a Draining pod// rather than a crashed one.+ // A new lease is a new claim: reset the shared clock rather+ // than replacing it, so the data plane's handle carries the+ // new session without re-plumbing.+ self.authority.begin_session(+ AuthorityClock::renewal_margin(self.config.lease_ttl),+ granted_at,+ );++ // The keepalive learns of a revoked lease on its next round,+ // which is up to a heartbeat away — and in that window the+ // coordinator has already seen the deletion and can reassign,+ // warm a successor, and let it start accepting writes while+ // this pod still answers reads from a cache that is no longer+ // the truth. Watching our own registration collapses that+ // window to a watch delivery.+ //+ // Deliberately best-effort: it accelerates detection, it does+ // not own it. If the stream never establishes or dies, the+ // keepalive's margin remains the guarantee, exactly as before.let heartbeat_cancel = CancellationToken::new();+ let registration_cancel = CancellationToken::new();+ let registration_watch = {+ let store = Arc::clone(&self.store);+ let authority = Arc::clone(&self.authority);+ let pod_name = self.config.pod_name.clone();+ let token = registration_cancel.child_token();+ // Ending the session is the keepalive's job, so the watch+ // ends it the same way rather than inventing a second+ // path: stopping the heartbeat makes the attempt loop+ // take the lease-loss branch it already has, which+ // fences, releases, and registers anew.+ let end_session = heartbeat_cancel.clone();+ tokio::spawn(async move {+ watch_own_registration(store, pod_name, authority, end_session, token).await;+ })+ };+let mut heartbeat_handle = {let store = Arc::clone(&self.store);let interval = self.config.heartbeat_interval;let lease_ttl = self.config.lease_ttl;let token = heartbeat_cancel.child_token();+ let authority = Arc::clone(&self.authority);tokio::spawn(async move {util::run_lease_keepalive(- store, lease_id, interval, lease_ttl, granted_at, "pod", token,+ store,+ lease_id,+ interval,+ lease_ttl,+ granted_at,+ "pod",+ Some(authority),+ token,).await})@@ -480,6 +558,16 @@ impl PodHandle {"pre-revoke self-fence failed; refusing in-place recovery");}+ // Only now do we stop being the owner. On this path the+ // lease is still alive and the registration still stands:+ // surrendering before the drain would refuse reads the+ // protocol deliberately keeps serving — the old owner's+ // cache is the latest state right up to cutover — while+ // the coordinator, seeing a live owner, reassigns+ // nothing.+ self.authority.surrender();+ registration_cancel.cancel();+ drop(registration_watch.await);heartbeat_cancel.cancel();drop(heartbeat_handle.await);drop(self.store.revoke_lease(lease_id).await);@@ -494,6 +582,15 @@ impl PodHandle {// expiry, and a fence still draining past it loses the// race it exists to win. Overshoot poisons, and the// process restart clears stragglers by death.+ // Authority is already gone, so stop serving as the owner+ // before the drain rather than after it: the coordinator+ // may be reassigning right now, and a drain can take+ // seconds. A stale stamp merely expires; lease loss is a+ // fact that must not be undone by a renewal racing in+ // behind us, which is why this latches.+ self.authority.surrender();+ registration_cancel.cancel();+ drop(registration_watch.await);let runway = Duration::from_secs(self.config.lease_ttl.max(0) as u64) / 3;if let Err(e) = self.self_fence_locally(runway.min(self.config.drain_timeout))@@ -506,6 +603,21 @@ impl PodHandle {"local self-fence failed; refusing in-place recovery");}+ // Usually the lease is already dead here and this is a+ // dropped error. The registration watch also lands on+ // this branch when the key was deleted out from under a+ // live lease (an operator `del`, not a revoke) — without+ // this, that lease would sit alive and unreferenced for+ // its full TTL while the next session grants a second+ // one. Strictly after the self-fence and bounded: this+ // is cleanup, an unhealthy etcd is the usual reason for+ // being on this branch, and the store has no request+ // timeouts of its own — unbounded it could hold up the+ // fence or the next session for as long as the outage.+ drop(+ tokio::time::timeout(Duration::from_secs(5), self.store.revoke_lease(lease_id))+ .await,+ );}if let Some(e) = fatal {@@ -943,6 +1055,13 @@ impl PodHandle {.insert(partition, WarmProvenance::Serving);did_work = true;}+ // Whatever the branch above did, the pod is meant to be+ // serving this partition now — so let the handler repair+ // anything it needs and no longer has. Repair applied is+ // progress like any other applied work.+ if self.handler.verify_serving(partition).await? {+ did_work = true;+ }// Resume any local fence regardless of which branch ran:// a crash-restart inside the TTL can leave a partition// fenced but unwarmed (re-fenced through the Drained arm@@ -951,6 +1070,7 @@ impl PodHandle {// admission depend on an undocumented handler side// effect. Resuming after a warm that already unfenced is// an idempotent no-op.+ //// Clear the local record only once the handler has// actually resumed: `resume_partition` can fail (it may// re-take broker-side state), and forgetting the fence@@ -1334,6 +1454,93 @@ enum Trigger {Reconcile,}+/// Surrender the moment this pod's own registration disappears.+///+/// A lease revoked or expired out from under a pod deletes its keys+/// immediately, but the pod only learns on its next keepalive round.+/// The coordinator sees the deletion at once and can reassign inside+/// that gap, so the pod can be answering reads from a cache the new+/// owner is already changing. This closes the gap to a watch delivery.+///+/// It is an accelerator, not the guarantee: a stream that never+/// establishes, or dies, simply leaves detection to the keepalive margin+/// as before, which is why nothing here retries or escalates.+async fn watch_own_registration(+ store: Arc<PersonhogStore>,+ pod_name: String,+ authority: Arc<AuthorityClock>,+ end_session: CancellationToken,+ cancel: CancellationToken,+) {+ // Establishment is raced against the token just like the stream+ // reads below: the session teardown joins this task, so an etcd call+ // stalling here would otherwise hold up the join — and behind it the+ // self-fence — for as long as the stall lasts.+ let revision = tokio::select! {+ _ = cancel.cancelled() => return,+ revision = store.current_revision() => match revision {+ Ok(revision) => revision,+ Err(e) => {+ tracing::warn!(pod = %pod_name, error = %e, "registration watch unavailable");+ return;+ }+ },+ };+ let mut stream = tokio::select! {+ _ = cancel.cancelled() => return,+ stream = store.watch_pods_from(revision + 1) => match stream {+ Ok(stream) => stream,+ Err(e) => {+ tracing::warn!(pod = %pod_name, error = %e, "registration watch unavailable");+ return;+ }+ },+ };+ let registration_key = store.pod_registration_key(&pod_name);+ loop {+ let message = tokio::select! {+ _ = cancel.cancelled() => return,+ message = stream.message() => message,+ };+ let Ok(Some(response)) = message else { return };+ for event in response.events() {+ if event.event_type() != EventType::Delete {+ continue;+ }+ // Exactly the key `register` writes — this is a prefix+ // watch, and matching anything looser (say, a final path+ // segment) would let an unrelated deletion under the prefix+ // cost this pod its session.+ let deleted_us = event+ .kv()+ .and_then(|kv| from_utf8(kv.key()).ok())+ .is_some_and(|key| key == registration_key);+ if deleted_us {+ counter!("personhog_coordination_registration_deleted_total").increment(1);+ tracing::error!(+ pod = %pod_name,+ "registration deleted; surrendering serving authority immediately"+ );+ // Deliberately redundant: the session teardown below+ // surrenders too, so deleting this line leaves every+ // test green. What it buys is the interval — the pod+ // stops answering on the watch event rather than+ // whenever teardown finishes, and until it does it is+ // serving strong reads on a claim the cluster has+ // already withdrawn. The residual gap is etcd's watch+ // delivery latency, which no call can close.+ authority.surrender();+ // Surrendering alone would leave a pod that holds a live+ // lease, refuses every read, and never registers again —+ // silently idle with nothing to escalate. Ending the+ // session is what puts it back to work.+ end_session.cancel();+ return;+ }+ }+ }+}+#[cfg(test)]mod tests {use super::*;diff --git a/rust/personhog-coordination/src/routing_table.rs b/rust/personhog-coordination/src/routing_table.rsindex a914b55e6781..0151e0ab468a 100644--- a/rust/personhog-coordination/src/routing_table.rs+++ b/rust/personhog-coordination/src/routing_table.rs@@ -12,6 +12,7 @@ use tokio_util::sync::CancellationToken;use assignment_coordination::store::parse_watch_value;+use crate::authority::AuthorityClock;use crate::error::{Error, Result};use crate::store::{self, PersonhogStore};use crate::types::{HandoffPhase, HandoffState, RegisteredPod, RegisteredRouter, RouterFreezeAck};@@ -286,7 +287,7 @@ pub struct RoutingTable {impl RoutingTable {pub fn new(store: Arc<PersonhogStore>, config: RoutingTableConfig) -> Self {- let renewal_margin = Duration::from_secs(config.lease_ttl.max(0) as u64).mul_f64(2.0 / 3.0);+ let renewal_margin = AuthorityClock::renewal_margin(config.lease_ttl);assert!(config.heartbeat_interval < renewal_margin,"heartbeat_interval ({:?}) must be well under the keepalive renewal margin \@@ -494,7 +495,7 @@ impl RoutingTable {let token = cancel.child_token();tasks.spawn(async move {util::run_lease_keepalive(- store, lease_id, interval, lease_ttl, granted_at, "router", token,+ store, lease_id, interval, lease_ttl, granted_at, "router", None, token,).await});diff --git a/rust/personhog-coordination/src/store.rs b/rust/personhog-coordination/src/store.rsindex f4b4402540da..858c9ef7ec45 100644--- a/rust/personhog-coordination/src/store.rs+++ b/rust/personhog-coordination/src/store.rs@@ -99,6 +99,13 @@ impl PersonhogStore {Ok(self.inner.put(&key, pod, Some(lease_id)).await?)}+ /// The exact key `register_pod` writes for a pod, for watchers that+ /// must match their own registration and nothing else under the+ /// prefix.+ pub fn pod_registration_key(&self, pod_name: &str) -> String {+ self.key(StoreKey::Pod(pod_name))+ }+pub async fn get_pod(&self, pod_name: &str) -> Result<Option<RegisteredPod>> {let key = self.key(StoreKey::Pod(pod_name));Ok(self.inner.get(&key).await?)diff --git a/rust/personhog-coordination/src/util.rs b/rust/personhog-coordination/src/util.rsindex 679101619c57..afd0fde01ece 100644--- a/rust/personhog-coordination/src/util.rs+++ b/rust/personhog-coordination/src/util.rs@@ -2,12 +2,13 @@ use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Arc;use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};-use metrics::counter;+use metrics::{counter, histogram};use tokio_util::sync::CancellationToken;use uuid::Uuid;pub use assignment_coordination::util::{now_millis, now_seconds};+use crate::authority::AuthorityClock;use crate::error::{Error, Result};use crate::store::PersonhogStore;@@ -85,11 +86,13 @@ pub(crate) fn note_run_failure(/// must fence *now* so the fence completes inside the final third,/// before the coordinator can possibly treat the lease as expired./// Retrying past the margin would win availability on a coin flip and-/// split-brain on the other face. The margin clock starts at response-/// receipt — strictly after the server reset its own countdown — so the-/// local measurement is conservative, and every await in the loop is+/// split-brain on the other face. The margin clock is anchored at each+/// renewal's *send* — the server restarts its countdown only after+/// that, when it processes the request — so the local measurement never+/// overstates how much lease is left, and every await in the loop is/// bounded by the time left so a hang can never defer the verdict past/// the moment the fence must begin.+#[allow(clippy::too_many_arguments)]pub async fn run_lease_keepalive(store: Arc<PersonhogStore>,lease_id: i64,@@ -97,9 +100,13 @@ pub async fn run_lease_keepalive(lease_ttl: i64,granted_at: Instant,component: &'static str,+ // Published on every confirmed renewal, so the data plane can judge+ // its own authority without depending on this task being alive to+ // tell it. `None` for components that serve nothing.+ authority: Option<Arc<AuthorityClock>>,cancel: CancellationToken,) -> Result<()> {- let renewal_margin = Duration::from_secs(lease_ttl.max(0) as u64).mul_f64(2.0 / 3.0);+ let renewal_margin = AuthorityClock::renewal_margin(lease_ttl);// `clamp` panics when min > max, and sub-250ms intervals are// constructible from zero-valued env config; floor the pace instead.let retry_pace = (interval / 4)@@ -161,6 +168,12 @@ pub async fn run_lease_keepalive(if left.is_zero() {return Err(margin_exhausted());}+ // The renewal is anchored at its send: etcd restarts the+ // lease countdown when it processes the request, which can+ // only be after this instant, so measuring age from here+ // never overstates how much lease is left. Anchoring at the+ // response would credit the round-trip delay to the lease.+ let sent = Instant::now();let round = async {keeper.keep_alive().await?;match stream.message().await? {@@ -180,7 +193,23 @@ pub async fn run_lease_keepalive())),};match outcome {- Ok(true) => last_renewed = Instant::now(),+ Ok(true) => {+ // The gap between confirmations is the headroom+ // question in one number: how close routine+ // operation runs to the margin at which a pod stops+ // being able to vouch for what it serves. Recorded+ // whether or not anything is gating on it, so the+ // distribution is known before it is enforced.+ histogram!(+ "personhog_coordination_lease_renewal_interval_ms",+ "component" => component+ )+ .record(last_renewed.elapsed().as_secs_f64() * 1000.0);+ last_renewed = sent;+ if let Some(authority) = &authority {+ authority.confirm(sent);+ }+ }// Authoritative: the lease is gone, no margin applies.Ok(false) => return Err(Error::leadership_lost()),Err(e) => {diff --git a/rust/personhog-coordination/tests/common/mod.rs b/rust/personhog-coordination/tests/common/mod.rsindex a1505bf7e7da..b9498bbe9ab3 100644--- a/rust/personhog-coordination/tests/common/mod.rs+++ b/rust/personhog-coordination/tests/common/mod.rs@@ -1,5 +1,6 @@#![allow(dead_code)]+use personhog_coordination::authority::AuthorityClock;use std::collections::{HashMap, HashSet};use std::future::{pending, Future};use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};@@ -203,6 +204,7 @@ pub fn start_pod_with_address(},Arc::new(handler),None,+ Arc::new(AuthorityClock::unclaimed()),);let token = cancel.child_token();let join_handle = tokio::spawn(async move { pod.run(token).await });@@ -285,6 +287,7 @@ pub fn start_pod_with_flaky_resume(},Arc::new(handler),None,+ Arc::new(AuthorityClock::unclaimed()),);let token = cancel.child_token();let join_handle = tokio::spawn(async move { pod.run(token).await });@@ -367,6 +370,7 @@ pub fn start_pod_with_flaky_release(},Arc::new(handler),None,+ Arc::new(AuthorityClock::unclaimed()),);let token = cancel.child_token();let join_handle = tokio::spawn(async move { pod.run(token).await });@@ -453,6 +457,7 @@ pub fn start_pod_with_stuck_drain(},Arc::new(handler),None,+ Arc::new(AuthorityClock::unclaimed()),);let token = cancel.child_token();let join_handle = tokio::spawn(async move { pod.run(token).await });@@ -533,6 +538,7 @@ pub fn start_pod_with_hanging_drain(},Arc::new(handler),None,+ Arc::new(AuthorityClock::unclaimed()),);let token = cancel.child_token();let join_handle = tokio::spawn(async move { pod.run(token).await });@@ -614,6 +620,7 @@ pub fn start_pod_with_failing_release(},Arc::new(handler),None,+ Arc::new(AuthorityClock::unclaimed()),);let token = cancel.child_token();let join_handle = tokio::spawn(async move { pod.run(token).await });@@ -649,6 +656,7 @@ pub fn start_pod_blocking(},Arc::new(handler),None,+ Arc::new(AuthorityClock::unclaimed()),);let token = cancel.child_token();let join_handle = tokio::spawn(async move { pod.run(token).await });@@ -718,6 +726,7 @@ pub fn start_pod_slow(},Arc::new(handler),None,+ Arc::new(AuthorityClock::unclaimed()),);let token = cancel.child_token();let join_handle = tokio::spawn(async move { pod.run(token).await });@@ -1109,6 +1118,7 @@ pub fn start_pod_gated(},Arc::new(handler),None,+ Arc::new(AuthorityClock::unclaimed()),);let token = cancel.child_token();let join_handle = tokio::spawn(async move { pod.run(token).await });diff --git a/rust/personhog-coordination/tests/k3s_integration.rs b/rust/personhog-coordination/tests/k3s_integration.rsindex 3761250ffe4c..906124c7f266 100644--- a/rust/personhog-coordination/tests/k3s_integration.rs+++ b/rust/personhog-coordination/tests/k3s_integration.rs@@ -1,3 +1,4 @@+use personhog_coordination::authority::AuthorityClock;mod common;use std::collections::BTreeMap;@@ -395,7 +396,13 @@ fn start_pod_k8s(cancel: CancellationToken,) -> (Arc<Mutex<Vec<HandoffEvent>>>, JoinHandle<Result<()>>) {let (handler, events) = MockHandler::new();- let pod = PodHandle::new(store, config, Arc::new(handler), k8s_awareness);+ let pod = PodHandle::new(+ store,+ config,+ Arc::new(handler),+ k8s_awareness,+ Arc::new(AuthorityClock::unclaimed()),+ );let token = cancel.child_token();let handle = tokio::spawn(async move { pod.run(token).await });(events, handle)diff --git a/rust/personhog-coordination/tests/protocol_hardening.rs b/rust/personhog-coordination/tests/protocol_hardening.rsindex 14e82ade80df..f8b603d56555 100644--- a/rust/personhog-coordination/tests/protocol_hardening.rs+++ b/rust/personhog-coordination/tests/protocol_hardening.rs@@ -7,6 +7,7 @@//! All tests run against a real etcd at localhost:2379 with per-test key//! prefixes, matching the conventions in `integration.rs`.+use personhog_coordination::authority::AuthorityClock;mod common;use std::collections::HashMap;@@ -2126,6 +2127,7 @@ async fn a_pod_attempt_failure_preserves_registration_and_partitions() {},Arc::new(handler),None,+ Arc::new(AuthorityClock::unclaimed()),);let token = cancel.child_token();tokio::spawn(async move { pod.run(token).await });@@ -2794,6 +2796,7 @@ async fn lease_loss_during_attempt_backoff_self_fences_promptly() {},Arc::new(handler),None,+ Arc::new(AuthorityClock::unclaimed()),);let token = cancel.child_token();tokio::spawn(async move { pod.run(token).await });@@ -2851,6 +2854,7 @@ async fn lease_loss_during_graceful_drain_self_fences_promptly() {},Arc::new(handler),None,+ Arc::new(AuthorityClock::unclaimed()),);let token = cancel.child_token();let join = tokio::spawn(async move { pod.run(token).await });@@ -2931,6 +2935,7 @@ async fn a_connection_blip_does_not_fence_the_pod() {},Arc::new(handler),None,+ Arc::new(AuthorityClock::unclaimed()),);let token = cancel.child_token();tokio::spawn(async move { pod.run(token).await });@@ -2990,6 +2995,7 @@ async fn a_sustained_outage_fences_at_the_renewal_margin() {},Arc::new(handler),None,+ Arc::new(AuthorityClock::unclaimed()),);let token = cancel.child_token();tokio::spawn(async move { pod.run(token).await });@@ -3058,6 +3064,7 @@ async fn progress_between_failures_keeps_the_run_alive() {},Arc::new(handler),None,+ Arc::new(AuthorityClock::unclaimed()),);let token = cancel.child_token();tokio::spawn(async move { pod.run(token).await });@@ -3117,6 +3124,7 @@ async fn budget_exhaustion_fences_before_deregistering() {},Arc::new(handler),None,+ Arc::new(AuthorityClock::unclaimed()),);let token = cancel.child_token();let join = tokio::spawn(async move { pod.run(token).await });@@ -3191,6 +3199,357 @@ async fn pod_retries_resume_after_a_failed_attempt() {cancel.cancel();}+/// The authority clock is what the data plane reads to decide whether it+/// may still answer as a partition's owner, so it has to lapse on the+/// strength of missing renewals alone — no coordination task has to run+/// for it to become invalid. This severs etcd and watches the claim+/// expire while the process is otherwise perfectly healthy.+#[tokio::test]+async fn authority_lapses_when_renewals_stop() {+ let proxy = FlakyProxy::start("127.0.0.1:2379").await;+ let prefix = format!("/test-authority-lapse-{}/", uuid::Uuid::new_v4());+ let pod_store = store_at(&proxy.endpoint, &prefix).await;++ let cancel = CancellationToken::new();+ let (handler, events) = MockHandoffHandler::new();+ let authority = Arc::new(AuthorityClock::unclaimed());+ // TTL 9 puts the renewal margin at 6s, so the lapse is observable+ // well inside the test's patience.+ let pod = personhog_coordination::pod::PodHandle::new(+ Arc::clone(&pod_store),+ personhog_coordination::pod::PodConfig {+ pod_name: "lapse-pod".to_string(),+ lease_ttl: 9,+ heartbeat_interval: Duration::from_secs(1),+ reconcile_interval: Duration::from_secs(86_400),+ ..Default::default()+ },+ Arc::new(handler),+ None,+ Arc::clone(&authority),+ );+ let token = cancel.child_token();+ tokio::spawn(async move { pod.run(token).await });++ let store = store_at(ETCD_ENDPOINT, &prefix).await;+ put_handoff(&store, 0, None, "lapse-pod", HandoffPhase::Warming).await;+ wait_for_event(&events, HandoffEvent::Warmed(0)).await;+ assert!(+ authority.is_valid(),+ "a registered pod renewing normally must hold authority"+ );++ // A reconnectable blip must not cost the pod its claim: the lease is+ // alive in etcd and the keepalive rebuilds its stream. Waiting past+ // the renewal margin (6s at this TTL) is what makes the assertion+ // mean something — surviving it requires renewals to have been+ // confirmed *and* published through the rebuilt stream, not merely+ // the stamp taken when the session began.+ proxy.sever();+ tokio::time::sleep(Duration::from_secs(8)).await;+ assert!(+ authority.is_valid(),+ "authority must survive a blip the keepalive can ride out, on the strength of \+ renewals published through the rebuilt stream"+ );++ // Now a real outage: new connections are refused too, so no renewal+ // can be confirmed however hard the keepalive tries.+ proxy.set_blackholed(true);+ proxy.sever();++ // Past the renewal margin, nothing confirms the lease any more.+ //+ // This deliberately does not assert *how* the claim went: with a+ // keepalive still running, the stamp ages out and the keepalive+ // declares lease loss at the same margin — they are the same+ // fraction of the same TTL — so surrender and staleness coincide and+ // no assertion here can separate them. The case where they diverge+ // is a keepalive that is not running at all, which no amount of+ // network fault injection produces, and which+ // `authority_lapses_without_renewal` covers directly against the+ // clock.+ wait_for_condition(Duration::from_secs(15), POLL_INTERVAL, || {+ let authority = Arc::clone(&authority);+ async move { !authority.is_valid() }+ })+ .await;++ // And it must have *surrendered*, not merely aged out. With etcd+ // dark the registration watch dies without seeing a deletion, so the+ // only thing that can set this is the lease-loss branch giving the+ // claim up before it drains — which is what stops the pod acking+ // writes for a partition the coordinator may already be reassigning.+ assert!(+ authority.is_surrendered(),+ "losing the lease must give the claim up, not just let it go stale"+ );++ cancel.cancel();+}++/// A lease revoked out from under a pod deletes its registration at once,+/// but the keepalive only learns on its next round — and the coordinator,+/// which sees the deletion immediately, can reassign inside that gap. The+/// pod must stop claiming ownership on the deletion, not a heartbeat+/// later.+#[tokio::test]+async fn authority_is_surrendered_when_the_registration_is_deleted() {+ let prefix = format!("/test-registration-delete-{}/", uuid::Uuid::new_v4());+ let store = store_at(ETCD_ENDPOINT, &prefix).await;++ let cancel = CancellationToken::new();+ let (handler, events) = MockHandoffHandler::new();+ let authority = Arc::new(AuthorityClock::unclaimed());+ // A long heartbeat is the point: without the watch, nothing would+ // notice for this long, and the test would time out.+ let pod = personhog_coordination::pod::PodHandle::new(+ Arc::clone(&store),+ personhog_coordination::pod::PodConfig {+ pod_name: "revoked-pod".to_string(),+ lease_ttl: 60,+ heartbeat_interval: Duration::from_secs(20),+ reconcile_interval: Duration::from_secs(86_400),+ ..Default::default()+ },+ Arc::new(handler),+ None,+ Arc::clone(&authority),+ );+ let token = cancel.child_token();+ tokio::spawn(async move { pod.run(token).await });++ put_handoff(&store, 0, None, "revoked-pod", HandoffPhase::Warming).await;+ wait_for_event(&events, HandoffEvent::Warmed(0)).await;+ assert!(authority.is_valid(), "a registered pod holds authority");++ revoke_lease_of_key(&format!("{prefix}pods/revoked-pod")).await;++ wait_for_condition(Duration::from_secs(10), POLL_INTERVAL, || {+ let authority = Arc::clone(&authority);+ async move { !authority.is_valid() }+ })+ .await;+ // The margin here is forty seconds, so nothing could have aged out in+ // ten — this is the watch giving the claim up on the deletion.+ assert!(+ authority.is_surrendered(),+ "a deleted registration must surrender the claim, not wait for it to lapse"+ );++ cancel.cancel();+}++/// A deleted registration must put the pod back to work, not just stop+/// it serving.+///+/// Surrendering alone would leave a pod holding a live lease, refusing+/// every read, and never registering again — idle with nothing to+/// escalate. Ending the session is what makes it re-register and take+/// partitions back.+#[tokio::test]+async fn a_deleted_registration_starts_a_new_session() {+ let prefix = format!("/test-registration-resession-{}/", uuid::Uuid::new_v4());+ let store = store_at(ETCD_ENDPOINT, &prefix).await;++ let cancel = CancellationToken::new();+ let (handler, events) = MockHandoffHandler::new();+ let authority = Arc::new(AuthorityClock::unclaimed());+ let pod = personhog_coordination::pod::PodHandle::new(+ Arc::clone(&store),+ personhog_coordination::pod::PodConfig {+ pod_name: "resession-pod".to_string(),+ lease_ttl: 60,+ // Long enough that the keepalive cannot be what notices.+ heartbeat_interval: Duration::from_secs(20),+ reconcile_interval: Duration::from_secs(86_400),+ ..Default::default()+ },+ Arc::new(handler),+ None,+ Arc::clone(&authority),+ );+ let token = cancel.child_token();+ tokio::spawn(async move { pod.run(token).await });++ put_handoff(&store, 0, None, "resession-pod", HandoffPhase::Warming).await;+ wait_for_event(&events, HandoffEvent::Warmed(0)).await;++ revoke_lease_of_key(&format!("{prefix}pods/resession-pod")).await;++ // The pod must come back: a fresh session re-registers and claims+ // authority again.+ let check = Arc::clone(&store);+ wait_for_condition(Duration::from_secs(20), POLL_INTERVAL, || {+ let store = Arc::clone(&check);+ let authority = Arc::clone(&authority);+ async move {+ let registered = store+ .list_pods()+ .await+ .map(|pods| pods.iter().any(|p| p.pod_name == "resession-pod"))+ .unwrap_or(false);+ registered && authority.is_valid()+ }+ })+ .await;++ cancel.cancel();+}++/// The watch is a prefix watch, so it sees every deletion under+/// `pods/`. Only the pod's own registration key may cost it the session+/// — matching anything looser (say, a final path segment) would let an+/// unrelated key deletion release and re-warm every partition the pod+/// holds.+#[tokio::test]+async fn a_foreign_deletion_under_the_pods_prefix_does_not_cost_the_session() {+ let prefix = format!("/test-registration-foreign-{}/", uuid::Uuid::new_v4());+ let store = store_at(ETCD_ENDPOINT, &prefix).await;++ let cancel = CancellationToken::new();+ let (handler, events) = MockHandoffHandler::new();+ let authority = Arc::new(AuthorityClock::unclaimed());+ let pod = personhog_coordination::pod::PodHandle::new(+ Arc::clone(&store),+ personhog_coordination::pod::PodConfig {+ pod_name: "exact-pod".to_string(),+ lease_ttl: 60,+ // Long enough that only the watch could be reacting.+ heartbeat_interval: Duration::from_secs(20),+ reconcile_interval: Duration::from_secs(86_400),+ ..Default::default()+ },+ Arc::new(handler),+ None,+ Arc::clone(&authority),+ );+ let token = cancel.child_token();+ tokio::spawn(async move { pod.run(token).await });++ put_handoff(&store, 0, None, "exact-pod", HandoffPhase::Warming).await;+ wait_for_event(&events, HandoffEvent::Warmed(0)).await;++ // A key under the prefix whose final segment matches the pod's name,+ // but which is not its registration.+ let mut raw = etcd_client::Client::connect([common::ETCD_ENDPOINT], None)+ .await+ .expect("connect raw etcd client");+ let decoy = format!("{prefix}pods/decoy/exact-pod");+ raw.put(decoy.as_str(), "{}", None)+ .await+ .expect("put decoy");+ raw.delete(decoy.as_str(), None)+ .await+ .expect("delete decoy");++ // The deletion must pass through the watch without costing the+ // session: no release, and the claim stays standing. The window is a+ // bounded observation, long enough for the watch to have delivered+ // the decoy event many times over.+ let observe_until = std::time::Instant::now() + Duration::from_millis(1_500);+ while std::time::Instant::now() < observe_until {+ assert!(+ authority.is_valid(),+ "an unrelated deletion under the prefix must not surrender the claim"+ );+ assert!(+ !events.lock().await.contains(&HandoffEvent::Released(0)),+ "an unrelated deletion under the prefix must not end the session"+ );+ tokio::time::sleep(POLL_INTERVAL).await;+ }++ // And the watch must still be live and exact: deleting the real+ // registration ends the session.+ raw.delete(format!("{prefix}pods/exact-pod").as_str(), None)+ .await+ .expect("delete the registration");+ wait_for_event(&events, HandoffEvent::Released(0)).await;++ cancel.cancel();+}++/// A registration deleted out from under a live lease (an operator+/// `del`, not a revoke) lands the pod on the lease-loss branch with the+/// lease still standing. The branch must revoke it: otherwise the next+/// session grants a second lease while the first sits alive and+/// unreferenced for its full TTL.+#[tokio::test]+async fn an_operator_delete_of_a_live_registration_revokes_its_lease() {+ let prefix = format!("/test-registration-operator-del-{}/", uuid::Uuid::new_v4());+ let store = store_at(ETCD_ENDPOINT, &prefix).await;++ let cancel = CancellationToken::new();+ let (handler, events) = MockHandoffHandler::new();+ let authority = Arc::new(AuthorityClock::unclaimed());+ let pod = personhog_coordination::pod::PodHandle::new(+ Arc::clone(&store),+ personhog_coordination::pod::PodConfig {+ pod_name: "operator-del-pod".to_string(),+ // Long enough that an unrevoked lease would outlive the test+ // by a wide margin — the assertion below can only pass+ // because the branch revoked it.+ lease_ttl: 60,+ heartbeat_interval: Duration::from_secs(20),+ reconcile_interval: Duration::from_secs(86_400),+ ..Default::default()+ },+ Arc::new(handler),+ None,+ Arc::clone(&authority),+ );+ let token = cancel.child_token();+ tokio::spawn(async move { pod.run(token).await });++ put_handoff(&store, 0, None, "operator-del-pod", HandoffPhase::Warming).await;+ wait_for_event(&events, HandoffEvent::Warmed(0)).await;++ let key = format!("{prefix}pods/operator-del-pod");+ let mut raw = etcd_client::Client::connect([common::ETCD_ENDPOINT], None)+ .await+ .expect("connect raw etcd client");+ let resp = raw.get(key.as_str(), None).await.expect("get registration");+ let orphaned_lease = resp.kvs().first().expect("registration exists").lease();+ assert_ne!(orphaned_lease, 0, "the registration is lease-backed");++ // The operator's `del`: the key goes, the lease stays.+ raw.delete(key.as_str(), None)+ .await+ .expect("delete the registration");++ // The pod notices via the watch, takes the lease-loss branch, and+ // must revoke the now-orphaned lease on its way to a new session.+ wait_for_condition(Duration::from_secs(15), POLL_INTERVAL, || {+ let mut raw = raw.clone();+ async move {+ raw.lease_time_to_live(orphaned_lease, None)+ .await+ .map(|resp| resp.ttl() <= 0)+ .unwrap_or(false)+ }+ })+ .await;++ // And the new session is live on a fresh lease.+ let check = Arc::clone(&store);+ wait_for_condition(Duration::from_secs(20), POLL_INTERVAL, || {+ let store = Arc::clone(&check);+ let authority = Arc::clone(&authority);+ async move {+ let registered = store+ .list_pods()+ .await+ .map(|pods| pods.iter().any(|p| p.pod_name == "operator-del-pod"))+ .unwrap_or(false);+ registered && authority.is_valid()+ }+ })+ .await;++ cancel.cancel();+}+/// A drain that cannot quiesce must not keep the pod serving everything/// else it no longer owns.///diff --git a/rust/personhog-leader/Cargo.toml b/rust/personhog-leader/Cargo.tomlindex 2de039cce3ad..0c91c865aacb 100644--- a/rust/personhog-leader/Cargo.toml+++ b/rust/personhog-leader/Cargo.toml@@ -47,6 +47,7 @@ uuid = { workspace = true }test-support = [][dev-dependencies]+personhog-coordination = { path = "../personhog-coordination", features = ["test-support"] }health = { path = "../common/health" }personhog-leader = { path = ".", features = ["test-support"] }tokio = { workspace = true, features = ["test-util"] }diff --git a/rust/personhog-leader/src/config.rs b/rust/personhog-leader/src/config.rsindex 72b1c61cae8d..7b8f090ce2d4 100644--- a/rust/personhog-leader/src/config.rs+++ b/rust/personhog-leader/src/config.rs@@ -4,6 +4,7 @@ use std::time::Duration;use common_kafka::config::KafkaConfig;use envconfig::Envconfig;+use personhog_coordination::authority::AuthorityClock;#[derive(Envconfig, Clone)]pub struct Config {@@ -293,6 +294,13 @@ pub struct Config {#[envconfig(default = "")]pub k8s_namespace: String,+ /// Refuse strong reads and fence acquisition once this pod's lease+ /// may have expired, instead of serving until the keepalive notices.+ /// Trades availability during an etcd outage for never answering as+ /// an owner the protocol may already have replaced.+ #[envconfig(default = "false")]+ pub lease_gated_authority: bool,+#[envconfig(default = "30")]pub lease_ttl: i64,@@ -331,13 +339,13 @@ pub const FENCING_COMMIT_ATTEMPTS: u32 = 2;/// How many times a window's abort is attempted in total.////// One, deliberately. An abort that does not land leaves the producer in-/// a state it cannot begin another transaction from — which is a-/// condemned fence, given up on the next write and re-taken by a fresh-/// acquisition, whose `init_transactions` aborts the pending transaction-/// at the broker as a side effect. Retrying the abort is therefore a-/// slower, less reliable version of a recovery that already exists, and-/// it is not free: every attempt is bounded by the transaction timeout-/// and has to fit the same runway.+/// a state it cannot begin another transaction from — which is now a+/// condemned fence, given up on the next write and re-taken by the+/// healing pass, whose `init_transactions` aborts the pending+/// transaction at the broker as a side effect. Retrying the abort is+/// therefore a slower, less reliable version of a recovery that already+/// exists, and it is not free: every attempt is bounded by the+/// transaction timeout and has to fit the same runway.pub const FENCING_ABORT_ATTEMPTS: u32 = 1;/// Every call bounded by the transaction timeout that one window can@@ -517,6 +525,43 @@ impl Config {lifetime + lifetime / 2}+ /// The lease relations that hold whether or not fencing is on.+ ///+ /// `PodHandle::new` asserts that the heartbeat fits inside the+ /// keepalive's renewal margin, but it does so several hundred lines+ /// into startup — after etcd, Kafka and the Postgres pool are+ /// established — and its message names the heartbeat rather than the+ /// TTL that decides the margin. Checking it here turns a late panic+ /// into an early refusal that names both.+ pub fn validate_lease_timescales(&self) -> Result<(), String> {+ let margin = AuthorityClock::renewal_margin(self.lease_ttl);+ let heartbeat = self.heartbeat_interval();+ // Zero is under every margin, so the comparison below waves it+ // through — but the keepalive uses this interval as the *timeout*+ // for each renewal round, so a zero one times out instantly,+ // exhausts the margin through its retry pace, and ends the+ // session. The pod then releases every partition and starts over,+ // for as long as it runs, without ever serving or crashing.+ if heartbeat.is_zero() {+ return Err(+ "HEARTBEAT_INTERVAL_SECS must be greater than zero: the keepalive uses it as \+ the timeout for each renewal round, so a zero interval fences the pod against \+ healthy etcd in a loop it cannot leave"+ .to_string(),+ );+ }+ if heartbeat >= margin {+ return Err(format!(+ "HEARTBEAT_INTERVAL_SECS ({heartbeat:?}) must be well under the keepalive \+ renewal margin ({margin:?} = 2/3 of LEASE_TTL {}s): the sleep between \+ renewals would exhaust the margin on its own, and the pod would fence \+ itself against healthy etcd",+ self.lease_ttl,+ ));+ }+ Ok(())+ }+/// Every relation the fenced produce path depends on, checked at/// startup: the derivation satisfies them wherever the lease TTL/// leaves room, and an operator can override either knob.@@ -524,6 +569,20 @@ impl Config {if !self.kafka_transactional_fencing {return Ok(());}+ // Fencing without the lease gate is the combination the e2e+ // zombie scenario breaks: acquisition takes the partition's epoch+ // from whoever holds it, so a pod waking inside its lease window+ // fences the legitimate owner on its way to noticing it is dead.+ // The gate is what gives acquisition the standing to be safe, so+ // the dependency is refused at startup rather than documented.+ if !self.lease_gated_authority {+ return Err(+ "KAFKA_TRANSACTIONAL_FENCING requires LEASE_GATED_AUTHORITY: unless \+ acquisition is gated on holding the lease, a pod whose lease has lapsed \+ can take the changelog fence away from the partition's real owner"+ .to_string(),+ );+ }let (message, txn, runway, window) = (self.fencing_message_timeout(),self.fencing_txn_timeout(),@@ -697,6 +756,7 @@ mod fencing_timescale_tests {fn fenced(lease_ttl: i64) -> Config {let mut config = Config::init_from_env().expect("defaults");config.kafka_transactional_fencing = true;+ config.lease_gated_authority = true;config.lease_ttl = lease_ttl;config.fencing_txn_timeout_ms = 0;config.fencing_message_timeout_ms = 0;@@ -764,6 +824,62 @@ mod fencing_timescale_tests {);}+ /// The gap that made the fencing check misleading: a TTL it accepts+ /// can still be one the pod refuses to start on, and that refusal+ /// arrived hundreds of lines later, blamed the heartbeat, and never+ /// mentioned the TTL that actually decides the margin.+ ///+ /// The fencing floor and the heartbeat happen not to overlap at the+ /// default heartbeat today, so the pairs below raise it — which is+ /// the point: the two checks constrain different things, and nothing+ /// keeps a future change to the timeout shares from moving the+ /// fencing floor back under the heartbeat.+ #[test]+ fn a_lease_ttl_the_heartbeat_cannot_fit_is_refused_up_front() {+ for (lease_ttl, heartbeat_secs) in [(27, 18), (30, 20), (60, 40)] {+ let mut config = fenced(lease_ttl);+ config.heartbeat_interval_secs = heartbeat_secs;+ assert!(+ config.validate_fencing_timescales().is_ok(),+ "LEASE_TTL={lease_ttl} is meant to pass the fencing check"+ );+ let err = config+ .validate_lease_timescales()+ .expect_err("but must not pass the lease check");+ assert!(+ err.contains("LEASE_TTL"),+ "the refusal must name the knob to change, got: {err}"+ );+ }+ }++ /// Zero passes the margin comparison — it is under every margin — but+ /// the keepalive uses the interval as each round's timeout, so it+ /// fences the pod against healthy etcd forever.+ #[test]+ fn a_zero_heartbeat_is_refused() {+ let mut config = fenced(30);+ config.heartbeat_interval_secs = 0;+ let err = config+ .validate_lease_timescales()+ .expect_err("a zero heartbeat must not start");+ assert!(+ err.contains("greater than zero"),+ "the refusal must name the constraint, got: {err}"+ );+ }++ /// And the production pairing must survive it, or the check would+ /// refuse the fleet it was written to protect.+ #[test]+ fn the_production_lease_and_heartbeat_agree() {+ let mut config = fenced(30);+ config.heartbeat_interval_secs = 10;+ config+ .validate_lease_timescales()+ .expect("LEASE_TTL=30 with a 10s heartbeat must start");+ }+/// The broker's patience has to cover the whole window, not the first/// call into it. A bound shorter than the lifetime lets the broker/// abandon a window this pod is still working, and that epoch bump@@ -994,4 +1110,17 @@ mod fencing_timescale_tests {.expect_err("must reject");assert!(err.contains("librdkafka"), "got: {err}");}++ /// The dependency is a startup failure, not a comment: fencing on a+ /// pod that will acquire without checking its lease is the shape the+ /// zombie gate reproduces.+ #[test]+ fn fencing_without_the_lease_gate_is_refused() {+ let mut config = fenced(30);+ config.lease_gated_authority = false;+ let err = config+ .validate_fencing_timescales()+ .expect_err("fencing must require the gate");+ assert!(err.contains("LEASE_GATED_AUTHORITY"), "got: {err}");+ }}diff --git a/rust/personhog-leader/src/coordination/mod.rs b/rust/personhog-leader/src/coordination/mod.rsindex 9115e8cdf36e..b4fd3084ef66 100644--- a/rust/personhog-leader/src/coordination/mod.rs+++ b/rust/personhog-leader/src/coordination/mod.rs@@ -2,13 +2,15 @@ use std::sync::Arc;use std::time::Duration;use async_trait::async_trait;+use metrics::counter;+use personhog_coordination::authority::AuthorityClock;use personhog_coordination::error::{Error, Result};use personhog_coordination::pod::HandoffHandler;-use tracing::info;+use tracing::{error, info};use crate::cache::{DirtyIndex, PartitionedCache};use crate::emitted::EmittedVersions;-use crate::fencing::{FenceGuard, FencedChangelogProducers};+use crate::fencing::{heal_fence, FenceGuard, FencedChangelogProducers, HealOutcome};use crate::inflight::InflightTracker;use crate::warming::{warm_from_kafka, WarmClientPools, WarmingConfig};@@ -52,6 +54,13 @@ pub struct LeaderHandoffHandler {/// partition initializes its transactional producer (fencing every/// predecessor), and releasing it drops the producer.fenced: Option<Arc<FencedChangelogProducers>>,+ /// Present when lease-gated authority is on. Acquiring a fence takes+ /// the partition's epoch away from whoever holds it, so a pod whose+ /// lease may have lapsed must not do it: the broker grants the epoch+ /// to whoever initializes last, not to whoever the protocol says+ /// owns the partition, so an unchecked acquire lets a zombie waking+ /// inside its lease window fence the legitimate owner.+ authority: Option<Arc<AuthorityClock>>,/// Shared with the service, so that giving up a partition also gives/// up the version floors held for its persons.emitted_versions: Arc<EmittedVersions>,@@ -67,6 +76,7 @@ pub struct LeaderHandoffHandler {}impl LeaderHandoffHandler {+ #[allow(clippy::too_many_arguments)]pub fn new(cache: Arc<PartitionedCache>,inflight: Arc<InflightTracker>,@@ -74,6 +84,7 @@ impl LeaderHandoffHandler {warming: WarmingConfig,pools: Arc<WarmClientPools>,fenced: Option<Arc<FencedChangelogProducers>>,+ authority: Option<Arc<AuthorityClock>>,emitted_versions: Arc<EmittedVersions>,) -> Self {Self {@@ -83,6 +94,7 @@ impl LeaderHandoffHandler {warming,pools,fenced,+ authority,emitted_versions,freshly_fenced: Arc::new(dashmap::DashSet::new()),}@@ -91,6 +103,68 @@ impl LeaderHandoffHandler {pub fn owns_partition(&self, partition: u32) -> bool {self.cache.has_partition(partition)}++ /// Refuse to take a partition's fence when this pod's own lease may+ /// have lapsed.+ ///+ /// Acquisition is not a private act: `init_transactions` moves the+ /// broker's epoch to this producer and invalidates the previous+ /// holder, whoever that is. A pod that has stopped renewing has no+ /// standing to do that, and doing it anyway is how a waking zombie+ /// takes the partition away from the owner that legitimately holds+ /// it. Failing here leaves the convergence to retry once the lease+ /// is confirmed again, or to end with the session if it is not.+ /// Re-check after a broker round trip that moved the partition's+ /// epoch.+ ///+ /// `check_authority` before `acquire` is a pre-check across an+ /// operation that talks to the broker, so the claim can lapse while+ /// it runs. The epoch bump cannot be undone — `init_transactions`+ /// has already taken it from whoever held it — but this pod can+ /// decline to build on a claim it no longer has: it drops the fence+ /// and fails the convergence rather than serving. The partition's+ /// real owner re-takes the epoch through its own healing+ /// re-acquisition, so a fence stolen this way corrects itself+ /// instead of persisting until the next handoff.+ fn check_authority_after_acquire(&self, partition: u32, phase: &'static str) -> Result<()> {+ let Err(e) = self.check_authority(partition, phase) else {+ return Ok(());+ };+ if let Some(fenced) = &self.fenced {+ fenced.release(partition);+ }+ counter!(+ "personhog_leader_authority_lapsed_mid_acquire_total",+ "phase" => phase+ )+ .increment(1);+ error!(+ partition,+ phase, "authority lapsed while taking the changelog fence; dropping it"+ );+ Err(e)+ }++ fn check_authority(&self, partition: u32, phase: &'static str) -> Result<()> {+ let Some(authority) = &self.authority else {+ return Ok(());+ };+ if authority.is_valid() {+ return Ok(());+ }+ counter!(+ "personhog_leader_authority_lapsed_acquires_total",+ "phase" => phase,+ "reason" => if authority.is_surrendered() { "surrendered" } else { "stale" }+ )+ .increment(1);+ Err(Error::invalid_state(format!(+ "refusing to take the changelog fence for partition {partition}: no confirmed \+ lease renewal in {:?}",+ authority.since_confirmed()+ )))+ }+/// Stage the mark warming leaves behind. Warming itself needs a/// broker, and what these tests pin is the mark's lifetime across the/// convergences that follow, not how it comes to exist.@@ -146,6 +220,7 @@ impl HandoffHandler for LeaderHandoffHandler {async fn warm_partition(&self, partition: u32) -> Result<()> {info!(partition, "warming partition cache from kafka");+ self.check_authority(partition, "warm")?;// Broker-side fencing before the warm read, not after: acquiring// the fence bumps the producer epoch and aborts any in-flight// transaction from a predecessor, so every write a stale owner@@ -165,13 +240,14 @@ impl HandoffHandler for LeaderHandoffHandler {.acquire(partition).await.map_err(Error::invalid_state)?;+ self.check_authority_after_acquire(partition, "warm")?;info!(partition, "changelog fence acquired");// From here the fence is held for a warm that has not// happened yet. If the warm fails — or never returns,// because the attempt was torn down by a lost lease — the// guard gives the epoch back rather than leaving this// process holding a partition it does not own.- Some(FenceGuard::new(Arc::clone(fenced), partition))+ Some(FenceGuard::new(Arc::clone(fenced), partition, "warm"))} else {None};@@ -195,6 +271,36 @@ impl HandoffHandler for LeaderHandoffHandler {Ok(())}+ /// The partition is meant to be served, so make sure this pod can+ /// actually write to it. A fence lost to a broker rejection or a+ /// failed abort has no other way back — convergence sees the+ /// partition warmed and unfenced and would otherwise do nothing.+ ///+ /// A heal that cannot acquire is reported through the+ /// partition-labeled failure counter and the error log, not by+ /// failing the run. Failing the run would escalate through the+ /// convergence budgets to process death — trading one partition's+ /// writes for every partition's reads — while the reconcile tick+ /// already retries this every pass. A heal that succeeds counts as+ /// applied work, so a repairing pod's budgets reset like any other+ /// progress.+ async fn verify_serving(&self, partition: u32) -> Result<bool> {+ let Some(fenced) = &self.fenced else {+ return Ok(false);+ };+ match heal_fence(fenced, &self.inflight, self.authority.as_deref(), partition).await {+ Ok(HealOutcome::Healed) => {+ // The epoch just moved. Mark it like every other+ // acquisition site, so the resume step of this same+ // convergence trusts this fence instead of bumping+ // the epoch out from under the writes it re-admits.+ self.freshly_fenced.insert(partition);+ Ok(true)+ }+ Ok(_) | Err(_) => Ok(false),+ }+ }+async fn release_partition(&self, partition: u32) -> Result<()> {info!(partition, "releasing partition");if let Some(fenced) = &self.fenced {@@ -216,6 +322,7 @@ impl HandoffHandler for LeaderHandoffHandler {async fn resume_partition(&self, partition: u32) -> Result<()> {info!(partition, "handoff cancelled; re-admitting writes");+ self.check_authority(partition, "resume")?;// The cancelled handoff's target may have gotten as far as// acquiring the changelog fence, which leaves this pod's producer// epoch-stale — every write would fail as fenced until the next@@ -241,6 +348,7 @@ impl HandoffHandler for LeaderHandoffHandler {.acquire(partition).await.map_err(Error::invalid_state)?;+ self.check_authority_after_acquire(partition, "resume")?;// Mark it the same way warming does. A convergence torn down// between here and the point `apply` records the resume// retries with the partition still listed as fenced, and@@ -310,6 +418,7 @@ mod tests {},pools,None,+ None,Arc::new(EmittedVersions::new(1_000_000)),)}diff --git a/rust/personhog-leader/src/fencing.rs b/rust/personhog-leader/src/fencing.rsindex 9a400b73e31d..07bc963dc716 100644--- a/rust/personhog-leader/src/fencing.rs+++ b/rust/personhog-leader/src/fencing.rs@@ -43,7 +43,10 @@ use tracing::{debug, error, warn};use personhog_proto::personhog::types::v1::Person;+use personhog_coordination::authority::AuthorityClock;+use crate::config::{FENCING_ABORT_ATTEMPTS, FENCING_COMMIT_ATTEMPTS};+use crate::inflight::InflightTracker;use crate::kafka::changelog_message_key;/// The fencing scope is the partition: every owner of partition `p`@@ -156,13 +159,11 @@ struct PartitionFence {////// Such a producer is still installed, so presence alone cannot tell/// a working fence from a dead one. This flag is what makes the- /// distinction visible: a condemned partition answers as unowned so- /// the router bounces instead of retrying a dead producer. On this- /// branch nothing re-acquires in place — recovery is a process- /// restart or the partition moving — and the stacked lease-validity- /// branch adds the serving-side re-acquisition, which consults this- /// flag and needs the authority stamp it introduces for the standing- /// to bump the epoch.+ /// distinction visible: a condemned partition answers as unowned, so+ /// the router bounces instead of retrying a dead producer, and+ /// `holds()` reports the fence missing — which is what lets+ /// `heal_fence`, on the next convergence to Serving, re-take the+ /// epoch once the pod's claim is confirmed.unusable: AtomicBool,commit_timeout: Duration,}@@ -350,16 +351,24 @@ pub struct FenceGuard {/// which after a release and a re-acquire is somebody else's/// producer — the same hazard `forget_fence` checks for.taken: Option<Arc<PartitionFence>>,+ /// Names the work the fence was taken for, so an abandon names the+ /// path that dropped mid-flight.+ context: &'static str,armed: bool,}impl FenceGuard {- pub fn new(fenced: Arc<FencedChangelogProducers>, partition: u32) -> Self {+ pub fn new(+ fenced: Arc<FencedChangelogProducers>,+ partition: u32,+ context: &'static str,+ ) -> Self {let taken = fenced.installed(partition);Self {fenced,partition,taken,+ context,armed: true,}}@@ -376,7 +385,8 @@ impl Drop for FenceGuard {counter!("personhog_leader_fence_abandoned_total").increment(1);warn!(partition = self.partition,- "releasing a fence taken for a warm that did not finish"+ context = self.context,+ "releasing a fence taken for work that did not finish");match &self.taken {Some(fence) => self.fenced.forget_fence(self.partition, fence),@@ -460,7 +470,7 @@ impl FencedChangelogProducers {/// initialize transactions, which fences every previous owner of the/// partition's transactional id. Runs on the blocking pool — init is/// a synchronous broker round trip.- pub async fn acquire(&self, partition: u32) -> Result<(), String> {+ async fn acquire_installed(&self, partition: u32) -> Result<Arc<PartitionFence>, String> {let kafka = self.kafka.clone();let tid = transactional_id(&self.topic, partition);let timeout = self.init_timeout;@@ -477,26 +487,30 @@ impl FencedChangelogProducers {})?;counter!("personhog_leader_fence_init_total", "outcome" => "ok").increment(1);histogram!("personhog_leader_fence_init_ms").record(start.elapsed().as_secs_f64() * 1000.0);- self.partitions.insert(- partition,- Arc::new(PartitionFence {- producer,- gate: Mutex::new(Gate {- open: false,- in_flight: 0,- poisoned: false,- committing: false,- waiters: Vec::new(),- }),- sends_settled: Notify::new(),- window_closed: Notify::new(),- #[cfg(any(test, feature = "test-support"))]- panic_next_commit: AtomicBool::new(false),- unusable: AtomicBool::new(false),- commit_timeout: self.commit_timeout,+ let installed = Arc::new(PartitionFence {+ producer,+ gate: Mutex::new(Gate {+ open: false,+ in_flight: 0,+ poisoned: false,+ committing: false,+ waiters: Vec::new(),}),- );- Ok(())+ sends_settled: Notify::new(),+ window_closed: Notify::new(),+ #[cfg(any(test, feature = "test-support"))]+ panic_next_commit: AtomicBool::new(false),+ unusable: AtomicBool::new(false),+ commit_timeout: self.commit_timeout,+ });+ self.partitions.insert(partition, Arc::clone(&installed));+ Ok(installed)+ }++ /// Take the partition's fence, discarding the handle. The caller+ /// relies on the map rather than on holding the fence itself.+ pub async fn acquire(&self, partition: u32) -> Result<(), String> {+ self.acquire_installed(partition).await.map(|_| ())}/// The fence currently installed for a partition, if any.@@ -512,6 +526,19 @@ impl FencedChangelogProducers {}}+ /// Whether this pod holds a *usable* fence for the partition.+ ///+ /// Deliberately not mere presence. A condemned producer is still+ /// installed, and answering "yes" for one would tell the repair pass+ /// that a partition it must re-acquire needs nothing — which is+ /// exactly how such a partition stayed unwritable until a handoff+ /// moved it.+ pub fn holds(&self, partition: u32) -> bool {+ self.partitions+ .get(&partition)+ .is_some_and(|fence| fence.is_usable())+ }+/// Commit the partition's open window before its owner gives it up.////// A request cancelled mid-produce takes its handler — and the@@ -1288,15 +1315,29 @@ pub fn preregister_fencing_metrics(partitions: u32) {counter!("personhog_leader_fence_slots_abandoned_total").increment(0);counter!("personhog_leader_fence_abandoned_total").increment(0);counter!("personhog_leader_fence_abort_failed_total").increment(0);+ // The healing counters fire exactly during the incidents an operator+ // would reach for them in, and rarely enough that lazy registration+ // can swallow the first burst between scrapes.+ counter!("personhog_leader_fence_healed_total").increment(0);+ counter!("personhog_leader_fence_heal_abandoned_total").increment(0);for reason in ["abort_failed", "commit_indeterminate", "commit_task_lost"] {counter!("personhog_leader_fence_condemned_total", "reason" => reason).increment(0);}counter!("personhog_leader_fence_commit_retries_total").increment(0);- counter!("personhog_leader_fenced_partition_drops_total").increment(0);counter!("personhog_leader_kafka_produce_errors_total").increment(0);for partition in 0..partitions {let p = partition.to_string();counter!("personhog_leader_fence_aborts_total", "partition" => p.clone()).increment(0);+ counter!(+ "personhog_leader_fenced_partition_drops_total",+ "partition" => p.clone()+ )+ .increment(0);+ counter!(+ "personhog_leader_fence_heal_failures_total",+ "partition" => p.clone()+ )+ .increment(0);counter!("personhog_leader_fence_commit_indeterminate_total","partition" => p.clone()@@ -1326,6 +1367,103 @@ fn clone_outcome(outcome: &Result<(), FencedProduceError>) -> Result<(), FencedP}}+/// Re-take the partition's fence if this pod is serving it without one.+///+/// A fence can go missing under a pod that legitimately owns its+/// partition: a broker rejection evicted it, an abort exhausted its+/// retries and left the producer unusable, or a stale pod took the epoch+/// and stepped back. Nothing in the handoff protocol repairs that —+/// convergence sees the partition warmed and unfenced and does nothing —+/// so without this the partition stays unwritable until a handoff moves+/// it.+///+/// Re-acquisition is safe only because of where this is called from and+/// what it checks. The caller is the convergence to `Serving`, so the+/// durable assignment says this pod owns the partition; the claim must+/// still be valid, because taking a fence moves the broker's epoch away+/// from whoever holds it; and a partition being locally fenced is+/// disqualifying, since that means a handoff is moving it and the+/// incoming owner's fence is the one that should stand.+/// What the healing pass did, for the caller to act on: a healed+/// partition is freshly fenced — the epoch just moved, and the same+/// convergence must not move it again — and a failure is the caller's+/// to surface, because a partition that cannot regain its fence has no+/// other repair path.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum HealOutcome {+ /// Nothing to do: the fence is present and usable, the partition is+ /// under handoff, or this pod cannot vouch for its claim.+ Intact,+ /// A fence was re-taken and is serving.+ Healed,+ /// A fence was taken but given back — standing lapsed or a handoff+ /// began during the broker round trip.+ Abandoned,+}++pub async fn heal_fence(+ fenced: &Arc<FencedChangelogProducers>,+ inflight: &InflightTracker,+ authority: Option<&AuthorityClock>,+ partition: u32,+) -> Result<HealOutcome, String> {+ let lost_standing = authority.is_some_and(|a| !a.is_valid());+ if lost_standing || fenced.holds(partition) || inflight.is_fenced(partition) {+ return Ok(HealOutcome::Intact);+ }+ let taken = match fenced.acquire_installed(partition).await {+ Ok(taken) => taken,+ Err(e) => {+ // Partition-labeled: a wedged partition must be attributable+ // from the series alone, because this is deliberately not a+ // run failure (see `verify_serving`) and the counter is the+ // alerting surface for it.+ counter!(+ "personhog_leader_fence_heal_failures_total",+ "partition" => partition.to_string()+ )+ .increment(1);+ error!(partition, error = %e, "failed to re-take the changelog fence");+ return Err(e);+ }+ };+ // Answerable for the installed fence from here until a deliberate+ // branch takes over. A drop *during* the acquire needs no guard —+ // the producer is discarded before it is installed, `holds()` stays+ // false, and the next convergence heals again. What the guard covers+ // is the stretch after installation: the checks below await nothing+ // today, so its teeth are a panic between them and any await a+ // future change adds. Same shape as the warm path.+ let guard = FenceGuard::new(Arc::clone(fenced), partition, "heal");+ // The round trip is long enough for the ground to move: the claim can+ // lapse, or a handoff can start draining the partition. Holding a+ // fence taken without standing is not passive — the write path trusts+ // the broker epoch rather than re-checking the claim, so a request+ // landing here would ack a mutation with an epoch taken from the+ // partition's real owner.+ let lost_standing = authority.is_some_and(|a| !a.is_valid());+ if lost_standing || inflight.is_fenced(partition) {+ guard.keep();+ // The fence this call installed, not whatever is installed now:+ // re-reading the map would match by construction and evict a+ // replacement just as readily as its own.+ fenced.forget_fence(partition, &taken);+ counter!("personhog_leader_fence_heal_abandoned_total").increment(1);+ warn!(+ partition,+ "released a fence taken while standing lapsed mid-acquire"+ );+ return Ok(HealOutcome::Abandoned);+ }+ guard.keep();+ counter!("personhog_leader_fence_healed_total").increment(1);+ warn!(+ partition,+ "re-took the changelog fence for a served partition"+ );+ Ok(HealOutcome::Healed)+}+#[cfg(test)]mod tests {use super::*;diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rsindex 3d9f2085c311..90731193cab9 100644--- a/rust/personhog-leader/src/main.rs+++ b/rust/personhog-leader/src/main.rs@@ -12,6 +12,7 @@ use kube::Client;use lifecycle::{ComponentOptions, Manager};use personhog_common::async_gzip::{AsyncGzipConfig, AsyncGzipLayer};use personhog_common::grpc::{tracked_tcp_incoming, GrpcLoadShedLayer, GrpcMetricsLayer};+use personhog_coordination::authority::AuthorityClock;use personhog_coordination::pod::{PodConfig, PodHandle};use personhog_coordination::store::PersonhogStore;use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeaderServer;@@ -54,6 +55,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {.expect("failed to install rustls ring CryptoProvider");let config = Config::init_from_env().expect("Invalid configuration");+ config+ .validate_lease_timescales()+ .expect("Invalid lease configuration");config.validate_fencing_timescales().expect("Invalid fencing configuration");@@ -118,6 +122,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {ComponentOptions::new().with_shutdown_phase(1),);+ let authority_metrics_handle = manager.register(+ "authority-metrics",+ ComponentOptions::new().is_observability(true),+ );+let readiness = manager.readiness_handler();let liveness = manager.liveness_handler();@@ -139,6 +148,30 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {.route("/_liveness", get(move || async move { liveness.check() }));let metrics_router = setup_metrics_routes(health_router);preregister_metrics();+ // The refusals the gate can emit: rare by design, and a burst is+ // exactly what a deploy-window scrape would otherwise miss.+ for reason in ["surrendered", "stale"] {+ counter!(+ "personhog_leader_authority_lapsed_rejections_total",+ "reason" => reason+ )+ .increment(0);+ for phase in ["warm", "resume"] {+ counter!(+ "personhog_leader_authority_lapsed_acquires_total",+ "phase" => phase,+ "reason" => reason+ )+ .increment(0);+ }+ }+ for phase in ["warm", "resume"] {+ counter!(+ "personhog_leader_authority_lapsed_mid_acquire_total",+ "phase" => phase+ )+ .increment(0);+ }counter!("personhog_leader_unresolved_versions_total").increment(0);counter!("personhog_leader_unresolved_versions_spilled_total").increment(0);gauge!("personhog_leader_unresolved_versions").set(0.0);@@ -273,6 +306,63 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {None};+ // One clock for the process: the coordination session claims and+ // surrenders it, the data plane reads it per request.+ let authority = Arc::new(AuthorityClock::unclaimed());+ // Publish the live headroom whether or not the gate is armed: the+ // question before enabling it is how close this fleet routinely runs+ // to the margin, and that has to be answerable from a deployment+ // that is not yet enforcing anything.+ //+ // This says nothing about a process-wide stall — a task that cannot+ // run cannot report that it cannot run, which is the same limitation+ // the clock exists to route around, and why enforcement reads the+ // stamp inline on the request path instead of trusting a publisher.+ // What it does show is a keepalive falling behind while the rest of+ // the process is healthy, and the steady-state distance from the+ // margin.+ {+ let authority = Arc::clone(&authority);+ let handle = authority_metrics_handle;+ tokio::spawn(async move {+ let _guard = handle.process_scope();+ let mut shutdown = std::pin::pin!(handle.shutdown_signal());+ let mut tick = tokio::time::interval(Duration::from_secs(5));+ loop {+ tokio::select! {+ _ = &mut shutdown => break,+ _ = tick.tick() => {}+ }+ // Before the first grant there is no claim to measure+ // against: age would read as process uptime and margin as+ // zero, which any threshold would treat as a permanent+ // emergency.+ if !authority.is_claimed() {+ continue;+ }+ gauge!("personhog_leader_authority_valid").set(if authority.is_valid() {+ 1.0+ } else {+ 0.0+ });+ gauge!("personhog_leader_authority_age_ms")+ .set(authority.since_confirmed().as_secs_f64() * 1000.0);+ gauge!("personhog_leader_authority_margin_ms")+ .set(authority.margin().as_secs_f64() * 1000.0);+ }+ });+ }++ let gated_authority = if config.lease_gated_authority {+ tracing::info!(+ "lease-gated authority enabled: reads and fence acquisition require a \+ confirmed lease renewal within the keepalive margin"+ );+ Some(Arc::clone(&authority))+ } else {+ None+ };+let service = PersonHogLeaderService::new(Arc::clone(&cache),kafka_producer.clone(),@@ -289,6 +379,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {),warnings.clone(),fenced.clone(),+ gated_authority.clone(),Arc::clone(&emitted_versions),);@@ -321,7 +412,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {},},Arc::clone(&warm_pools),- fenced,+ fenced.clone(),+ gated_authority.clone(),Arc::clone(&emitted_versions),);let advertise_address =@@ -397,7 +489,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {});}- let pod = PodHandle::new(store, pod_config, Arc::new(handler), k8s_awareness);+ let pod = PodHandle::new(+ store,+ pod_config,+ Arc::new(handler),+ k8s_awareness,+ Arc::clone(&authority),+ );tokio::spawn(async move {let _guard = coordination_handle.process_scope();diff --git a/rust/personhog-leader/src/service.rs b/rust/personhog-leader/src/service.rsindex d92550219a88..66c6ebdb15de 100644--- a/rust/personhog-leader/src/service.rs+++ b/rust/personhog-leader/src/service.rs@@ -16,6 +16,8 @@ use uuid::Uuid;use personhog_common::partitioning::partition_for_person;+use personhog_coordination::authority::AuthorityClock;+use crate::cache::{approx_person_bytes, CacheLookup, CachedPerson, DirtyIndex, DirtyMark, PartitionedCache,PersonCacheKey,@@ -87,12 +89,65 @@ pub struct PersonHogLeaderService {/// Present when broker-enforced epoch fencing is on; the write/// path produces through the partition's transaction window.fenced: Option<Arc<FencedChangelogProducers>>,+ /// This pod's claim to serve, consulted before answering a strong+ /// read. Present only when lease-gated reads are enabled.+ authority: Option<Arc<AuthorityClock>>,/// Versions emitted without a confirmed outcome, so a later write for/// the same person cannot reuse one.emitted_versions: Arc<EmittedVersions>,}impl PersonHogLeaderService {+ /// Refuse to answer as the partition's owner once this pod's lease+ /// may have expired.+ ///+ /// The cache is only authoritative while the lease behind it is, and+ /// the keepalive's own detection cannot be relied on to notice: a+ /// process that is stopped, starved, or wedged stops renewing and+ /// stops noticing together, then keeps serving state the new owner+ /// is already changing. Reading the published stamp here makes the+ /// lapse self-enforcing — nothing has to be alive to apply it.+ ///+ /// Refusal starts at the keepalive's renewal margin, strictly before+ /// the coordinator could treat the lease as expired, so requests are+ /// turned away while ownership is merely doubtful rather than after+ /// it is wrong. `FailedPrecondition` is the admission fence's own+ /// vocabulary: the router bounces and re-resolves toward whoever+ /// actually owns the partition.+ #[allow(clippy::result_large_err)]+ fn check_authority(&self, partition: u32) -> Result<(), Status> {+ let Some(authority) = &self.authority else {+ return Ok(());+ };+ if authority.is_valid() {+ return Ok(());+ }+ let reason = if authority.is_surrendered() {+ "surrendered"+ } else {+ "stale"+ };+ counter!(+ "personhog_leader_authority_lapsed_rejections_total",+ "reason" => reason+ )+ .increment(1);+ let since = authority.since_confirmed();+ // Debug, not warn: the gate refuses *every* request for the whole+ // duration of a lapse, so this fires at the pod's full read rate+ // during exactly the incident someone would be reading logs for.+ // The labelled counter above carries the rate and the cause.+ tracing::debug!(+ partition,+ ?since,+ margin = ?authority.margin(),+ "refusing to serve: no confirmed lease renewal within the margin"+ );+ Err(Status::failed_precondition(format!(+ "serving authority lapsed: no confirmed lease renewal in {since:?}"+ )))+ }+#[allow(clippy::too_many_arguments)]pub fn new(cache: Arc<PartitionedCache>,@@ -107,6 +162,7 @@ impl PersonHogLeaderService {size_limits: PropertySizeLimits,warnings: WarningsProducer,fenced: Option<Arc<FencedChangelogProducers>>,+ authority: Option<Arc<AuthorityClock>>,emitted_versions: Arc<EmittedVersions>,) -> Self {Self {@@ -122,6 +178,7 @@ impl PersonHogLeaderService {size_limits,warnings,fenced,+ authority,emitted_versions,}}@@ -423,12 +480,19 @@ impl PersonHogLeader for PersonHogLeaderService {let partition = partition_from_metadata(&request)?;let req = request.into_inner();self.validate_partition(partition, req.team_id, req.person_id)?;+ self.check_authority(partition)?;let cache_key = PersonCacheKey {team_id: req.team_id,person_id: req.person_id,};let person = self.lookup_or_load(partition, &cache_key).await?;+ // Re-check before answering. The load can wait — on the per-key+ // lock behind another request's produce, or on a changelog+ // recovery — for long enough that a claim valid at admission has+ // lapsed by the time there is something to return, and it is the+ // answer, not the arrival, that has to be backed by ownership.+ self.check_authority(partition)?;Ok(Response::new(GetPersonResponse {person: Some(cached_person_to_proto(&person)),@@ -442,6 +506,16 @@ impl PersonHogLeader for PersonHogLeaderService {let partition = partition_from_metadata(&request)?;let req = request.into_inner();self.validate_partition(partition, req.team_id, req.person_id)?;+ // A write is serving too. Broker-enforced fencing covers this+ // path when it is on, but it cannot be turned on first — startup+ // refuses fencing without the gate — so every fleet passes+ // through a window where the gate is the only thing standing+ // between a pod that stopped renewing and a write the successor+ // will never see. The lease-loss path surrenders before it+ // drains, deliberately, and until this check existed only reads+ // honoured that: writes stayed admitted until the local fence+ // landed, behind a watch teardown and a task join.+ self.check_authority(partition)?;// Admit the write as inflight, unless the partition is fenced. A// fenced partition has drained for handoff: every router acked the@@ -716,6 +790,16 @@ impl PersonHogLeader for PersonHogLeaderService {let proto = cached_person_to_proto(&updated_person);+ // Re-check before producing, for the same reason the read path+ // re-checks before answering: admission proves nothing about the+ // moment the record lands. Between the check at entry and here a+ // write can wait on the per-key lock behind another produce, and+ // on a changelog recovery — long enough for a starved keepalive's+ // stamp to age out, for the lease to expire at etcd, and for the+ // coordinator to warm a successor past the point this record+ // would land.+ self.check_authority(partition)?;+// From here the record may reach the changelog whatever happens// to this request — including the request simply ceasing to exist// when the client's deadline expires. The guard is what makes the@@ -753,18 +837,15 @@ impl PersonHogLeader for PersonHogLeaderService {// initialized the transactional id, not that this pod// lost the partition: a zombie waking inside its// lease window re-acquires on the way to noticing it- // is dead, which fences the legitimate owner. Giving- // up the partition here takes it out of service with- // nothing to put it back — convergence sees it warmed- // and unfenced, so no branch re-warms it. On this- // branch that leaves writes bouncing until a restart- // or a handoff moves the partition; the stacked- // lease-validity branch closes it with a serving-side- // re-acquisition, gated on the authority stamp that- // gives a pod the standing to bump the epoch. Reads- // stay served until the lease machinery settles- // ownership; refusing them needs a lease-validity- // check on the read path, closed on the same branch.+ // is dead, which fences the legitimate owner. So the+ // fence is given up here as unusable and nothing+ // more; `heal_fence`, on the next convergence to+ // Serving, re-takes the epoch once the authority+ // stamp confirms this pod's standing. Reads stay+ // served meanwhile under the same stamp — the+ // `check_authority` calls at admission and before+ // answering are what refuse them once the claim+ // lapses.return Err(Status::failed_precondition(format!("partition ownership fenced: {e}")));@@ -985,10 +1066,424 @@ mod tests {PropertySizeLimits::new(655360, 524288),WarningsProducer::new(producer, "clickhouse_ingestion_warnings".to_string()),None,+ None,Arc::new(EmittedVersions::new(1_000_000)),)}+ /// The guarantee the clock exists for: a pod whose renewals have+ /// stopped refuses to answer as the partition's owner, without+ /// anything running to notice they stopped. The keepalive being+ /// wedged is exactly the case the lease machinery cannot cover.+ #[tokio::test]+ async fn a_pod_whose_renewals_stopped_refuses_to_serve() {+ // A clock whose renewals stopped longer ago than the margin —+ // constructed stale rather than aged by sleeping, so no runner+ // pace can blur which side of the margin the test is on.+ let margin = Duration::from_secs(20);+ let clock = Arc::new(AuthorityClock::stale_for(+ margin,+ margin + Duration::from_secs(1),+ ));+ let service = PersonHogLeaderService {+ authority: Some(Arc::clone(&clock)),+ ..make_test_service().await+ };++ let err = service+ .check_authority(0)+ .expect_err("a lapsed lease must not serve");+ assert_eq!(err.code(), Code::FailedPrecondition);++ clock.confirm(Instant::now());+ service+ .check_authority(0)+ .expect("a confirmed renewal restores service");+ }++ /// Losing the lease is decided immediately, not after the margin:+ /// the coordinator may already be reassigning.+ #[tokio::test]+ async fn surrendering_the_lease_stops_reads_at_once() {+ let clock = Arc::new(AuthorityClock::unclaimed());+ clock.begin_session(Duration::from_secs(30), Instant::now());+ let service = PersonHogLeaderService {+ authority: Some(Arc::clone(&clock)),+ ..make_test_service().await+ };++ service.check_authority(0).expect("still the owner");+ clock.surrender();+ assert_eq!(+ service.check_authority(0).unwrap_err().code(),+ Code::FailedPrecondition+ );+ }++ /// The gate has to be wired into the RPC, not merely implemented:+ /// this drives `get_person` itself rather than the check in+ /// isolation.+ ///+ /// It does not distinguish the two checks — a read that finds its+ /// person in cache never waits, so either one refuses it, and both+ /// return the same status. `a_read_admitted_before_the_lapse_still_+ /// refuses_to_answer` is what pins the second.+ #[tokio::test]+ async fn get_person_refuses_once_authority_lapses() {+ let margin = Duration::from_secs(20);+ let clock = Arc::new(AuthorityClock::stale_for(+ margin,+ margin + Duration::from_secs(1),+ ));+ let service = PersonHogLeaderService {+ authority: Some(Arc::clone(&clock)),+ ..make_test_service().await+ };+ // The fixture's single partition makes 0 the only routing answer.+ let (team_id, person_id) = (7, 42);+ service.cache.create_partition(0);+ service.cache.put(+ 0,+ PersonCacheKey { team_id, person_id },+ CachedPerson {+ id: person_id,+ uuid: "00000000-0000-0000-0000-000000000007".to_string(),+ team_id,+ properties: serde_json::json!({}),+ created_at: 0,+ version: 1,+ is_identified: false,+ approx_bytes: 64,+ },+ );++ let request = || {+ let mut request = Request::new(GetPersonRequest {+ team_id,+ person_id,+ read_options: None,+ });+ request+ .metadata_mut()+ .insert("x-partition", "0".parse().unwrap());+ request+ };++ let err = service+ .get_person(request())+ .await+ .expect_err("a lapsed lease must refuse the read");+ assert_eq!(err.code(), Code::FailedPrecondition);++ clock.confirm(Instant::now());+ service+ .get_person(request())+ .await+ .expect("a confirmed renewal serves the read");+ }++ /// A write is serving too, and the lease-loss path surrenders before+ /// it drains — so between the surrender and the local fence landing,+ /// this check is what stops a pod that no longer holds its lease from+ /// acking a mutation the successor will never see. Fencing covers the+ /// same ground when it is on, but it cannot be enabled first, so this+ /// is the only cover the intermediate rollout state has.+ ///+ /// Like its read-path counterpart it does not distinguish admission+ /// from the pre-produce re-check; `a_write_admitted_before_the_lapse_+ /// is_not_produced` pins the second.+ ///+ /// The person is seeded deliberately: without it a removed check+ /// would still surface `FailedPrecondition` from the ownership guard+ /// further down, and the test would pass having proved nothing.+ #[tokio::test]+ async fn update_refuses_once_authority_is_surrendered() {+ let clock = Arc::new(AuthorityClock::unclaimed());+ clock.begin_session(Duration::from_secs(30), Instant::now());+ let service = PersonHogLeaderService {+ authority: Some(Arc::clone(&clock)),+ ..make_test_service().await+ };+ let (team_id, person_id) = (7, 42);+ service.cache.create_partition(0);+ service.cache.put(+ 0,+ PersonCacheKey { team_id, person_id },+ CachedPerson {+ id: person_id,+ uuid: "00000000-0000-0000-0000-000000000007".to_string(),+ team_id,+ properties: serde_json::json!({}),+ created_at: 0,+ version: 1,+ is_identified: false,+ approx_bytes: 64,+ },+ );++ let request = || {+ let mut request = Request::new(UpdatePersonPropertiesRequest {+ team_id,+ person_id,+ event_name: "$set".to_string(),+ set_properties: serde_json::to_vec(&serde_json::json!({"a": 1})).unwrap(),+ set_once_properties: vec![],+ unset_properties: vec![],+ });+ request+ .metadata_mut()+ .insert("x-partition", "0".parse().unwrap());+ request+ };++ // Losing the lease is decided at once, not after the margin, so+ // no sleep is needed to reach the state that matters.+ clock.surrender();++ // Bounded on purpose: with the check gone the handler runs on to+ // produce against a broker that is not there, so an unbounded+ // await would report this regression as a hung test rather than a+ // failing one.+ let result = tokio::time::timeout(+ Duration::from_secs(5),+ service.update_person_properties(request()),+ )+ .await+ .expect("the refusal must come from the claim check, not from a produce timeout");+ let err = result.expect_err("a surrendered pod must not ack a write");+ assert_eq!(err.code(), Code::FailedPrecondition);+ }++ /// `get_person` checks the claim twice, and asserting only on the+ /// status code cannot tell the two apart: delete either and the other+ /// still answers FailedPrecondition. This one pins the second.+ ///+ /// The load is what makes it distinct. A read that finds the person+ /// in cache never waits, so the admission check is the only one it+ /// can trip; a read that has to wait — on the per-key lock, or on a+ /// changelog recovery — can be admitted under a claim that is gone by+ /// the time there is an answer, and it is the answer, not the+ /// arrival, that has to be backed by ownership.+ #[tokio::test]+ async fn a_read_admitted_before_the_lapse_still_refuses_to_answer() {+ let clock = Arc::new(AuthorityClock::unclaimed());+ clock.begin_session(Duration::from_secs(30), Instant::now());+ let service = Arc::new(PersonHogLeaderService {+ authority: Some(Arc::clone(&clock)),+ ..make_test_service().await+ });+ let (team_id, person_id) = (7, 42);+ let cache_key = PersonCacheKey { team_id, person_id };+ service.cache.create_partition(0);++ // Hold the per-key lock. The read misses the cache, reaches for+ // this lock, and parks there — which is where a changelog+ // recovery would leave it.+ let mutex = service+ .locks+ .entry(cache_key.clone())+ .or_default()+ .value()+ .clone();+ let held = mutex.lock().await;++ let mut request = Request::new(GetPersonRequest {+ team_id,+ person_id,+ read_options: None,+ });+ request+ .metadata_mut()+ .insert("x-partition", "0".parse().unwrap());+ let reading = tokio::spawn({+ let service = Arc::clone(&service);+ async move { service.get_person(request).await }+ });+ tokio::task::yield_now().await;++ // The claim goes while the read is parked, and the answer it was+ // waiting for arrives at the same time.+ clock.surrender();+ service.cache.put(+ 0,+ cache_key.clone(),+ CachedPerson {+ id: person_id,+ uuid: "00000000-0000-0000-0000-000000000007".to_string(),+ team_id,+ properties: serde_json::json!({}),+ created_at: 0,+ version: 1,+ is_identified: false,+ approx_bytes: 64,+ },+ );+ drop(held);++ let err = reading+ .await+ .expect("the read task must not panic")+ .expect_err("a claim that lapsed during the load must not be answered");+ assert_eq!(err.code(), Code::FailedPrecondition);+ }++ /// The write path checks the claim twice for the same reason the read+ /// path does, and asserting only on the status code cannot tell them+ /// apart. This one pins the second.+ ///+ /// A write admitted under a valid claim can wait on the per-key lock+ /// behind another produce, and on a changelog recovery — long enough+ /// for a starved keepalive's stamp to age out, for the lease to+ /// expire, and for a successor to warm past the point this record+ /// would land. Acking it then is acked-write loss that needs only one+ /// wedged pod, not a double zombie.+ #[tokio::test]+ async fn a_write_admitted_before_the_lapse_is_not_produced() {+ let clock = Arc::new(AuthorityClock::unclaimed());+ clock.begin_session(Duration::from_secs(30), Instant::now());+ let service = Arc::new(PersonHogLeaderService {+ authority: Some(Arc::clone(&clock)),+ ..make_test_service().await+ });+ let (team_id, person_id) = (7, 42);+ let cache_key = PersonCacheKey { team_id, person_id };+ service.cache.create_partition(0);+ service.cache.put(+ 0,+ cache_key.clone(),+ CachedPerson {+ id: person_id,+ uuid: "00000000-0000-0000-0000-000000000007".to_string(),+ team_id,+ properties: serde_json::json!({}),+ created_at: 0,+ version: 1,+ is_identified: false,+ approx_bytes: 64,+ },+ );++ // Hold the per-key lock so the write is admitted and then parks,+ // where a concurrent produce for the same person would leave it.+ let mutex = service+ .locks+ .entry(cache_key.clone())+ .or_default()+ .value()+ .clone();+ let held = mutex.lock().await;++ let mut request = Request::new(UpdatePersonPropertiesRequest {+ team_id,+ person_id,+ event_name: "$set".to_string(),+ set_properties: serde_json::to_vec(&serde_json::json!({"a": 1})).unwrap(),+ set_once_properties: vec![],+ unset_properties: vec![],+ });+ request+ .metadata_mut()+ .insert("x-partition", "0".parse().unwrap());+ let writing = tokio::spawn({+ let service = Arc::clone(&service);+ async move { service.update_person_properties(request).await }+ });+ tokio::task::yield_now().await;++ // The claim goes while the write is parked, then the lock frees.+ clock.surrender();+ drop(held);++ // Bounded: without the re-check the handler runs on to produce+ // against a broker that is not there, and an unbounded await+ // would report the regression as a hang rather than a failure.+ let result = tokio::time::timeout(Duration::from_secs(5), writing)+ .await+ .expect("the refusal must come from the claim check, not a produce timeout")+ .expect("the write task must not panic");+ let err = result.expect_err("a claim that lapsed during the wait must not be produced");+ assert_eq!(err.code(), Code::FailedPrecondition);+ }++ /// The admission checks refuse *before* the request does any work, and+ /// only the wait distinguishes them from the pre-answer re-checks: a+ /// request that reaches the per-key lock has already been admitted.+ ///+ /// Holding that lock turns the difference into a deadline. With+ /// admission intact neither call ever reaches it; without it they park+ /// there and are refused only once the lock frees, having meanwhile+ /// taken an inflight seat a handoff's drain must wait out and, on a+ /// miss, driven a Postgres fallback or a changelog recovery for a+ /// partition this pod no longer answers for.+ #[tokio::test]+ async fn a_request_arriving_after_the_lapse_is_refused_before_it_loads() {+ let clock = Arc::new(AuthorityClock::unclaimed());+ clock.begin_session(Duration::from_secs(30), Instant::now());+ let service = Arc::new(PersonHogLeaderService {+ authority: Some(Arc::clone(&clock)),+ ..make_test_service().await+ });+ let (team_id, person_id) = (7, 42);+ let cache_key = PersonCacheKey { team_id, person_id };+ // Deliberately unseeded: the read reaches the lock only on a+ // miss, and a hit would let a dropped admission check still be+ // caught by the pre-answer one, proving nothing.+ service.cache.create_partition(0);++ // Anything admitted parks here; nothing admitted ever arrives.+ let mutex = service+ .locks+ .entry(cache_key.clone())+ .or_default()+ .value()+ .clone();+ let _held = mutex.lock().await;++ clock.surrender();++ let mut read = Request::new(GetPersonRequest {+ team_id,+ person_id,+ read_options: None,+ });+ read.metadata_mut()+ .insert("x-partition", "0".parse().unwrap());+ let err = tokio::time::timeout(Duration::from_millis(200), service.get_person(read))+ .await+ .expect("the read must be refused at admission, not behind the load")+ .expect_err("a lapsed claim must not be served");+ assert_eq!(err.code(), Code::FailedPrecondition);++ let mut write = Request::new(UpdatePersonPropertiesRequest {+ team_id,+ person_id,+ event_name: "$set".to_string(),+ set_properties: serde_json::to_vec(&serde_json::json!({"a": 1})).unwrap(),+ set_once_properties: vec![],+ unset_properties: vec![],+ });+ write+ .metadata_mut()+ .insert("x-partition", "0".parse().unwrap());+ let err = tokio::time::timeout(+ Duration::from_millis(200),+ service.update_person_properties(write),+ )+ .await+ .expect("the write must be refused at admission, not behind the load")+ .expect_err("a lapsed claim must not be admitted");+ assert_eq!(err.code(), Code::FailedPrecondition);+ }++ /// With the gate off the pod serves exactly as before, so the flag+ /// is a real off switch rather than a partial one.+ #[tokio::test]+ async fn an_ungated_service_serves_regardless_of_renewals() {+ let service = make_test_service().await;+ assert!(service.authority.is_none());+ service.check_authority(0).expect("no gate, no refusal");+ }+#[test]#[should_panic(expected = "must not exceed")]fn inverted_size_limits_refuse_to_construct() {diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rsindex d0efbab2d8c0..c15b898b7748 100644--- a/rust/personhog-leader/tests/common/mod.rs+++ b/rust/personhog-leader/tests/common/mod.rs@@ -14,6 +14,7 @@ use async_trait::async_trait;use common_kafka::config::KafkaConfig;use common_kafka::kafka_producer::{create_kafka_producer, KafkaContext};use health::HealthRegistry;+use personhog_coordination::authority::AuthorityClock;use personhog_coordination::coordinator::{Coordinator, CoordinatorConfig};use personhog_coordination::error::Result;use personhog_coordination::pod::{PodConfig, PodHandle};@@ -364,8 +365,10 @@ pub async fn start_leader_pod(warming,pools,None,+ None,std::sync::Arc::clone(&emitted_versions),);+ let authority = Arc::new(AuthorityClock::unclaimed());let pod = PodHandle::new(store,PodConfig {@@ -377,6 +380,7 @@ pub async fn start_leader_pod(},Arc::new(handler),None,+ authority,);let pod_token = cancel.child_token();tokio::spawn(async move { pod.run(pod_token).await });@@ -395,6 +399,10 @@ pub async fn start_leader_pod(PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),None,+ // A live claim rather than none, so the lease gate on the read+ // and write paths is exercised by every test built on this+ // fixture instead of being skipped by all of them.+ Some(live_authority()),std::sync::Arc::clone(&emitted_versions),);let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();@@ -453,8 +461,10 @@ pub async fn start_leader_pod_with_lease_ttl(warming,pools,None,+ None,std::sync::Arc::clone(&emitted_versions),);+ let authority = Arc::new(AuthorityClock::unclaimed());let pod = PodHandle::new(store,PodConfig {@@ -468,6 +478,7 @@ pub async fn start_leader_pod_with_lease_ttl(},Arc::new(handler),None,+ authority,);let pod_token = cancel.child_token();tokio::spawn(async move { pod.run(pod_token).await });@@ -485,6 +496,7 @@ pub async fn start_leader_pod_with_lease_ttl(PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),None,+ None,std::sync::Arc::clone(&emitted_versions),);let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();@@ -575,6 +587,7 @@ pub async fn start_leader_with_pg_fallback(PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),None,+ None,std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);@@ -624,43 +637,76 @@ pub fn fenced_producers_for(topic: &str) -> personhog_leader::fencing::FencedCha)}-/// A handoff handler sharing an inflight tracker with the caller, for-/// the drain's own admission fence.+/// A handoff handler wired to real fenced producers, in the shape+/// production runs: fencing on, and a lease whose renewals are current.+///+/// Deliberately not `None` for the authority. A fixture that leaves a+/// mechanism out makes every test written against it exercise the+/// degenerate path, and the gate stops being covered by anything —+/// which is exactly how all four of its call sites became deletable+/// with the suite green. Tests that need a lapsed claim pass their own.#[allow(dead_code)]-pub fn test_handoff_handler_with_inflight(+pub fn test_handoff_handler(topic: &str,fenced: Arc<personhog_leader::fencing::FencedChangelogProducers>,- inflight: Arc<personhog_leader::inflight::InflightTracker>,) -> personhog_leader::coordination::LeaderHandoffHandler {- let mut warming = test_warming_config("test", KAFKA_BOOTSTRAP);- warming.topic = topic.to_string();- personhog_leader::coordination::LeaderHandoffHandler::new(- Arc::new(PartitionedCache::new(1 << 20)),- inflight,- Arc::new(DirtyIndex::new(1_000_000)),- warming,- Arc::new(personhog_leader::warming::WarmClientPools::new(- &test_kafka_config(),- "test",- "personhog-writer",- )),- Some(fenced),- Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),+ handoff_handler_with(+ topic,+ fenced,+ Arc::new(personhog_leader::inflight::InflightTracker::new()),+ live_authority(),+ )+}++/// The same handler, holding an authority clock the caller controls.+///+/// Acquisition is gated on the published claim, so every branch that+/// declines to take the epoch is unreachable while the handler carries no+/// clock at all.+#[allow(dead_code)]+pub fn test_handoff_handler_with_authority(+ topic: &str,+ fenced: Arc<personhog_leader::fencing::FencedChangelogProducers>,+ authority: Arc<AuthorityClock>,+) -> personhog_leader::coordination::LeaderHandoffHandler {+ handoff_handler_with(+ topic,+ fenced,+ Arc::new(personhog_leader::inflight::InflightTracker::new()),+ authority,)}-/// A handoff handler wired to real fenced producers, for the convergence-/// steps whose whole point is what they do to the broker's epoch.+/// The same handler, sharing its inflight tracker with the caller — the+/// only way to observe when the drain closes admissions relative to when+/// it waits.#[allow(dead_code)]-pub fn test_handoff_handler(+pub fn test_handoff_handler_with_inflight(+ topic: &str,+ fenced: Arc<personhog_leader::fencing::FencedChangelogProducers>,+ inflight: Arc<personhog_leader::inflight::InflightTracker>,+) -> personhog_leader::coordination::LeaderHandoffHandler {+ handoff_handler_with(topic, fenced, inflight, live_authority())+}++/// Takes the authority clock by value rather than as an `Option`.+///+/// A fixture that can be built without one produces tests that exercise+/// the ungated path by default, and the gate stops being covered by+/// anything — which is how all four of its call sites became deletable+/// with the suite green. Requiring it makes that configuration+/// unbuildable rather than merely discouraged.+fn handoff_handler_with(topic: &str,fenced: Arc<personhog_leader::fencing::FencedChangelogProducers>,+ inflight: Arc<personhog_leader::inflight::InflightTracker>,+ authority: Arc<AuthorityClock>,) -> personhog_leader::coordination::LeaderHandoffHandler {let mut warming = test_warming_config("test", KAFKA_BOOTSTRAP);warming.topic = topic.to_string();personhog_leader::coordination::LeaderHandoffHandler::new(Arc::new(PartitionedCache::new(1 << 20)),- Arc::new(personhog_leader::inflight::InflightTracker::new()),+ inflight,Arc::new(DirtyIndex::new(1_000_000)),warming,Arc::new(personhog_leader::warming::WarmClientPools::new(@@ -669,6 +715,23 @@ pub fn test_handoff_handler("personhog-writer",)),Some(fenced),+ Some(authority),Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),)}++/// A clock holding a claim its keepalive is still confirming.+#[allow(dead_code)]+/// A claim that stays valid for the whole of any test.+///+/// The TTL is deliberately far longer than production's. Validity lapses+/// once no renewal has been confirmed for two thirds of the TTL, and+/// nothing renews this one — so a production-shaped 30s TTL gives a 20s+/// margin, which the fencing suite's longest tests already reach. Tests+/// that want a lapsed claim surrender explicitly rather than waiting one+/// out.+pub fn live_authority() -> Arc<AuthorityClock> {+ let clock = Arc::new(AuthorityClock::unclaimed());+ clock.begin_session(Duration::from_secs(3600), std::time::Instant::now());+ clock+}diff --git a/rust/personhog-leader/tests/fencing_integration.rs b/rust/personhog-leader/tests/fencing_integration.rsindex 657a0da14c06..6bfa63ad5bbb 100644--- a/rust/personhog-leader/tests/fencing_integration.rs+++ b/rust/personhog-leader/tests/fencing_integration.rs@@ -10,9 +10,11 @@ use std::sync::Arc;use std::time::Duration;use envconfig::Envconfig;+use personhog_coordination::authority::AuthorityClock;use personhog_coordination::pod::HandoffHandler;use personhog_leader::fencing::{- FenceGuard, FencedChangelogProducers, FencedProduceError, FencedProducerConfig,+ heal_fence, FenceGuard, FencedChangelogProducers, FencedProduceError, FencedProducerConfig,+ HealOutcome,};use personhog_leader::inflight::InflightTracker;use personhog_proto::personhog::types::v1::Person;@@ -346,7 +348,7 @@ async fn a_fence_taken_for_an_unfinished_warm_is_given_back() {{producers.acquire(0).await.expect("acquire");- let _guard = FenceGuard::new(Arc::clone(&producers), 0);+ let _guard = FenceGuard::new(Arc::clone(&producers), 0, "warm");// The warm ends here without returning, as a torn-down attempt// does.}@@ -364,7 +366,7 @@ async fn a_completed_warm_keeps_its_fence() {let producers = Arc::new(fenced_producers(&topic));producers.acquire(0).await.expect("acquire");- FenceGuard::new(Arc::clone(&producers), 0).keep();+ FenceGuard::new(Arc::clone(&producers), 0, "warm").keep();producers.produce(0, &test_person(1))@@ -422,7 +424,7 @@ async fn an_abandoned_guard_does_not_evict_its_replacement() {producers.acquire(0).await.expect("first acquire");// A warm takes the fence, then never finishes.- let stale = FenceGuard::new(Arc::clone(&producers), 0);+ let stale = FenceGuard::new(Arc::clone(&producers), 0, "warm");// Meanwhile the partition is released and taken again, so what is// installed is no longer what the guard is answerable for.@@ -437,6 +439,125 @@ async fn an_abandoned_guard_does_not_evict_its_replacement() {.expect("the replacement fence must survive the stale guard");}+/// A partition can end up served without a fence — a broker rejection+/// evicted it, an abort exhausted its retries, a stale pod took the+/// epoch and stepped back. Convergence sees such a partition warmed and+/// unfenced and does nothing, so this is what gets it writable again+/// before the next handoff.+#[tokio::test]+async fn healing_retakes_a_fence_for_a_served_partition() {+ let topic = format!("fence_heal_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers(&topic));+ let inflight = InflightTracker::new();+ let clock = AuthorityClock::unclaimed();+ clock.begin_session(Duration::from_secs(30), std::time::Instant::now());++ let outcome = heal_fence(&producers, &inflight, Some(&clock), 0).await;+ assert_eq!(+ outcome,+ Ok(HealOutcome::Healed),+ "the caller marks the partition freshly fenced on this answer"+ );++ producers+ .produce(0, &test_person(1))+ .await+ .expect("a served partition must regain a usable fence");+}++/// Healing takes the partition's epoch from whoever holds it, so a pod+/// that cannot vouch for its own claim must not start the round trip at+/// all — `init_transactions` cannot be undone once it returns, and the+/// post-acquire check can only stop *this* pod from building on a fence+/// it already stole.+///+/// The assertion is therefore on the victim. Asking only whether we+/// ended up holding a fence cannot tell the pre-check from the+/// post-check: both leave us empty-handed, and only one of them leaves+/// the legitimate owner still able to write.+#[tokio::test]+async fn healing_without_standing_does_not_steal_the_epoch() {+ let topic = format!("fence_heal_{}", uuid::Uuid::new_v4().simple());+ let inflight = InflightTracker::new();++ // The partition's real owner, holding a working fence.+ let owner = Arc::new(fenced_producers(&topic));+ owner.acquire(0).await.expect("the owner takes its fence");+ owner+ .produce(0, &test_person(1))+ .await+ .expect("the owner can write");++ // A pod whose claim is gone tries to heal the same partition.+ let zombie = Arc::new(fenced_producers(&topic));+ let lapsed = AuthorityClock::unclaimed();+ lapsed.begin_session(Duration::from_secs(30), std::time::Instant::now());+ lapsed.surrender();+ let outcome = heal_fence(&zombie, &inflight, Some(&lapsed), 0).await;+ assert_eq!(outcome, Ok(HealOutcome::Intact));++ owner+ .produce(0, &test_person(2))+ .await+ .expect("a pod with no standing must not take the epoch from the real owner");+}++/// A partition a handoff is already moving belongs to the incoming+/// owner, so healing must leave it alone for the same reason.+#[tokio::test]+async fn healing_skips_a_partition_under_handoff() {+ let topic = format!("fence_heal_{}", uuid::Uuid::new_v4().simple());+ let inflight = InflightTracker::new();++ let owner = Arc::new(fenced_producers(&topic));+ owner.acquire(0).await.expect("the owner takes its fence");++ let other = Arc::new(fenced_producers(&topic));+ let valid = AuthorityClock::unclaimed();+ valid.begin_session(Duration::from_secs(30), std::time::Instant::now());+ inflight.fence(0);+ let outcome = heal_fence(&other, &inflight, Some(&valid), 0).await;+ assert_eq!(outcome, Ok(HealOutcome::Intact));++ owner+ .produce(0, &test_person(1))+ .await+ .expect("a partition being handed off is not ours to take");+}++/// Standing can lapse *during* the broker round trip, by which point the+/// fence is installed. Keeping it is not passive: the write path trusts+/// the broker epoch rather than re-checking the claim, so a request+/// landing here would ack a mutation with an epoch taken from the+/// partition's real owner.+#[tokio::test]+async fn healing_gives_back_a_fence_it_lost_standing_for() {+ let topic = format!("fence_heal_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers(&topic));+ let inflight = InflightTracker::new();++ let clock = Arc::new(AuthorityClock::unclaimed());+ clock.begin_session(Duration::from_secs(30), std::time::Instant::now());+ let losing = Arc::clone(&clock);+ let lease_loss = tokio::spawn(async move {+ tokio::time::sleep(Duration::from_millis(5)).await;+ losing.surrender();+ });++ let outcome = heal_fence(&producers, &inflight, Some(&clock), 0).await;+ assert_ne!(+ outcome,+ Ok(HealOutcome::Healed),+ "a fence taken while standing lapsed must not be reported serving"+ );+ lease_loss.await.unwrap();++ match producers.produce(0, &test_person(1)).await {+ Err(FencedProduceError::NotAcquired) => {}+ other => panic!("a fence taken without standing must be given back, got {other:?}"),+ }+}+/// A writer parked behind a committing window is woken by the very commit/// that condemns the producer. Checking usability only before the park/// skips exactly that writer: it wakes, finds the gate idle, and opens a@@ -471,6 +592,46 @@ async fn a_writer_woken_onto_a_condemned_producer_is_bounced() {}}+/// Healing must leave a partition it already holds alone. Re-acquiring+/// runs `init_transactions`, which bumps the broker epoch — so a healing+/// pass that ignored the fence it is already holding would fence this+/// pod's own producer on every reconcile tick.+///+/// The damage lands on writes already in flight, not on the next one: a+/// fresh write simply uses whichever producer is installed. So the write+/// here is mid-window when the tick runs.+#[tokio::test]+async fn healing_leaves_a_fence_it_already_holds_alone() {+ let topic = format!("fence_heal_noop_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers_with_window(+ &topic,+ Duration::from_millis(600),+ ));+ let inflight = InflightTracker::new();+ let clock = AuthorityClock::unclaimed();+ clock.begin_session(Duration::from_secs(30), std::time::Instant::now());++ producers.acquire(0).await.expect("take the fence");++ // In flight: the window is open and its commit has not fired.+ let writing = {+ let p = Arc::clone(&producers);+ tokio::spawn(async move { p.produce(0, &test_person(1)).await })+ };+ tokio::time::sleep(Duration::from_millis(100)).await;++ // A reconcile tick with everything healthy.+ let outcome = heal_fence(&producers, &inflight, Some(&clock), 0).await;+ assert_eq!(outcome, Ok(HealOutcome::Intact));++ let result = writing.await.expect("the write task must not panic");+ assert!(+ result.is_ok(),+ "a healing pass must not fence the window this pod is already \+ filling, got {result:?}"+ );+}+/// A commit task that never reports its outcome must condemn the producer.////// `spawn_blocking` work is not cancelled when its handle drops, so the@@ -735,6 +896,7 @@ async fn a_repeated_resume_does_not_fence_the_window_the_first_one_admitted() {"a retried resume must not fence the window the first one admitted, got {result:?}");}+/// A drain that arrives while the window's commit is already running must/// wait for it.///@@ -811,6 +973,158 @@ async fn a_resume_that_took_the_fence_itself_does_not_take_it_again() {);}+/// Warming without a confirmed renewal must not take the epoch.+///+/// `init_transactions` grants the epoch to whoever initializes last, not+/// to whoever the protocol says owns the partition — so a zombie warming+/// on its way to noticing it is dead would fence the legitimate owner.+#[tokio::test]+async fn warming_without_a_confirmed_lease_does_not_take_the_epoch() {+ let topic = format!("fence_warm_auth_{}", uuid::Uuid::new_v4().simple());+ let owner = Arc::new(fenced_producers(&topic));+ owner.acquire(0).await.expect("the owner takes its fence");+ owner+ .produce(0, &test_person(1))+ .await+ .expect("the owner can write");++ let lapsed = common::live_authority();+ lapsed.surrender();+ let zombie = Arc::new(fenced_producers(&topic));+ let handler = common::test_handoff_handler_with_authority(&topic, Arc::clone(&zombie), lapsed);+ handler+ .warm_partition(0)+ .await+ .expect_err("a pod with no confirmed renewal must not warm");++ owner+ .produce(0, &test_person(2))+ .await+ .expect("a warm with no standing must not take the epoch from the real owner");+}++/// A resume without a confirmed renewal must not take the epoch either —+/// the same act, reached through the branch that cancels a handoff.+#[tokio::test]+async fn a_resume_without_a_confirmed_lease_does_not_take_the_epoch() {+ let topic = format!("fence_resume_auth_{}", uuid::Uuid::new_v4().simple());+ let owner = Arc::new(fenced_producers(&topic));+ owner.acquire(0).await.expect("the owner takes its fence");+ owner+ .produce(0, &test_person(1))+ .await+ .expect("the owner can write");++ let lapsed = common::live_authority();+ lapsed.surrender();+ let zombie = Arc::new(fenced_producers(&topic));+ let handler = common::test_handoff_handler_with_authority(&topic, Arc::clone(&zombie), lapsed);+ handler+ .resume_partition(0)+ .await+ .expect_err("a pod with no confirmed renewal must not resume");++ owner+ .produce(0, &test_person(2))+ .await+ .expect("a resume with no standing must not take the epoch from the real owner");+}++/// The claim can lapse *during* the acquire, by which point the epoch has+/// already moved. The pod cannot undo that, but it can decline to build on+/// a claim it no longer holds: it drops the fence and fails the+/// convergence, so the partition's real owner heals back to it instead of+/// finding a zombie serving on a stolen epoch.+#[tokio::test]+async fn a_warm_that_loses_its_claim_mid_acquire_gives_the_fence_back() {+ let topic = format!("fence_warm_midauth_{}", uuid::Uuid::new_v4().simple());+ // Seeded through a separate owner so the warm below is a real one: a+ // warm that fails for want of a topic would leave the fence behind+ // through its guard and prove nothing about this branch.+ let seed = fenced_producers(&topic);+ seed.acquire(0).await.expect("seed the topic");+ seed.produce(0, &test_person(1)).await.expect("seed record");++ let producers = Arc::new(fenced_producers(&topic));+ let clock = common::live_authority();+ let handler = common::test_handoff_handler_with_authority(+ &topic,+ Arc::clone(&producers),+ Arc::clone(&clock),+ );++ let losing = Arc::clone(&clock);+ let lease_loss = tokio::spawn(async move {+ sleep(Duration::from_millis(5)).await;+ losing.surrender();+ });+ let outcome = handler.warm_partition(0).await;+ lease_loss.await.unwrap();++ match outcome {+ // The surrender landed inside the warm: whichever check saw it,+ // an epoch taken across a lapsed claim is not this pod's to+ // keep.+ Err(_) => match producers.produce(0, &test_person(2)).await {+ Err(FencedProduceError::NotAcquired) => {}+ other => {+ panic!("a fence taken across a lapsed claim must be given back, got {other:?}")+ }+ },+ // The surrender lost the race outright — the claim was valid at+ // both checks, so the warm keeps its fence legitimately. A fast+ // broker reaches this branch; asserting the fence works keeps+ // the test meaningful there instead of panicking on good+ // behavior.+ Ok(()) => {+ producers+ .produce(0, &test_person(2))+ .await+ .expect("a warm whose claim never lapsed keeps a working fence");+ }+ }+}++/// The same window on the resume path.+#[tokio::test]+async fn a_resume_that_loses_its_claim_mid_acquire_gives_the_fence_back() {+ let topic = format!("fence_resume_midauth_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers(&topic));+ let clock = common::live_authority();+ let handler = common::test_handoff_handler_with_authority(+ &topic,+ Arc::clone(&producers),+ Arc::clone(&clock),+ );++ let losing = Arc::clone(&clock);+ let lease_loss = tokio::spawn(async move {+ sleep(Duration::from_millis(5)).await;+ losing.surrender();+ });+ let outcome = handler.resume_partition(0).await;+ lease_loss.await.unwrap();++ match outcome {+ // The surrender landed inside the resume: the fence it took+ // across a lapsed claim is not this pod's to keep.+ Err(_) => match producers.produce(0, &test_person(1)).await {+ Err(FencedProduceError::NotAcquired) => {}+ other => {+ panic!("a fence taken across a lapsed claim must be given back, got {other:?}")+ }+ },+ // The surrender lost the race outright — the claim held at both+ // checks and the resume keeps a working fence.+ Ok(()) => {+ producers+ .produce(0, &test_person(1))+ .await+ .expect("a resume whose claim never lapsed keeps a working fence");+ }+ }+}+/// The drain closes admissions before it waits, not after.////// Waiting first leaves a window where a request admitted during the wait@@ -877,6 +1191,114 @@ async fn releasing_a_partition_retires_its_fresh_fence_mark() {.expect("a resume after a release must take the fence again");}+/// The repair pass has to actually run for a condemned partition.+///+/// `heal_fence` knows how to retake an epoch this pod gave up on, but+/// convergence only reaches it through `verify_serving`. Without that+/// call a condemned partition stays warmed, unfenced, and unwritable for+/// the life of the process, with no branch left to re-acquire.+#[tokio::test]+async fn verifying_a_served_partition_retakes_a_condemned_fence() {+ let topic = format!("fence_verify_heal_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers(&topic));+ let handler = common::test_handoff_handler(&topic, Arc::clone(&producers));+ producers.acquire(0).await.expect("acquire the fence");++ // The state a failed abort or an unknown commit leaves behind.+ producers.condemn_for_test(0);+ assert!(+ !producers.holds(0),+ "a condemned producer must not still claim the partition"+ );++ let repaired = handler+ .verify_serving(0)+ .await+ .expect("verifying a served partition must not fail");+ assert!(+ repaired,+ "a heal that re-took the epoch is applied work, and must count as progress"+ );++ assert!(+ producers.holds(0),+ "a served partition whose fence was condemned must be healed back into service"+ );+}++/// A heal that cannot acquire must not fail the convergence run: the+/// run's failure budgets escalate to process death, which would trade+/// one partition's writes for every partition's reads. The wedge stays+/// visible through the partition-labeled failure counter and stays+/// retried by the reconcile tick — and the partition must still answer+/// as unfenced, never as quietly repaired.+#[tokio::test]+async fn a_heal_that_cannot_acquire_does_not_fail_the_run() {+ let topic = format!("fence_heal_err_{}", uuid::Uuid::new_v4().simple());+ let mut kafka = test_kafka_config();+ // Nothing listens here: the acquire's init round trip must fail.+ kafka.kafka_hosts = "127.0.0.1:1".to_string();+ let producers = Arc::new(FencedChangelogProducers::new(FencedProducerConfig {+ kafka,+ topic: topic.clone(),+ init_timeout: Duration::from_secs(2),+ commit_timeout: Duration::from_secs(2),+ broker_txn_timeout: BROKER_TXN_TIMEOUT,+ window: Duration::from_millis(5),+ settle_budget: Duration::from_secs(1),+ }));+ let handler = common::test_handoff_handler(&topic, Arc::clone(&producers));++ let outcome = handler.verify_serving(0).await;+ assert!(+ !outcome.expect("a wedged heal must not fail the run"),+ "an unhealed partition is not applied work"+ );+ assert!(+ !producers.holds(0),+ "a partition that could not be healed must still answer as unfenced"+ );+}++/// A heal is an acquisition like any other: the same convergence's+/// resume step must trust its fence rather than bump the epoch again.+/// Re-acquiring on resume would fence the very window the heal just made+/// writable — the double-acquire the fresh-fence mark exists to prevent.+#[tokio::test]+async fn a_healed_fence_is_not_reacquired_by_the_same_convergences_resume() {+ let topic = format!("fence_heal_mark_{}", uuid::Uuid::new_v4().simple());+ let producers = Arc::new(fenced_producers_with_window(+ &topic,+ Duration::from_millis(600),+ ));+ let handler = common::test_handoff_handler(&topic, Arc::clone(&producers));++ // A served partition with no usable fence — the state heal repairs.+ handler+ .verify_serving(0)+ .await+ .expect("healing a served partition must succeed");++ // In flight: the healed fence's window is open and uncommitted.+ let writing = {+ let p = Arc::clone(&producers);+ tokio::spawn(async move { p.produce(0, &test_person(1)).await })+ };+ sleep(Duration::from_millis(100)).await;++ handler+ .resume_partition(0)+ .await+ .expect("resuming a served partition must succeed");++ let result = writing.await.expect("the write task must not panic");+ assert!(+ result.is_ok(),+ "a resume in the same convergence must trust the healed fence, \+ not fence the window it is filling, got {result:?}"+ );+}+/// A committer that unwinds with subscribers still queued must condemn/// the producer, not strand them.///@@ -924,6 +1346,7 @@ async fn the_derived_production_timescales_compose_against_a_real_broker() {let mut config =personhog_leader::config::Config::init_from_env().expect("defaults are constructible");config.kafka_transactional_fencing = true;+ config.lease_gated_authority = true;config.lease_ttl = 30;config.fencing_txn_timeout_ms = 0;config.fencing_message_timeout_ms = 0;diff --git a/rust/personhog-leader/tests/integration.rs b/rust/personhog-leader/tests/integration.rsindex 692939778a57..3a06bea074cb 100644--- a/rust/personhog-leader/tests/integration.rs+++ b/rust/personhog-leader/tests/integration.rs@@ -187,6 +187,7 @@ async fn unowned_partition_returns_failed_precondition() {PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),None,+ None,std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);@@ -267,6 +268,7 @@ async fn missing_partition_metadata_returns_invalid_argument() {PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),None,+ None,std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);@@ -350,6 +352,7 @@ async fn mismatched_partition_metadata_returns_invalid_argument() {PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),None,+ None,std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);@@ -439,6 +442,7 @@ async fn writes_fenced_after_drain_reads_still_served() {PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),None,+ None,std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);// The handler shares the cache, inflight tracker, dirty index, and@@ -456,6 +460,7 @@ async fn writes_fenced_after_drain_reads_still_served() {warming,pools,None,+ None,std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);@@ -561,6 +566,7 @@ async fn drain_fences_before_waiting_on_inflight() {PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),None,+ None,std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);let warming = test_warming_config("fence-race-pod", KAFKA_BOOTSTRAP);@@ -576,6 +582,7 @@ async fn drain_fences_before_waiting_on_inflight() {warming,pools,None,+ None,std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),));@@ -881,6 +888,7 @@ async fn update_produces_person_state_to_kafka() {PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),None,+ None,std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);@@ -993,6 +1001,7 @@ async fn kafka_produce_failure_leaves_cache_unchanged() {PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),None,+ None,std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);@@ -1115,6 +1124,7 @@ async fn e2e_update_produces_to_local_kafka() {PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),None,+ None,std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);@@ -1447,6 +1457,7 @@ async fn evicted_dirty_person_recovers_from_changelog() {PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),None,+ None,std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);@@ -1547,6 +1558,7 @@ async fn dirty_person_with_failed_recovery_is_unavailable_not_stale() {PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),None,+ None,std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);@@ -1653,6 +1665,7 @@ async fn writes_shed_when_dirty_index_is_full() {PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),None,+ None,std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);@@ -1750,6 +1763,7 @@ async fn recovery_fails_when_record_version_disagrees_with_the_mark() {PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),None,+ None,std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);@@ -1857,6 +1871,7 @@ async fn recovery_reuses_the_partition_consumer_across_fetches() {PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),None,+ None,std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);@@ -2075,6 +2090,7 @@ async fn oversize_updates_are_rejected_and_oversized_rows_remediated() {WarningThrottle::new(DEFAULT_THROTTLE_PERIOD, NonZeroU32::new(2).unwrap()),),None,+ None,std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);@@ -2509,6 +2525,7 @@ async fn an_unresolved_version_is_never_reused() {PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),None,+ None,Arc::clone(&emitted_versions),);@@ -2587,6 +2604,7 @@ async fn a_fenced_write_that_bounces_does_not_hand_its_version_back() {PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),Some(Arc::clone(&fenced)),+ None,std::sync::Arc::new(personhog_leader::emitted::EmittedVersions::new(1_000_000)),);@@ -2703,6 +2721,7 @@ async fn an_unknown_outcome_keeps_its_version(PropertySizeLimits::new(655360, 524288),WarningsProducer::new(kafka_producer, "clickhouse_ingestion_warnings".to_string()),Some(Arc::clone(&fenced)),+ None,Arc::clone(&emitted_versions),);diff --git a/rust/personhog-router/src/config.rs b/rust/personhog-router/src/config.rsindex d85ee8382b23..43bc5b28002a 100644--- a/rust/personhog-router/src/config.rs+++ b/rust/personhog-router/src/config.rs@@ -2,6 +2,7 @@ use std::fmt;use std::str::FromStr;use envconfig::Envconfig;+use personhog_coordination::authority::AuthorityClock;use std::net::SocketAddr;use std::time::Duration;@@ -313,6 +314,55 @@ pub struct Config {mod tests {use super::*;+ fn leased(lease_ttl: i64, heartbeat_interval_secs: u64) -> Config {+ let mut config = Config::init_from_env().expect("defaults");+ config.lease_ttl = lease_ttl;+ config.heartbeat_interval_secs = heartbeat_interval_secs;+ config+ }++ /// The keepalive uses the heartbeat as the timeout for each renewal+ /// round, so a zero one times out instantly and the router fences+ /// itself against healthy etcd for as long as it runs — taking every+ /// handoff that needs its freeze ack with it.+ #[test]+ fn a_zero_heartbeat_is_refused() {+ assert!(leased(10, 0).validate_lease_timescales().is_err());+ }++ /// A heartbeat past the renewal margin exhausts the lease by sleeping,+ /// with the same result.+ #[test]+ fn a_heartbeat_the_lease_cannot_fit_is_refused() {+ assert!(leased(10, 30).validate_lease_timescales().is_err());+ }++ #[test]+ fn a_heartbeat_well_inside_the_margin_is_accepted() {+ assert!(leased(10, 2).validate_lease_timescales().is_ok());+ }++ /// The coordinator election lease runs the same keepalive on its own+ /// pair of knobs; a misconfigured pair reproduces the same+ /// self-fencing loop, stalling every handoff behind the coordinator.+ #[test]+ fn a_coordinator_keepalive_the_lease_cannot_fit_is_refused() {+ let mut config = leased(10, 2);+ config.coordinator_lease_ttl = 10;+ config.coordinator_keepalive_secs = 30;+ assert!(config.validate_lease_timescales().is_err());+ config.coordinator_keepalive_secs = 0;+ assert!(config.validate_lease_timescales().is_err());+ config.coordinator_keepalive_secs = 2;+ assert!(config.validate_lease_timescales().is_ok());++ // A disabled coordinator never reads these knobs, so they must+ // not be able to refuse startup.+ config.coordinator_keepalive_secs = 0;+ config.coordinator_enabled = false;+ assert!(config.validate_lease_timescales().is_ok());+ }+// ── ReplicaDiscoveryMode ──────────────────────────────────────────────────#[test]@@ -476,6 +526,66 @@ impl Config {Duration::from_secs(self.heartbeat_interval_secs)}+ /// Refuse a heartbeat the lease cannot survive.+ ///+ /// The router holds an etcd lease and votes in the freeze quorum,+ /// on the same keepalive the leader runs — which uses this interval+ /// as the timeout for each renewal round. A zero one times out+ /// instantly and a slow one sleeps through the margin, and either+ /// exhausts the lease against healthy etcd. The router then+ /// deregisters and starts over for as long as it runs, and every+ /// handoff that needs its freeze ack waits on a participant that+ /// keeps leaving.+ ///+ /// The coordinator election lease runs the same keepalive with its+ /// own pair of knobs, so it gets the same refusal: a coordinator+ /// that keeps fencing itself stalls every handoff behind it.+ pub fn validate_lease_timescales(&self) -> Result<(), String> {+ Self::validate_keepalive_pair(+ "HEARTBEAT_INTERVAL_SECS",+ self.heartbeat_interval(),+ "LEASE_TTL",+ self.lease_ttl,+ )?;+ // Only where a coordinator can actually run: refusing startup+ // over knobs a disabled coordinator never reads would turn dead+ // config into an outage.+ if !self.coordinator_enabled {+ return Ok(());+ }+ Self::validate_keepalive_pair(+ "COORDINATOR_KEEPALIVE_SECS",+ self.coordinator_keepalive_interval(),+ "COORDINATOR_LEASE_TTL",+ self.coordinator_lease_ttl,+ )+ }++ fn validate_keepalive_pair(+ interval_name: &str,+ interval: Duration,+ ttl_name: &str,+ ttl: i64,+ ) -> Result<(), String> {+ let margin = AuthorityClock::renewal_margin(ttl);+ if interval.is_zero() {+ return Err(format!(+ "{interval_name} must be greater than zero: the keepalive uses it as the \+ timeout for each renewal round, so a zero interval fences the holder \+ against healthy etcd in a loop it cannot leave"+ ));+ }+ if interval >= margin {+ return Err(format!(+ "{interval_name} ({interval:?}) must be well under the keepalive renewal \+ margin ({margin:?} = 2/3 of {ttl_name} {ttl}s): the sleep between renewals \+ would exhaust the margin on its own, and the holder would fence itself \+ against healthy etcd"+ ));+ }+ Ok(())+ }+pub fn coordinator_keepalive_interval(&self) -> Duration {Duration::from_secs(self.coordinator_keepalive_secs)}diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rsindex 7dd5e517f0a3..6ebe36144577 100644--- a/rust/personhog-router/src/main.rs+++ b/rust/personhog-router/src/main.rs@@ -36,6 +36,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {.expect("Failed to install rustls crypto provider");let config = Config::init_from_env().expect("Invalid configuration");+ if let Err(e) = config.validate_lease_timescales() {+ panic!("invalid lease configuration: {e}");+ }preregister_metrics();// Initialize tracingdiff --git a/rust/personhog-stateright/README.md b/rust/personhog-stateright/README.mdindex 0828e92fd3a2..9cbd4b0d8837 100644--- a/rust/personhog-stateright/README.md+++ b/rust/personhog-stateright/README.md@@ -181,6 +181,17 @@ cutover (thaw ordering); multi-partition rebalance gating; concurrenthandoffs (probed reachable, safety checked throughout); the dual-rolepod shape (probed unreachable — see Results).+The claim to serve is modeled apart from the lease (`Pod.claims_authority`,+production's `AuthorityClock`), because in production the two diverge and+the interesting failures live in the gap: a revoked lease leaves a pod+claiming what it no longer holds until something tells it. `ClaimDetection`+selects whether that is immediate — the pod watching its own registration —+or waits for a keepalive round, and the verdict pins that only the prompt+form closes the stale-read half. Stability now also requires the assigned+owner to still claim its partitions, so an owner that refuses its own+reads while looking alive to the coordinator fails liveness rather than+passing quietly.+Known remaining abstractions: warming is instant and atomic (productionstreams from Kafka with retries — availability, not safety); stashdeadlines/bounds are not modeled (availability policies); thediff --git a/rust/personhog-stateright/src/main.rs b/rust/personhog-stateright/src/main.rsindex 7707e4e27999..7b2c9274594a 100644--- a/rust/personhog-stateright/src/main.rs+++ b/rust/personhog-stateright/src/main.rs@@ -11,7 +11,7 @@use clap::{Parser, ValueEnum};-use personhog_stateright::model::{HandoffModel, Variant, WarmOrder};+use personhog_stateright::model::{ClaimDetection, HandoffModel, Variant, WarmOrder};use stateright::Model;#[derive(Parser)]@@ -49,6 +49,9 @@ fn main() {partitions: 1,variant,warm_order,+ lease_gated_reads: false,+ claim_recovers: true,+ claim_detection: ClaimDetection::Prompt,writes: 2,reads: 1,crashes,diff --git a/rust/personhog-stateright/src/model.rs b/rust/personhog-stateright/src/model.rsindex 2c9caf7f4a0f..2476171085b0 100644--- a/rust/personhog-stateright/src/model.rs+++ b/rust/personhog-stateright/src/model.rs@@ -73,6 +73,21 @@ pub enum Variant {EpochFenced,}+/// How promptly a pod learns that its lease is gone.+///+/// The keepalive only finds out on its next round, so a revoked lease+/// leaves the pod claiming a partition the coordinator can already have+/// reassigned. Production closes that by watching its own registration;+/// `Delayed` is what the window looks like without it.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ClaimDetection {+ /// The registration watch: the claim drops with the registration.+ Prompt,+ /// Keepalive-only: the claim outlives the registration until a later+ /// round notices, which the checker explores as a separate step.+ Delayed,+}+/// Which side of the warm read acquires the broker fence, under/// `Variant::EpochFenced`. `warm_partition` ships `FenceFirst`;/// `ReadFirst` is the rejected ordering, kept checkable as the machine@@ -97,6 +112,19 @@ pub struct HandoffModel {/// Fence-vs-read ordering of the decomposed warm; ignored under/// `Variant::Current`, whose warm is a single atomic step.pub warm_order: WarmOrder,+ /// How promptly a pod notices its lease is gone; only meaningful+ /// with `lease_gated_reads`, since nothing else consults the claim.+ pub claim_detection: ClaimDetection,+ /// Whether a pod consults its lease before serving a strong read+ /// (production: the leader's `LEASE_GATED_AUTHORITY`). Without it a+ /// pod that has lost its registration keeps answering out of a cache+ /// the new owner is already changing.+ pub lease_gated_reads: bool,+ /// Whether a lapsed claim can come back without the session ending+ /// (production: the keepalive confirming a renewal again). Turning it+ /// off is what makes the black hole permanent, which is the only way+ /// to show that stability actually notices one.+ pub claim_recovers: bool,/// Total client writes the checker may inject.pub writes: u8,/// Total strong reads the checker may inject.@@ -327,6 +355,23 @@ impl HandoffModel {if !pod.running {return false;}+ // The read gate: a pod that no longer claims the partition+ // refuses rather than serving from a cache it cannot vouch for.+ // The claim is what production actually consults — a stamp the+ // keepalive publishes — and it is not the same fact as holding+ // the lease, which is the whole point of modeling it separately.+ //+ // Production refuses on a margin against the last confirmed+ // renewal, which is a *later*-firing predicate than this one in+ // the case where a lease is revoked between keepalive rounds:+ // the stamp stays fresh for up to a heartbeat after the+ // registration is gone. The model is therefore optimistic about+ // that window, and the property holding here does not cover it —+ // it is recorded as a residual in the coordination README rather+ // than claimed as closed.+ if self.lease_gated_reads && !pod.claims_authority {+ return false;+ }let Some(warm) = pod.warmed.get(&partition) else {return false;};@@ -491,6 +536,7 @@ impl Model for HandoffModel {fenced: BTreeSet::new(),pending_warm: BTreeMap::new(),zombie_writes_left: 0,+ claims_authority: true,},)})@@ -578,6 +624,18 @@ impl Model for HandoffModel {}for pod in self.pod_ids() {actions.push(Action::SelfFence(pod));+ if self.claim_detection == ClaimDetection::Delayed {+ actions.push(Action::NoticeLeaseLoss(pod));+ }+ // Only meaningful when something consults the claim, and the+ // state space is expensive enough that exploring it in+ // configurations that ignore the claim would buy nothing.+ if self.lease_gated_reads {+ actions.push(Action::AuthorityLapse(pod));+ if self.claim_recovers {+ actions.push(Action::AuthorityRenew(pod));+ }+ }if state.rejoins_left > 0 {actions.push(Action::Join(pod));}@@ -1101,6 +1159,8 @@ impl Model for HandoffModel {pod.fenced.clear();pod.pending_warm.clear();pod.zombie_writes_left = 0;+ // A new session is a new claim.+ pod.claims_authority = true;}Action::CrashRestartWithinTtl(x) => {let pod = &state.pods[&x];@@ -1120,12 +1180,51 @@ impl Model for HandoffModel {}state.crashes_left -= 1;let zombie_window = self.zombie_window;+ let prompt = self.claim_detection == ClaimDetection::Prompt;let pod = state.pods.get_mut(&x).unwrap();pod.registered = false;+ // With the registration watch the claim drops here;+ // without it the pod keeps claiming until a later round+ // notices, which `NoticeLeaseLoss` explores as its own+ // step so every interleaving in between is checked.+ if prompt {+ pod.claims_authority = false;+ }if pod.running {pod.zombie_writes_left = zombie_window;}}+ // The gap the registration watch closes: between losing the+ // lease and noticing, the pod still answers as the owner.+ // The window production's clock actually creates: the stamp+ // ages past the margin at two thirds of the TTL, but etcd+ // holds the registration until the full TTL. For that third+ // the pod refuses to serve while still looking alive to the+ // coordinator — the black hole `converges_to_stable` has to+ // be able to see, and which tying the claim to the+ // registration made unrepresentable.+ Action::AuthorityLapse(x) => {+ let pod = &state.pods[&x];+ if !pod.registered || !pod.claims_authority {+ return None;+ }+ state.pods.get_mut(&x).unwrap().claims_authority = false;+ }+ Action::AuthorityRenew(x) => {+ let pod = &state.pods[&x];+ if !pod.registered || pod.claims_authority {+ return None;+ }+ state.pods.get_mut(&x).unwrap().claims_authority = true;+ }+ Action::NoticeLeaseLoss(x) => {+ let pod = &state.pods[&x];+ if pod.registered || !pod.claims_authority {+ return None;+ }+ state.pods.get_mut(&x).unwrap().claims_authority = false;+ }+Action::SelfFence(x) => {let pod = &state.pods[&x];if pod.registered || !pod.running {@@ -1137,6 +1236,7 @@ impl Model for HandoffModel {pod.fenced.clear();pod.pending_warm.clear();pod.zombie_writes_left = 0;+ pod.claims_authority = false;}Action::RouterLeaseExpire(r) => {if state.crashes_left == 0 || !state.routers[&r].registered {@@ -1290,6 +1390,11 @@ impl Model for HandoffModel {&& pod.running&& pod.registered&& m.write_capable(s, target, p)+ // A converged owner that refuses its+ // own reads is a black hole the+ // coordinator will not reassign,+ // because it still looks alive.+ && (!m.lease_gated_reads || pod.claims_authority)})))&& m.router_ids().all(|r| {let router = &s.routers[&r];diff --git a/rust/personhog-stateright/src/types.rs b/rust/personhog-stateright/src/types.rsindex 1aa8846aed02..12c0170e49cf 100644--- a/rust/personhog-stateright/src/types.rs+++ b/rust/personhog-stateright/src/types.rs@@ -99,6 +99,15 @@ pub struct Pod {/// 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,+ /// Whether this pod still claims the right to serve (production: the+ /// `AuthorityClock` the keepalive stamps and the data plane reads).+ ///+ /// Deliberately not the same fact as `registered`. A lease can be+ /// revoked out from under a pod, leaving it claiming a partition it+ /// no longer holds until something tells it otherwise — which is the+ /// window the read gate is trying to close, and cannot be expressed+ /// if the two are one flag.+ pub claims_authority: bool,}/// One router. A clean router restart is indistinguishable from a@@ -285,6 +294,20 @@ pub enum Action {/// The zombie's keepalive notices the dead lease and the process/// exits (production fix 1).SelfFence(PodId),+ /// A pod notices its lease is gone and stops claiming the partitions+ /// it holds (production: the keepalive's next round, or the+ /// registration watch firing). Only reachable under delayed+ /// detection; prompt detection drops the claim with the lease.+ NoticeLeaseLoss(PodId),+ /// A pod's published claim ages past the renewal margin while its+ /// registration still stands (production: the keepalive stops+ /// confirming, but etcd holds the lease until the full TTL). The pod+ /// refuses to serve and the coordinator, seeing a live registration,+ /// reassigns nothing.+ AuthorityLapse(PodId),+ /// A renewal lands and the claim comes back, without the session ever+ /// having ended.+ AuthorityRenew(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 thediff --git a/rust/personhog-stateright/tests/model_tests.rs b/rust/personhog-stateright/tests/model_tests.rsindex 030e5a6765f9..e16593070be6 100644--- a/rust/personhog-stateright/tests/model_tests.rs+++ b/rust/personhog-stateright/tests/model_tests.rs@@ -27,7 +27,7 @@use std::time::Instant;-use personhog_stateright::model::{HandoffModel, Variant, WarmOrder};+use personhog_stateright::model::{ClaimDetection, HandoffModel, Variant, WarmOrder};use stateright::{Checker, Model};/// Every checker explores in parallel: stateright defaults to a single@@ -50,6 +50,9 @@ fn base() -> HandoffModel {partitions: 1,variant: Variant::Current,warm_order: WarmOrder::FenceFirst,+ lease_gated_reads: false,+ claim_recovers: true,+ claim_detection: ClaimDetection::Prompt,writes: 2,reads: 1,crashes: 0,@@ -141,9 +144,8 @@ fn current_protocol_double_zombie_loses_acked_writes() {////// `strong_reads_complete` is deliberately not asserted here: it still/// fails, because a zombie pod serves reads from its stale cache and-/// nothing on the read path rejects them. Closing that needs a-/// lease-validity check on read admission — see the residual ledger in-/// `personhog-coordination/README.md`.+/// nothing rejects them when the read gate is off. Turning it on closes+/// that — see `fencing_and_lease_gated_reads_together_close_the_double_zombie`.#[test]fn epoch_fenced_double_zombie_is_safe() {let checker = model(Variant::EpochFenced, 2, 1)@@ -772,3 +774,143 @@ fn epoch_fenced_under_cancellation_is_safe_and_live() {.join().assert_properties();}++/// Fencing and the read gate are complementary, not alternative.+///+/// Fencing alone leaves `strong_reads_complete` violated under the+/// double zombie: it rejects a zombie's writes, not its reads, and the+/// zombie keeps answering from a cache the new owner is already+/// changing. The gate alone does not close it either — without fencing+/// the zombie's write is lost, so the *legitimate* owner is the one+/// serving a read missing an acked write. Only both together hold every+/// safety property, which is why the leader's read gate is a+/// prerequisite for enabling fencing rather than an independent+/// improvement.+#[test]+fn fencing_and_lease_gated_reads_together_close_the_double_zombie() {+ let cfg = |variant, gated| HandoffModel {+ variant,+ lease_gated_reads: gated,+ claim_recovers: true,+ crashes: 2,+ zombie_window: 1,+ ..base()+ };+ let stale_reads = |variant, gated| {+ cfg(variant, gated)+ .checker()+ .threads(parallelism())+ .spawn_bfs()+ .join()+ .discovery("strong_reads_complete")+ .is_some()+ };++ assert!(+ stale_reads(Variant::Current, true),+ "the read gate alone must not close it: the honest owner serves a read missing the \+ zombie's lost write"+ );+ assert!(+ stale_reads(Variant::EpochFenced, false),+ "fencing alone must not close it: the zombie still answers reads"+ );+ assert!(+ !stale_reads(Variant::EpochFenced, true),+ "together they must close it"+ );+}++/// The gate makes pods refuse reads, which is exactly the kind of change+/// that can starve liveness — so a gated configuration has to clear+/// every property, not just the stale-read one the complementarity+/// verdict inspects.+#[test]+fn a_lease_gated_fleet_is_safe_and_live() {+ HandoffModel {+ variant: Variant::EpochFenced,+ lease_gated_reads: true,+ claim_recovers: true,+ crashes: 1,+ zombie_window: 1,+ ..base()+ }+ .checker()+ .threads(parallelism())+ .spawn_bfs()+ .join()+ .assert_properties();+}++/// The state the stability property's claim conjunct exists for, made+/// reachable and then made permanent.+///+/// Production's clock lapses at two thirds of the TTL while etcd holds+/// the registration for the full TTL, so for that third a pod refuses+/// every read while still looking alive to the coordinator — which+/// therefore reassigns nothing. Tying the claim to the registration, as+/// the model previously did, made `registered` imply `claims_authority`+/// and left the conjunct unable to change any verdict.+///+/// With recovery available the fleet converges; without it the black+/// hole is permanent and stability has to notice. If this stops+/// producing a counterexample, the conjunct has gone back to being+/// decorative.+#[test]+fn a_lapsed_claim_that_never_returns_fails_stability() {+ let checker = HandoffModel {+ variant: Variant::EpochFenced,+ lease_gated_reads: true,+ claim_recovers: false,+ crashes: 1,+ zombie_window: 1,+ ..base()+ }+ .checker()+ .threads(parallelism())+ .spawn_bfs()+ .join();+ assert!(+ checker.discovery("converges_to_stable").is_some(),+ "an owner that refuses its own reads while looking alive to the coordinator \+ must fail stability rather than passing it"+ );+}++/// What the registration watch buys, as a verdict rather than prose.+///+/// A revoked lease deletes a pod's registration at once, but a pod that+/// only learns on its next keepalive round keeps claiming the partition+/// meanwhile — and the coordinator, which saw the deletion immediately,+/// can reassign inside that window. With detection delayed, the read+/// gate does not close the stale-read half at all; with the watch, it+/// does.+#[test]+fn prompt_detection_is_what_makes_the_read_gate_hold() {+ let stale_reads = |detection| {+ HandoffModel {+ variant: Variant::EpochFenced,+ lease_gated_reads: true,+ claim_recovers: true,+ claim_detection: detection,+ crashes: 2,+ zombie_window: 1,+ ..base()+ }+ .checker()+ .threads(parallelism())+ .spawn_bfs()+ .join()+ .discovery("strong_reads_complete")+ .is_some()+ };++ assert!(+ stale_reads(ClaimDetection::Delayed),+ "a claim outliving its lease must still leave stale reads reachable"+ );+ assert!(+ !stale_reads(ClaimDetection::Prompt),+ "dropping the claim with the registration must close them"+ );+}