Skip to content

: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.

chore(personhog): etcd resilience (#74478)

Zach Brown5ce36dc01bc2
diff --git a/rust/common/assignment-coordination/src/store.rs b/rust/common/assignment-coordination/src/store.rs
index dc071aa09e45..6956524c0630 100644
--- a/rust/common/assignment-coordination/src/store.rs
+++ b/rust/common/assignment-coordination/src/store.rs
@@ -1,5 +1,8 @@
+use std::time::Duration;
+
use etcd_client::{
- Client, DeleteOptions, GetOptions, PutOptions, Txn, TxnResponse, WatchOptions, WatchStream,
+ Client, ConnectOptions, DeleteOptions, GetOptions, PutOptions, Txn, TxnResponse, WatchOptions,
+ WatchStream,
};
use serde::de::DeserializeOwned;
use serde::Serialize;
@@ -28,7 +31,27 @@ pub struct EtcdStore {
impl EtcdStore {
pub async fn connect(config: StoreConfig) -> Result<Self> {
- let client = Client::connect(&config.endpoints, None).await?;
+ // Transport-level liveness so a silent network partition fails
+ // fast instead of hanging until TCP retransmission gives up
+ // (minutes — far past any lease TTL): HTTP/2 pings ride every
+ // connection, including idle ones and long-lived watch streams,
+ // and error all in-flight requests within roughly one ping
+ // interval plus its timeout of the peer going dark. Deliberately
+ // no per-request timeout — it would apply to the whole lifetime
+ // of a watch stream and kill healthy watches.
+ // The ping interval must clear etcd's server-side gRPC keepalive
+ // enforcement (--grpc-keepalive-min-time, default 5s): pings at or
+ // under the floor are strikes, and two strikes close the
+ // connection with GOAWAY. Idle pings are likewise strikes unless
+ // the server permits them, so they stay off — every component
+ // that matters holds an active watch or keepalive stream, and an
+ // idle channel is revalidated on next use within the connect
+ // timeout.
+ let options = ConnectOptions::new()
+ .with_connect_timeout(Duration::from_secs(5))
+ .with_keep_alive(Duration::from_secs(10), Duration::from_secs(5))
+ .with_keep_alive_while_idle(false);
+ let client = Client::connect(&config.endpoints, Some(options)).await?;
Ok(Self { client, config })
}
diff --git a/rust/common/assignment-coordination/src/util.rs b/rust/common/assignment-coordination/src/util.rs
index d0287fe80d01..78e98726b19f 100644
--- a/rust/common/assignment-coordination/src/util.rs
+++ b/rust/common/assignment-coordination/src/util.rs
@@ -1,4 +1,5 @@
use std::collections::HashMap;
+use std::time::{SystemTime, UNIX_EPOCH};
use crate::error::{Error, Result};
@@ -26,15 +27,15 @@ pub fn validate_identifier(name: &str) -> Result<()> {
}
pub fn now_seconds() -> i64 {
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64
}
pub fn now_millis() -> i64 {
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as i64
}
diff --git a/rust/personhog-coordination/README.md b/rust/personhog-coordination/README.md
index ba2f9bbed659..a8f88a30e952 100644
--- a/rust/personhog-coordination/README.md
+++ b/rust/personhog-coordination/README.md
@@ -73,7 +73,8 @@ Several failure modes are handled explicitly:
- **Warm provenance**: A pod records what each partition warm was installed for (serving, or a specific handoff id). Warming honors only a warm installed for the *current* handoff — one left over from an earlier ownership era is released and rebuilt, because its cache can hold values that predate writes the changelog accepted since, and a fresh warm replays only from the writer's committed offset. Without this, a returning owner whose `Released` convergence never ran could ack a warm it never performed and lose acknowledged writes — a counterexample the stateright model found and now pins.
- **Coordinator restart**: On startup, the coordinator runs `reconcile_pending_handoffs`. For every existing handoff it applies cleanup if `Complete`, otherwise calls `check_phase_advance` to nudge the state machine. This handles the case where acks were written before the coordinator was up — the ack-watch only fires on Put events, so without reconcile those acks would be invisible.
- **Reconcile tick**: Beyond the startup reconcile, the coordinator re-evaluates every in-flight handoff on a fixed interval (`reconcile_interval`, default 5 s). This is the liveness backstop for state changes that fire no watched event — e.g. a router departing (nothing watches router registrations) newly satisfying a freeze quorum. Everything the tick drives is idempotent: phase transitions use CAS and cleanup tolerates already-deleted records.
-- **Lease loss (self-fencing)**: A pod or router whose lease keepalive fails — including etcd answering a keepalive with TTL ≤ 0 for a revoked or expired lease — treats the lease as lost and exits its run loop immediately, skipping the graceful drain: the coordinator already considers it dead and is reassigning its partitions via the dead-owner path, so a graceful drain would only race that. This prevents a zombie owner from continuing to serve partitions the protocol has reassigned.
+- **Lease loss (self-fencing)**: Connection trouble and lease loss are different things. A broken or silent keepalive stream is a fact about one connection — the lease lives in etcd's replicated keyspace and stays valid until its TTL passes without renewal — so ambiguous keepalive failures rebuild the stream and retry (a fresh connection through the service reaches a healthy member) for as long as the last confirmed renewal is recent; a routine single-member restart costs some retries (`personhog_coordination_keepalive_retries_total{component}`), not a fence. The keepalive declares loss on exactly two signals: etcd answering a round with TTL ≤ 0 (authoritative — the lease is revoked or expired), or the renewal margin running out (two thirds of the TTL without a confirmed renewal — the final third is reserved so the fence completes before the coordinator can possibly treat the lease as expired; retrying past it would gamble split-brain against availability). On loss the component ends the coordination attempt immediately, skipping the graceful drain: the coordinator already considers it dead and is reassigning its partitions via the dead-owner path, so a graceful drain would only race that. A pod self-fences *locally* before anything else: every held partition is released (dropping its cache and serving authority — re-acquisition always re-warms), so a zombie owner can never keep serving partitions the protocol has reassigned; if that local fence itself fails, in-place recovery is refused and the process restarts. Lease loss is observed at every await the session makes while holding a lease — the attempt select, the backoff nap between failed attempts, and the graceful drain all race the keepalive — so once the keepalive declares loss, the fence is never deferred by supervisor state. Every other session end fences too — budget exhaustion and shutdown revoke the lease, which deletes the registration instantly, so the local fence runs first (a no-op after a completed graceful drain) and the dead-owner path never meets a still-serving owner. On lease loss the fence's drain budget is the runway the keepalive margin reserved (a third of the TTL), not the full graceful drain timeout; overshoot poisons recovery and the process restart clears stragglers by death.
+- **Supervised coordination runs (etcd resilience)**: A failed coordination attempt — a broken watch stream, a failed etcd write, an exhausted reconcile budget — no longer kills the process; the run supervisors tear the attempt down cleanly, back off exponentially, and rebuild through the same bootstrap that recovers a restarted process, while the data plane keeps serving. The two participant classes recover *differently*, on purpose. A **router** sheds its registration on every failed attempt (its registration is a freeze-quorum vote, and a registered but non-acking router would stall every quorum until the phase deadline); serving through its gap is safe because handoffs created while it is unregistered exclude it from their quorums and the leader-side fences reject its stale forwards. A **pod** does the opposite: its lease session (grant, register, heartbeat) lives *above* the attempt loop and survives attempt failures, so the coordinator keeps seeing a live pod and never runs the dead-owner path against a process that is still serving — the invariant is that serving authority is held exactly as long as the lease-backed registration behind it. This matters because the dead-owner path has no fence: its safety rests entirely on a deregistered owner being unable to produce, so a pod must never voluntarily deregister while it still serves. Only lease loss ends a pod session, self-fencing locally (every held partition released; re-acquisition re-warms) before a fresh session registers anew. A consecutive-failure budget (`ROUTER_RUN_RETRY_BUDGET`, default 10; same default on pods) keeps a genuinely wedged participant on the process-restart path; an attempt that made real progress — a convergence applied, a reconcile pass completed — resets the count, and the reset is keyed on measured progress rather than elapsed time because a time threshold silently exempts every failure detector slower than it (the reconcile budget and the stall watchdog both take a minute to fire), and `personhog_coordination_run_restarts_total{component}` counts every rebuild.
### Concurrency and atomicity
diff --git a/rust/personhog-coordination/src/coordinator.rs b/rust/personhog-coordination/src/coordinator.rs
index 612a1581bf92..f69d56193968 100644
--- a/rust/personhog-coordination/src/coordinator.rs
+++ b/rust/personhog-coordination/src/coordinator.rs
@@ -1,6 +1,7 @@
use std::collections::{HashMap, HashSet};
+use std::str::from_utf8;
use std::sync::Arc;
-use std::time::Duration;
+use std::time::{Duration, Instant};
use etcd_client::{EventType, WatchStream};
use metrics::{counter, gauge, histogram};
@@ -170,6 +171,7 @@ impl Coordinator {
/// election immediately instead of stranding it until TTL expiry.
/// `run` relies on that by awaiting this call to completion.
async fn try_lead(&self, cancel: CancellationToken) -> Result<bool> {
+ let granted_at = Instant::now();
let lease_id = self.store.grant_lease(self.config.leader_lease_ttl).await?;
let acquired = match self
@@ -206,12 +208,35 @@ impl Coordinator {
let keepalive_handle = {
let store = Arc::clone(&self.store);
let interval = self.config.keepalive_interval;
+ let lease_ttl = self.config.leader_lease_ttl;
let token = keepalive_cancel.clone();
let lease_lost = lease_lost.clone();
tokio::spawn(async move {
- if let Err(e) = util::run_lease_keepalive(store, lease_id, interval, token).await {
- tracing::error!(error = %e, "election lease keepalive failed");
- lease_lost.cancel();
+ // The keepalive runs as its own inner task so a panic
+ // surfaces as a JoinError here instead of silently
+ // unwinding this watcher: a leader whose keepalive died
+ // without signalling would coordinate on with no renewal
+ // until a successor is elected alongside it.
+ let inner = tokio::spawn(util::run_lease_keepalive(
+ store,
+ lease_id,
+ interval,
+ lease_ttl,
+ granted_at,
+ "coordinator",
+ token.clone(),
+ ));
+ let failure = match inner.await {
+ Ok(Ok(())) => (!token.is_cancelled())
+ .then(|| "election lease keepalive exited unexpectedly".to_string()),
+ Ok(Err(e)) => Some(format!("election lease keepalive failed: {e}")),
+ Err(join_err) => Some(format!("election lease keepalive panicked: {join_err}")),
+ };
+ if let Some(reason) = failure {
+ if !token.is_cancelled() {
+ tracing::error!(reason, "abdicating leadership");
+ lease_lost.cancel();
+ }
}
})
};
@@ -483,7 +508,7 @@ impl Coordinator {
for event in resp.events() {
if event.event_type() == EventType::Put {
let partition = event.kv().and_then(|kv| {
- let key = std::str::from_utf8(kv.key()).ok()?;
+ let key = from_utf8(kv.key()).ok()?;
store::extract_partition_from_ack_key(key)
});
diff --git a/rust/personhog-coordination/src/pod.rs b/rust/personhog-coordination/src/pod.rs
index fd3cdb727cdf..ffaf1423f969 100644
--- a/rust/personhog-coordination/src/pod.rs
+++ b/rust/personhog-coordination/src/pod.rs
@@ -1,5 +1,7 @@
use std::collections::{HashMap, HashSet};
+use std::result::Result as StdResult;
use std::str::from_utf8;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -9,6 +11,7 @@ use futures::future::BoxFuture;
use futures::stream::{FuturesUnordered, StreamExt};
use metrics::{counter, gauge, histogram};
use tokio::sync::{Mutex, Notify, Semaphore, SemaphorePermit};
+use tokio::task::JoinError;
use tokio_util::sync::CancellationToken;
use assignment_coordination::store::parse_watch_value;
@@ -115,6 +118,13 @@ pub trait HandoffHandler: Send + Sync {
/// Called when this pod is `new_owner` and handoff phase reaches `Warming`.
/// The HWM is guaranteed stable at this point — the old owner has drained
/// and no router is producing for this partition.
+ ///
+ /// May be cancelled mid-flight (the coordination loop is dropped on
+ /// lease loss and shutdown) and re-invoked later for the same
+ /// partition. Implementations must therefore leave no observable
+ /// partial state on cancellation — buffer and install atomically, as
+ /// the leader's warm does — because a cancelled warm is never
+ /// released: the pod only tracks a warm once this returns.
async fn warm_partition(&self, partition: u32) -> Result<()>;
/// Old owner: release the partition from this pod's local state (drop cache,
@@ -163,6 +173,13 @@ pub struct PodConfig {
/// must not restart the fleet, and sustained outage self-fences
/// through the lease keepalive.
pub reconcile_failure_budget: u32,
+ /// How many consecutive coordination-attempt failures the run
+ /// supervisor tolerates before giving up and letting the process
+ /// restart. An attempt that made real progress resets the count.
+ pub run_retry_budget: u32,
+ /// Base backoff between coordination attempts; doubles per
+ /// consecutive failure up to a fixed cap.
+ pub run_retry_backoff: Duration,
/// `host:port` where this pod's gRPC server is reachable; registered
/// so routers can dial the pod through the routing table.
pub advertise_address: Option<String>,
@@ -186,6 +203,8 @@ impl Default for PodConfig {
drain_timeout: Duration::from_secs(30),
reconcile_interval: Duration::from_secs(5),
reconcile_failure_budget: 12,
+ run_retry_budget: 10,
+ run_retry_backoff: Duration::from_millis(500),
advertise_address: None,
warm_concurrency: 4,
}
@@ -225,6 +244,10 @@ pub struct PodHandle {
drain_notify: Notify,
/// Bounds concurrent `warm_partition` calls to `warm_concurrency`.
warm_slots: Semaphore,
+ /// Set when a lease-loss self-fence failed: local serving state may
+ /// not reflect lost ownership, so the run supervisor must not retry
+ /// in place — only a process restart clears this.
+ fence_poisoned: AtomicBool,
/// Optional K8s awareness for departure classification during shutdown.
k8s_awareness: Option<Arc<K8sAwareness>>,
}
@@ -236,6 +259,14 @@ impl PodHandle {
handler: Arc<dyn HandoffHandler>,
k8s_awareness: Option<Arc<K8sAwareness>>,
) -> Self {
+ let renewal_margin = Duration::from_secs(config.lease_ttl.max(0) as u64).mul_f64(2.0 / 3.0);
+ assert!(
+ config.heartbeat_interval < renewal_margin,
+ "heartbeat_interval ({:?}) must be well under the keepalive renewal margin \
+ (2/3 of lease_ttl = {renewal_margin:?}): the post-renewal sleep alone would \
+ exhaust the margin and the pod would fence-loop against healthy etcd",
+ config.heartbeat_interval,
+ );
let warm_slots = Semaphore::new(config.warm_concurrency);
Self {
store,
@@ -245,116 +276,400 @@ impl PodHandle {
fenced_partitions: Mutex::new(HashSet::new()),
drain_notify: Notify::new(),
warm_slots,
+ fence_poisoned: AtomicBool::new(false),
k8s_awareness,
}
}
- /// Run the pod coordination loop. Blocks until cancelled.
+ /// 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,
+ /// heartbeat. The **attempt** level (`run_once`) owns only
+ /// convergence and the handoff watch.
+ ///
+ /// An attempt failure — a broken watch stream, a failed etcd write,
+ /// a phase-handler error — retries in place with the lease and
+ /// registration intact: the coordinator keeps seeing a live pod, so
+ /// it never runs the dead-owner path against a process that is
+ /// still serving, and the data plane keeps its cache. That is the
+ /// invariant this split enforces: serving authority is held exactly
+ /// as long as the lease-backed registration the coordinator's view
+ /// derives from. A handoff that tries to move a partition away
+ /// while the watch is down stalls awaiting this pod's ack and
+ /// resolves through the phase-deadline replacement machinery.
///
- /// 1. Register with etcd (creates lease + key)
- /// 2. Start heartbeat loop
- /// 3. Watch for handoff and assignment events
- /// 4. On cancellation (SIGTERM): transition to Draining, wait for
- /// partition handoffs to complete, then revoke lease and exit
+ /// Only lease loss ends a session, and it still self-fences — now
+ /// locally: every held partition is released before a new session
+ /// registers afresh, because the coordinator treats the expired
+ /// lease as death and may already be reassigning. Re-acquisition
+ /// always re-warms. A failed local fence poisons recovery and the
+ /// error propagates so a process restart clears everything.
+ ///
+ /// The registration asymmetry with the router is deliberate: a pod
+ /// holds data authority, so its registration must survive attempt
+ /// failures; a router holds freeze-quorum membership, so it sheds
+ /// its registration fast — a registered but non-acking router would
+ /// stall every freeze quorum until the phase deadline.
pub async fn run(&self, cancel: CancellationToken) -> Result<()> {
- let lease_id = self.store.grant_lease(self.config.lease_ttl).await?;
- self.register(lease_id).await?;
+ let mut consecutive_failures: u32 = 0;
+ // Set by the coordination loop whenever it applies real work
+ // (a convergence completed); consumed by each failure note to
+ // decide crash-loop vs fresh failure.
+ let progress = AtomicBool::new(false);
+ loop {
+ let (lease_id, granted_at) = match self.begin_session().await {
+ Ok(session) => session,
+ Err(e) => {
+ if cancel.is_cancelled() {
+ return Ok(());
+ }
+ if !self.note_run_failure(&mut consecutive_failures, &progress, &e) {
+ return Err(e);
+ }
+ if self.run_backoff(&cancel, consecutive_failures).await {
+ return Ok(());
+ }
+ continue;
+ }
+ };
- tracing::info!(pod = %self.config.pod_name, "registered with etcd");
+ // The heartbeat is session-scoped and outlives attempts: were
+ // it attempt-scoped, a failed attempt would let the lease
+ // lapse and reopen the deregistered-but-serving hole the
+ // 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.
+ let heartbeat_cancel = CancellationToken::new();
+ 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();
+ tokio::spawn(async move {
+ util::run_lease_keepalive(
+ store, lease_id, interval, lease_ttl, granted_at, "pod", token,
+ )
+ .await
+ })
+ };
- // Heartbeat runs for the entire pod lifetime, including drain phase.
- // This keeps the lease alive so the coordinator sees a Draining pod
- // (not a crashed one with an expired lease).
- let heartbeat_cancel = CancellationToken::new();
- let mut heartbeat_handle = {
- let store = Arc::clone(&self.store);
- let interval = self.config.heartbeat_interval;
- let token = heartbeat_cancel.child_token();
- tokio::spawn(async move {
- util::run_lease_keepalive(store, lease_id, interval, token).await
- })
- };
+ let mut lease_err: Option<Error> = None;
+ let mut fatal: Option<Error> = None;
+ // Attempts under this lease. The outer `select!` is what
+ // guarantees prompt exit even when the watch loop is parked
+ // inside a phase handler: the loop's own cancel check only
+ // runs between iterations, so racing the token here drops the
+ // in-flight future via cancel-by-drop, unwinding a stuck
+ // handler. The heartbeat is raced for the same reason — a pod
+ // that outlives its lease is a zombie, and lease loss must
+ // end the session immediately.
+ loop {
+ let result = tokio::select! {
+ r = self.run_once(cancel.clone(), &progress) => r,
+ r = &mut heartbeat_handle => {
+ let err = Self::heartbeat_exit_error(r);
+ tracing::error!(
+ pod = %self.config.pod_name,
+ error = %err,
+ "lease keepalive failed; self-fencing"
+ );
+ lease_err = Some(err);
+ break;
+ }
+ _ = cancel.cancelled() => Ok(()),
+ };
+ if cancel.is_cancelled() {
+ break;
+ }
+ let err = match result {
+ Ok(()) => break,
+ Err(e) => e,
+ };
+ if !self.note_run_failure(&mut consecutive_failures, &progress, &err) {
+ fatal = Some(err);
+ break;
+ }
+ // The nap races the heartbeat: every await under a live
+ // lease must observe lease loss promptly, and this one
+ // otherwise defers it by a full backoff period — the
+ // coordinator may already be reassigning while the pod
+ // serves, unaware, until the nap ends.
+ tokio::select! {
+ stop = self.run_backoff(&cancel, consecutive_failures) => {
+ if stop {
+ break;
+ }
+ }
+ r = &mut heartbeat_handle => {
+ let err = Self::heartbeat_exit_error(r);
+ tracing::error!(
+ pod = %self.config.pod_name,
+ error = %err,
+ "lease keepalive failed during backoff; self-fencing"
+ );
+ lease_err = Some(err);
+ break;
+ }
+ }
+ // Next attempt runs under the same lease: the
+ // registration was never given up, so the coordinator's
+ // view of this pod is unbroken.
+ }
- // Phase 1: Normal operation. The unified handoff protocol makes the
- // handoff watch the sole source of ownership transitions — assignment
- // changes only ever happen atomically with a handoff Complete event,
- // so there's no need to watch assignments separately.
- //
- // The outer `select!` against the cancel token is what guarantees a
- // prompt exit: dropping the loop future also drops every in-flight
- // convergence it is driving, so even a phase handler (e.g.
- // `warm_partition`) that blocks indefinitely cannot hold the pod
- // back from proceeding to drain + lease revoke.
- //
- // The heartbeat task is raced here too: the coordinator treats
- // lease expiry as pod death and hands this pod's partitions to
- // new owners, so a pod that outlives its lease is a zombie — it
- // would keep accepting writes for partitions the protocol has
- // already moved. Losing the lease therefore terminates the run
- // loop (self-fence) and the process restarts through the normal
- // lifecycle.
- let mut lease_lost = false;
- let result = tokio::select! {
- r = async {
- // Seed the loop with every partition this pod is involved
- // in before watching for new events. A pod that
- // crash-restarts within its lease TTL keeps its
- // registration and assignments but loses all in-memory
- // state (cache, fences) — and because nothing about etcd
- // changed, no event will ever arrive to repair the
- // divergence. Re-deriving local state from the durable
- // state at startup closes that structurally: cold assigned
- // partitions re-warm, in-flight handoffs get their
- // drain/warm/ack, completed ones release. The watch is
- // anchored to the snapshot's revision, so an event landing
- // between the snapshot and the watch attaching is replayed
- // rather than lost.
- let (initial, snapshot_revision) = self.involved_partitions().await?;
- let stream = self.store.watch_handoffs_from(snapshot_revision + 1).await?;
- self.watch_handoff_loop(stream, cancel.clone(), initial).await
- } => r,
- r = &mut heartbeat_handle => {
- lease_lost = true;
- let err = match r {
- Ok(Ok(())) => {
- Error::invalid_state("lease keepalive exited unexpectedly".to_string())
+ // Graceful drain only on external shutdown with a live
+ // lease. Skipped on lease loss: the coordinator already
+ // considers this pod dead and is reassigning via the
+ // dead-owner path — a graceful drain would only race it, and
+ // every status write would fail against the expired lease.
+ // The drain itself races the heartbeat for the same reason
+ // as every other live-lease await: the pod serves its
+ // partitions until their handoffs complete, so a lease lost
+ // mid-drain must switch to the local self-fence immediately
+ // rather than draining leaseless until the timeout.
+ if cancel.is_cancelled() && lease_err.is_none() {
+ tokio::select! {
+ r = self.drain(lease_id, &progress) => {
+ if let Err(e) = r {
+ tracing::warn!(pod = %self.config.pod_name, error = %e, "drain failed");
+ }
}
- Ok(Err(e)) => e,
- Err(join_err) => {
- Error::invalid_state(format!("keepalive task panicked: {join_err}"))
+ r = &mut heartbeat_handle => {
+ let err = Self::heartbeat_exit_error(r);
+ tracing::error!(
+ pod = %self.config.pod_name,
+ error = %err,
+ "lease keepalive failed during drain; self-fencing"
+ );
+ lease_err = Some(err);
}
+ }
+ }
+ let lease_lost = lease_err.is_some();
+
+ if !lease_lost {
+ // Fence before the registration disappears: revoking the
+ // lease deletes it instantly, and the dead-owner path the
+ // coordinator then runs has no fence of its own — its
+ // safety rests on a deregistered owner being unable to
+ // produce. This matters most on the budget-exhausted
+ // path, where the pod still holds and serves every
+ // partition; after a completed graceful drain it is a
+ // no-op. The heartbeat is still running here, so the
+ // fence has no lease-runway pressure — but on the
+ // shutdown path it does have a lifecycle budget: the
+ // graceful drain may already have spent its full
+ // timeout, and the process supervisor's window and the
+ // pod's termination grace period are sized around one
+ // drain timeout plus headroom, not two. Anything the
+ // drain could not quiesce in thirty seconds will not
+ // quiesce now; the fence's value here is stopping
+ // admissions (milliseconds) and giving stragglers a
+ // short grace, so its drain bound is a few seconds. The
+ // budget-exhausted path is not on the shutdown clock and
+ // keeps the full timeout.
+ let fence_bound = if cancel.is_cancelled() {
+ Duration::from_secs(3).min(self.config.drain_timeout)
+ } else {
+ self.config.drain_timeout
};
- tracing::error!(
- pod = %self.config.pod_name,
- error = %err,
- "lease keepalive failed; self-fencing"
- );
- Err(err)
+ if let Err(e) = self.self_fence_locally(fence_bound).await {
+ self.fence_poisoned.store(true, Ordering::SeqCst);
+ tracing::error!(
+ pod = %self.config.pod_name,
+ error = %e,
+ "pre-revoke self-fence failed; refusing in-place recovery"
+ );
+ }
+ heartbeat_cancel.cancel();
+ drop(heartbeat_handle.await);
+ drop(self.store.revoke_lease(lease_id).await);
+ } else {
+ // Self-fence locally before any new session: every held
+ // partition is released, dropping its cache and serving
+ // authority. Re-acquisition always re-warms, so nothing
+ // is lost but memory. A failed release poisons recovery.
+ // The drain budget is the lease runway the keepalive
+ // margin reserved — a third of the TTL — not the full
+ // graceful drain timeout: the coordinator reassigns at
+ // 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.
+ 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))
+ .await
+ {
+ self.fence_poisoned.store(true, Ordering::SeqCst);
+ tracing::error!(
+ pod = %self.config.pod_name,
+ error = %e,
+ "local self-fence failed; refusing in-place recovery"
+ );
+ }
}
- _ = cancel.cancelled() => Ok(()),
- };
- // Phase 2: If cancelled externally (SIGTERM), drain gracefully.
- // Skipped on lease loss: the coordinator already considers this
- // pod dead and is reassigning its partitions via the dead-owner
- // path — a graceful drain would race it, and every status write
- // would fail against the expired lease anyway.
- if cancel.is_cancelled() && !lease_lost {
- if let Err(e) = self.drain(lease_id).await {
- tracing::warn!(pod = %self.config.pod_name, error = %e, "drain failed");
+ if let Some(e) = fatal {
+ return Err(e);
+ }
+ if cancel.is_cancelled() {
+ return Ok(());
}
+ match lease_err {
+ Some(e) => {
+ if self.fence_poisoned.load(Ordering::SeqCst) {
+ // Serving state may not reflect the lost
+ // ownership; only a process restart clears it.
+ return Err(e);
+ }
+ if !self.note_run_failure(&mut consecutive_failures, &progress, &e) {
+ return Err(e);
+ }
+ if self.run_backoff(&cancel, consecutive_failures).await {
+ return Ok(());
+ }
+ // New session: fresh lease, fresh registration,
+ // ownership re-acquired through the warm path.
+ }
+ None => return Ok(()),
+ }
+ }
+ }
+
+ /// Classify the session keepalive task's exit. Any exit while the
+ /// session is live means the lease can no longer be trusted.
+ fn heartbeat_exit_error(result: StdResult<Result<()>, JoinError>) -> Error {
+ match result {
+ Ok(Ok(())) => Error::invalid_state("lease keepalive exited unexpectedly".to_string()),
+ Ok(Err(e)) => e,
+ Err(join_err) => Error::invalid_state(format!("keepalive task panicked: {join_err}")),
+ }
+ }
+
+ /// Grant a fresh lease and register under it — the start of a
+ /// coordination session.
+ async fn begin_session(&self) -> Result<(i64, Instant)> {
+ // The server's TTL countdown starts at the grant; anchoring the
+ // keepalive's margin clock any later would overstate runway by
+ // however long registration took.
+ let granted_at = Instant::now();
+ let lease_id = self.store.grant_lease(self.config.lease_ttl).await?;
+ self.register(lease_id).await?;
+ tracing::info!(pod = %self.config.pod_name, "registered with etcd");
+ Ok((lease_id, granted_at))
+ }
+
+ /// See `util::note_run_failure` for the progress-based reset
+ /// semantics.
+ fn note_run_failure(&self, consecutive: &mut u32, progress: &AtomicBool, err: &Error) -> bool {
+ util::note_run_failure(
+ consecutive,
+ progress,
+ self.config.run_retry_budget,
+ "pod",
+ &self.config.pod_name,
+ err,
+ )
+ }
+
+ /// Exponential backoff between recovery steps. Returns `true` when
+ /// cancelled during the wait.
+ async fn run_backoff(&self, cancel: &CancellationToken, consecutive: u32) -> bool {
+ const BACKOFF_CAP: Duration = Duration::from_secs(15);
+ let backoff = self
+ .config
+ .run_retry_backoff
+ .saturating_mul(2u32.saturating_pow(consecutive.saturating_sub(1)))
+ .min(BACKOFF_CAP);
+ tokio::select! {
+ _ = cancel.cancelled() => true,
+ _ = tokio::time::sleep(backoff) => false,
}
+ }
- // Cleanup: stop heartbeat and revoke lease. On lease loss the
- // heartbeat task has already exited (its handle must not be
- // awaited twice) and there is no lease left to revoke.
- if !lease_lost {
- heartbeat_cancel.cancel();
- drop(heartbeat_handle.await);
- drop(self.store.revoke_lease(lease_id).await);
+ /// One coordination attempt under a live session: converge every
+ /// involved partition from a fresh snapshot, then watch. Holds no
+ /// lease state — the session and its heartbeat outlive any number of
+ /// failed attempts. Convergence-before-watching is what makes each
+ /// attempt (and a crash-restart within the lease TTL) safe: local
+ /// state is re-derived from durable state, cold assigned partitions
+ /// re-warm, in-flight handoffs get their drain/warm/ack, completed
+ /// ones release, and the watch anchors to the snapshot revision so
+ /// nothing between snapshot and attach is lost.
+ async fn run_once(&self, cancel: CancellationToken, progress: &AtomicBool) -> Result<()> {
+ let (initial, snapshot_revision) = self.involved_partitions().await?;
+ let stream = self
+ .store
+ .watch_handoffs_from(snapshot_revision + 1)
+ .await?;
+ self.watch_handoff_loop(stream, cancel, initial, progress)
+ .await
+ }
+
+ /// Fence, quiesce, and release every locally held partition —
+ /// warmed or fenced — through the handler, clearing the pod's local
+ /// ownership state. Purely local: no etcd writes, callable with no
+ /// lease.
+ ///
+ /// The order per partition is load-bearing: `release_partition`
+ /// unfences and drops the cache without waiting, so releasing first
+ /// would let a write admitted before the lease was lost complete
+ /// its produce and ack after the replacement owner's warm — an
+ /// acked write the new owner never sees. Draining first (fence,
+ /// then wait for the inflight counter) guarantees that once this
+ /// returns, nothing this pod admitted can ack. Each drain is
+ /// bounded by the drain timeout; a partition that cannot quiesce
+ /// fails the fence, which the caller poisons — the process restart
+ /// then clears the stuck in-flight work by death, exactly as the
+ /// pre-supervisor design did. The window before the lease loss is
+ /// even *detected* (up to one heartbeat tick) remains the
+ /// documented zombie residual; this closes only the part the local
+ /// fence itself controls.
+ async fn self_fence_locally(&self, drain_bound: Duration) -> Result<()> {
+ let held: HashSet<u32> = {
+ let warmed = self.warmed_partitions.lock().await;
+ let fenced = self.fenced_partitions.lock().await;
+ warmed
+ .keys()
+ .copied()
+ .chain(fenced.iter().copied())
+ .collect()
+ };
+ // Phase 1: fence and quiesce every partition CONCURRENTLY. Each
+ // drain fences as its first action, so running them together
+ // stops all admissions within milliseconds of each other and
+ // bounds the whole quiesce by a single drain timeout. Draining
+ // sequentially would leave later partitions serving — leaseless
+ // — while earlier ones wait out their in-flight work, extending
+ // the zombie window per held partition.
+ let mut drains = tokio::task::JoinSet::new();
+ for &partition in &held {
+ let handler = Arc::clone(&self.handler);
+ let timeout = drain_bound;
+ drains.spawn(async move {
+ tokio::time::timeout(timeout, handler.drain_partition_inflight(partition))
+ .await
+ .map_err(|_| {
+ Error::invalid_state(format!(
+ "self-fence drain timed out for partition {partition}"
+ ))
+ })?
+ });
+ }
+ while let Some(joined) = drains.join_next().await {
+ joined
+ .map_err(|e| Error::invalid_state(format!("self-fence drain panicked: {e}")))??;
}
- result
+ // Phase 2: with nothing in flight anywhere, release each
+ // partition (dropping cache and serving authority) and clear
+ // the local ownership state.
+ for partition in held {
+ self.handler.release_partition(partition).await?;
+ self.warmed_partitions.lock().await.remove(&partition);
+ self.fenced_partitions.lock().await.remove(&partition);
+ }
+ gauge!("personhog_coordination_partitions_held").set(0.0);
+ Ok(())
}
async fn register(&self, lease_id: i64) -> Result<()> {
@@ -390,7 +705,7 @@ impl PodHandle {
///
/// For StatefulSet rollouts, the same pod name comes back with a new
/// revision, so we skip the drain and exit immediately (ShutdownNow).
- async fn drain(&self, lease_id: i64) -> Result<()> {
+ async fn drain(&self, lease_id: i64, progress: &AtomicBool) -> Result<()> {
let reason = self.classify_departure().await;
// StatefulSet rollout: same pod name returns, no need to drain
@@ -436,7 +751,7 @@ impl PodHandle {
.await?;
tokio::select! {
- r = self.watch_handoff_loop(stream, drain_cancel.clone(), initial) => {
+ r = self.watch_handoff_loop(stream, drain_cancel.clone(), initial, progress) => {
r?;
},
_ = self.wait_for_drain() => {
@@ -525,7 +840,7 @@ impl PodHandle {
/// convergence acts on observed durable state, never on remembered
/// event payloads, so missed, reordered, or replayed events cannot
/// corrupt local state.
- async fn converge(&self, partition: u32) -> Result<()> {
+ async fn converge(&self, partition: u32) -> Result<bool> {
let handoff = self.store.get_handoff(partition).await?;
let assignment = self.store.get_assignment(partition).await?;
self.apply(partition, assignment.as_ref(), handoff.as_ref())
@@ -547,14 +862,21 @@ impl PodHandle {
/// runs at most one convergence per partition at a time, so no two
/// applications for the same partition ever interleave — applications
/// for different partitions may run concurrently.
+ ///
+ /// Returns whether the application changed local state (a warm, a
+ /// fence, a resume, a release). A convergence that merely confirms
+ /// the partition is already settled is a read, and the run budget's
+ /// progress signal must not count it — a pod whose coordination is
+ /// wedged still no-op-converges its settled partitions successfully.
async fn apply(
&self,
partition: u32,
assignment: Option<&PartitionAssignment>,
handoff: Option<&HandoffState>,
- ) -> Result<()> {
+ ) -> Result<bool> {
let pod = &self.config.pod_name;
let desired = desired_state(pod, assignment, handoff);
+ let mut did_work = false;
match desired {
DesiredState::Serving => {
@@ -569,11 +891,21 @@ impl PodHandle {
.lock()
.await
.insert(partition, WarmProvenance::Serving);
- } else if self.fenced_partitions.lock().await.contains(&partition) {
+ 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
+ // before the handoff was cancelled), and relying on the
+ // handler's warm to lift the fence would make write
+ // admission depend on an undocumented handler side
+ // effect. Resuming after a warm that already unfenced is
+ // an idempotent no-op.
+ if self.fenced_partitions.lock().await.remove(&partition) {
tracing::info!(pod, partition, "converging to Serving: resuming writes");
self.handler.resume_partition(partition).await?;
+ did_work = true;
}
- self.fenced_partitions.lock().await.remove(&partition);
}
DesiredState::Drained { ack } => {
// The coordinator only advances Freezing → Draining once
@@ -585,6 +917,7 @@ impl PodHandle {
let newly_fencing = !self.fenced_partitions.lock().await.contains(&partition);
if newly_fencing {
tracing::info!(pod, partition, "converging to Drained: fencing + draining");
+ did_work = true;
}
let start = Instant::now();
self.handler.drain_partition_inflight(partition).await?;
@@ -650,6 +983,7 @@ impl PodHandle {
partition,
WarmProvenance::Handoff(handoff.handoff_id.clone()),
);
+ did_work = true;
}
self.fenced_partitions.lock().await.remove(&partition);
self.store
@@ -675,6 +1009,7 @@ impl PodHandle {
self.handler.release_partition(partition).await?;
counter!("personhog_coordination_partition_releases_total").increment(1);
self.drain_notify.notify_one();
+ did_work = true;
}
}
}
@@ -682,7 +1017,7 @@ impl PodHandle {
gauge!("personhog_coordination_partitions_held")
.set(self.held_partition_count().await as f64);
- Ok(())
+ Ok(did_work)
}
async fn watch_handoff_loop(
@@ -690,6 +1025,7 @@ impl PodHandle {
mut stream: WatchStream,
cancel: CancellationToken,
initial: HashSet<u32>,
+ progress: &AtomicBool,
) -> Result<()> {
// The truth path: periodically re-derive the involved-partition
// set from a fresh snapshot and re-dispatch each member,
@@ -700,6 +1036,7 @@ impl PodHandle {
tokio::time::Instant::now() + self.config.reconcile_interval,
self.config.reconcile_interval,
);
+ reconcile_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
// Convergence is single-flight per partition: at most one
// `converge` future per partition lives in `lanes` at a time,
@@ -712,7 +1049,7 @@ impl PodHandle {
// absorbs any number of coalesced signals. Dropping this loop
// future drops every in-flight convergence with it, so cancel
// semantics are unchanged from converging inline.
- let mut lanes: FuturesUnordered<BoxFuture<'_, (u32, Trigger, Result<()>)>> =
+ let mut lanes: FuturesUnordered<BoxFuture<'_, (u32, Trigger, Result<bool>)>> =
FuturesUnordered::new();
let mut in_flight: HashSet<u32> = HashSet::new();
let mut pending: HashMap<u32, Trigger> = HashMap::new();
@@ -723,7 +1060,7 @@ impl PodHandle {
trigger: Trigger,
in_flight: &mut HashSet<u32>,
pending: &mut HashMap<u32, Trigger>,
- lanes: &mut FuturesUnordered<BoxFuture<'s, (u32, Trigger, Result<()>)>>,
+ lanes: &mut FuturesUnordered<BoxFuture<'s, (u32, Trigger, Result<bool>)>>,
) {
if in_flight.contains(&partition) {
// Coalesce, keeping the stricter error disposition: a
@@ -867,7 +1204,17 @@ impl PodHandle {
Some((partition, trigger, result)) = lanes.next(), if !lanes.is_empty() => {
in_flight.remove(&partition);
match result {
- Ok(()) => {
+ Ok(did_work) => {
+ // Progress means *applied* work — a handler
+ // invoked, local serving state changed — never
+ // a successful read. A no-op convergence of an
+ // already-settled partition succeeds even on a
+ // pod whose coordination is otherwise wedged,
+ // and counting it would make the run budget
+ // unreachable in exactly that wedge.
+ if did_work {
+ progress.store(true, Ordering::SeqCst);
+ }
if trigger == Trigger::Reconcile {
window_ok = true;
}
diff --git a/rust/personhog-coordination/src/routing_table.rs b/rust/personhog-coordination/src/routing_table.rs
index 52c7fb3e2241..f67cca0ca3d6 100644
--- a/rust/personhog-coordination/src/routing_table.rs
+++ b/rust/personhog-coordination/src/routing_table.rs
@@ -1,5 +1,6 @@
use std::collections::{HashMap, HashSet};
-use std::sync::atomic::{AtomicU64, Ordering};
+use std::str::from_utf8;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex as StdMutex, RwLock as StdRwLock};
use std::time::{Duration, Instant};
@@ -221,6 +222,14 @@ pub struct RoutingTableConfig {
/// (freeze-ack re-assertion, yielded-drain re-requests, address
/// refresh).
pub reconcile_failure_budget: u32,
+ /// How many consecutive coordination-attempt failures the run
+ /// supervisor tolerates before giving up and letting the process
+ /// restart. An attempt that ran healthily before failing resets the
+ /// count, so the budget bounds crash loops, not lifetime failures.
+ pub run_retry_budget: u32,
+ /// Base backoff between coordination attempts; doubles per
+ /// consecutive failure up to a fixed cap.
+ pub run_retry_backoff: Duration,
}
impl Default for RoutingTableConfig {
@@ -236,6 +245,8 @@ impl Default for RoutingTableConfig {
participant_stall_threshold: Some(Duration::from_secs(60)),
reconcile_interval: Duration::from_secs(5),
reconcile_failure_budget: 12,
+ run_retry_budget: 10,
+ run_retry_backoff: Duration::from_millis(500),
}
}
}
@@ -275,6 +286,14 @@ 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);
+ assert!(
+ config.heartbeat_interval < renewal_margin,
+ "heartbeat_interval ({:?}) must be well under the keepalive renewal margin \
+ (2/3 of lease_ttl = {renewal_margin:?}): the post-renewal sleep alone would \
+ exhaust the margin and the router would deregister against healthy etcd",
+ config.heartbeat_interval,
+ );
Self {
store,
config,
@@ -307,44 +326,150 @@ impl RoutingTable {
Arc::clone(&self.addresses)
}
- /// Run the routing table. Registers with etcd, loads the initial state,
- /// then watches the handoffs keyspace. Blocks until cancelled. Routing
- /// changes flow exclusively through handoff Complete events; there is
- /// no separate assignment watch.
+ /// Run the routing table, supervising the coordination loop across
+ /// etcd failures. Each attempt registers with etcd, loads the
+ /// initial state, and watches the handoffs keyspace; when an attempt
+ /// fails (a broken watch stream, a failed etcd write, an exhausted
+ /// reconcile budget), the failure is contained here instead of
+ /// killing the process: the data plane keeps serving from the
+ /// last-known routing table and the stash keeps its parked clients
+ /// while the coordination layer rebuilds in place through the same
+ /// bootstrap that recovers a restarted process.
+ ///
+ /// Serving while disconnected is safe because ownership cannot move
+ /// while etcd is unreachable — the coordinator cannot advance
+ /// handoffs — and once etcd recovers, any handoff created before we
+ /// re-register excludes us from its freeze quorum, so the old owner
+ /// fences before a new owner warms and our stale forwards bounce
+ /// into the drain/retry machinery rather than landing.
+ ///
+ /// Retries back off exponentially and are budgeted by consecutive
+ /// failures (an attempt that made real progress — a reconcile pass
+ /// completed, a handoff event applied — resets the count); past the
+ /// budget the last error is returned and the process-restart path
+ /// takes over as the backstop.
+ pub async fn run(
+ &self,
+ cancel: CancellationToken,
+ handler: Arc<dyn StashHandler>,
+ ) -> Result<()> {
+ const BACKOFF_CAP: Duration = Duration::from_secs(15);
+
+ let mut consecutive_failures: u32 = 0;
+ // Set by the coordination loop whenever it does real work;
+ // consumed by each failure note to decide crash-loop vs fresh
+ // failure. Arc because the watch loop runs as a spawned task.
+ let progress = Arc::new(AtomicBool::new(false));
+ loop {
+ let result = self
+ .run_once(cancel.clone(), Arc::clone(&handler), &progress)
+ .await;
+ if cancel.is_cancelled() {
+ return result;
+ }
+ let err = match result {
+ Ok(()) => return Ok(()),
+ Err(e) => e,
+ };
+
+ if !util::note_run_failure(
+ &mut consecutive_failures,
+ &progress,
+ self.config.run_retry_budget,
+ "router",
+ &self.config.router_name,
+ &err,
+ ) {
+ return Err(err);
+ }
+
+ let backoff = self
+ .config
+ .run_retry_backoff
+ .saturating_mul(2u32.saturating_pow(consecutive_failures.saturating_sub(1)))
+ .min(BACKOFF_CAP);
+ tokio::select! {
+ _ = cancel.cancelled() => return Ok(()),
+ _ = tokio::time::sleep(backoff) => {}
+ }
+ }
+ }
+
+ /// One coordination attempt: register, load initial state, watch.
+ /// Runs its own teardown on every exit path — tasks joined, drains
+ /// joined, lease revoked best-effort (an unreachable etcd lets it
+ /// lapse by TTL, which quorums already treat as departure) — so the
+ /// supervisor above can always start the next attempt from a clean
+ /// slate.
///
/// The `handler` implements stashing and drain. It's invoked on handoff
/// phase transitions: `begin_stash` at Freezing, `drain_stash` at Complete.
- /// Accepting it here (rather than in the constructor) lets callers build
- /// the handler after the routing table, avoiding circular-dependency
- /// workarounds like `OnceCell`.
- pub async fn run(
+ async fn run_once(
&self,
cancel: CancellationToken,
handler: Arc<dyn StashHandler>,
+ progress: &Arc<AtomicBool>,
) -> Result<()> {
+ // How long the registered-but-not-yet-watching bootstrap may
+ // take. Registration makes this router count in freeze quorums,
+ // so a bootstrap that hangs past this must tear down rather than
+ // stall every handoff frozen in the meantime.
+ const BOOTSTRAP_DEADLINE: Duration = Duration::from_secs(30);
+
// Register this router so the coordinator can count it for ack quorum
+ let granted_at = Instant::now();
let lease_id = self.store.grant_lease(self.config.lease_ttl).await?;
self.register_router(lease_id).await?;
- let (snapshot_revision, pods_revision) = self.load_initial(&handler).await?;
-
- // The pod watch anchors strictly after the pod snapshot, exactly
- // like the handoff watch below: nothing older than the snapshot
- // is ever replayed, so a registration installed by the snapshot
- // can never be regressed by a replayed predecessor. (Anchoring
- // before the snapshot — the coordinator's pattern — is only safe
- // for CAS-guarded consumers; this map is last-writer-wins.)
- let pods_stream = self.store.watch_pods_from(pods_revision + 1).await?;
-
- // Anchor the handoff watch to the snapshot's revision: every event
- // at or before it was handled by `load_initial`, every later one
- // is replayed by the watch regardless of when it attaches. Without
- // the anchor, an event landing between the snapshot read and the
- // watch attaching is in neither and is never redelivered.
- let handoff_stream = self
- .store
- .watch_handoffs_from(snapshot_revision + 1)
- .await?;
+ // From here to the supervised select below, this router is
+ // registered — counted in every freeze quorum — but not yet
+ // acking. Every bootstrap failure must therefore deregister on
+ // the way out: returning with the lease intact would leave a
+ // never-acking quorum member, re-registered afresh by every
+ // supervisor retry. The same reasoning bounds the bootstrap and
+ // races it against shutdown; nothing here is supervised yet (the
+ // keepalive and watchdog tasks spawn only after it succeeds).
+ let bootstrap = async {
+ let (snapshot_revision, pods_revision) = self.load_initial(&handler).await?;
+
+ // The pod watch anchors strictly after the pod snapshot, exactly
+ // like the handoff watch below: nothing older than the snapshot
+ // is ever replayed, so a registration installed by the snapshot
+ // can never be regressed by a replayed predecessor. (Anchoring
+ // before the snapshot — the coordinator's pattern — is only safe
+ // for CAS-guarded consumers; this map is last-writer-wins.)
+ let pods_stream = self.store.watch_pods_from(pods_revision + 1).await?;
+
+ // Anchor the handoff watch to the snapshot's revision: every event
+ // at or before it was handled by `load_initial`, every later one
+ // is replayed by the watch regardless of when it attaches. Without
+ // the anchor, an event landing between the snapshot read and the
+ // watch attaching is in neither and is never redelivered.
+ let handoff_stream = self
+ .store
+ .watch_handoffs_from(snapshot_revision + 1)
+ .await?;
+ Ok::<_, Error>((pods_stream, handoff_stream))
+ };
+ let (pods_stream, handoff_stream) = tokio::select! {
+ _ = cancel.cancelled() => {
+ drop(self.store.revoke_lease(lease_id).await);
+ return Ok(());
+ }
+ r = tokio::time::timeout(BOOTSTRAP_DEADLINE, bootstrap) => match r {
+ Ok(Ok(streams)) => streams,
+ Ok(Err(e)) => {
+ drop(self.store.revoke_lease(lease_id).await);
+ return Err(e);
+ }
+ Err(_) => {
+ drop(self.store.revoke_lease(lease_id).await);
+ return Err(Error::invalid_state(format!(
+ "router bootstrap exceeded {BOOTSTRAP_DEADLINE:?} while registered"
+ )));
+ }
+ },
+ };
// Run heartbeat and handoff watch concurrently
let mut tasks = tokio::task::JoinSet::new();
@@ -365,9 +490,13 @@ impl RoutingTable {
{
let store = Arc::clone(&self.store);
let interval = self.config.heartbeat_interval;
+ let lease_ttl = self.config.lease_ttl;
let token = cancel.child_token();
tasks.spawn(async move {
- util::run_lease_keepalive(store, lease_id, interval, token).await
+ util::run_lease_keepalive(
+ store, lease_id, interval, lease_ttl, granted_at, "router", token,
+ )
+ .await
});
}
@@ -426,6 +555,7 @@ impl RoutingTable {
let reconcile_interval = self.config.reconcile_interval;
let reconcile_failure_budget = self.config.reconcile_failure_budget;
let token = cancel.child_token();
+ let progress = Arc::clone(progress);
tasks.spawn(async move {
Self::watch_handoffs_loop(
store,
@@ -441,6 +571,7 @@ impl RoutingTable {
stamp_interval,
reconcile_interval,
reconcile_failure_budget,
+ progress,
)
.await
});
@@ -625,6 +756,7 @@ impl RoutingTable {
stamp_interval: Duration,
reconcile_interval: Duration,
reconcile_failure_budget: u32,
+ progress: Arc<AtomicBool>,
) -> Result<()> {
let mut consecutive_reconcile_failures: u32 = 0;
// The stamp arm can only run while the loop is free to iterate —
@@ -643,6 +775,11 @@ impl RoutingTable {
tokio::time::Instant::now() + reconcile_interval,
reconcile_interval,
);
+ // Banked ticks after a slow event handler would fire back to
+ // back, each failing fast during an outage and burning the
+ // failure budget in milliseconds instead of one tick of real
+ // staleness per count.
+ reconcile_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
tokio::select! {
_ = cancel.cancelled() => return Ok(()),
@@ -672,7 +809,10 @@ impl RoutingTable {
)
.await
{
- Ok(()) => consecutive_reconcile_failures = 0,
+ Ok(()) => {
+ progress.store(true, Ordering::SeqCst);
+ consecutive_reconcile_failures = 0;
+ }
Err(e) => {
consecutive_reconcile_failures += 1;
metrics::counter!(
@@ -698,7 +838,7 @@ impl RoutingTable {
for event in resp.events() {
match event.event_type() {
EventType::Put => {
- Self::handle_handoff_put(
+ if Self::handle_handoff_put(
event,
store.as_ref(),
&table,
@@ -706,7 +846,10 @@ impl RoutingTable {
&handler,
&lanes,
&router_name,
- ).await?;
+ ).await?
+ {
+ progress.store(true, Ordering::SeqCst);
+ }
}
EventType::Delete => {
// A handoff record is never deleted while
@@ -721,7 +864,7 @@ impl RoutingTable {
// disposal from durable state and drains it
// to the assignment owner.
let Some(kv) = event.kv() else { continue };
- let key = std::str::from_utf8(kv.key()).unwrap_or("");
+ let key = from_utf8(kv.key()).unwrap_or("");
let Some(partition) = store::extract_partition_from_key(key) else {
continue
};
@@ -863,12 +1006,15 @@ impl RoutingTable {
handler: &Arc<dyn StashHandler>,
lanes: &Arc<DrainLanes>,
router_name: &str,
- ) -> Result<()> {
+ ) -> Result<bool> {
let handoff: HandoffState = match parse_watch_value(event) {
Ok(h) => h,
Err(e) => {
tracing::error!(error = %e, "failed to parse handoff event");
- return Ok(());
+ // Nothing was applied: an unparseable record must not
+ // count as run-budget progress, or a poison record would
+ // reset the budget on every delivery.
+ return Ok(false);
}
};
@@ -959,7 +1105,7 @@ impl RoutingTable {
);
}
}
- Ok(())
+ Ok(true)
}
}
diff --git a/rust/personhog-coordination/src/store.rs b/rust/personhog-coordination/src/store.rs
index 327f0c282aa8..3cdb8e535af0 100644
--- a/rust/personhog-coordination/src/store.rs
+++ b/rust/personhog-coordination/src/store.rs
@@ -1,3 +1,5 @@
+use std::str::from_utf8;
+
use assignment_coordination::store::EtcdStore;
use etcd_client::{Compare, CompareOp, DeleteOptions, PutOptions, Txn, TxnOp, WatchStream};
@@ -671,7 +673,7 @@ impl PersonhogStore {
.get_raw(&key)
.await?
.ok_or_else(|| Error::NotFound(key))?;
- let s = std::str::from_utf8(&bytes)
+ let s = from_utf8(&bytes)
.map_err(|e| Error::invalid_state(format!("non-utf8 total_partitions: {e}")))?;
s.parse::<u32>()
.map_err(|e| Error::invalid_state(format!("invalid total_partitions: {e}")))
diff --git a/rust/personhog-coordination/src/util.rs b/rust/personhog-coordination/src/util.rs
index 4ecd3bb5f903..331f370f54cf 100644
--- a/rust/personhog-coordination/src/util.rs
+++ b/rust/personhog-coordination/src/util.rs
@@ -1,6 +1,8 @@
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
-use std::time::{Duration, SystemTime, UNIX_EPOCH};
+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
+use metrics::counter;
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
@@ -21,28 +23,192 @@ pub fn new_handoff_id() -> String {
format!("{}-{}", millis, Uuid::new_v4())
}
+/// Record one supervisor-level failure (a bootstrap, an attempt, or a
+/// lost lease) against the consecutive budget. Returns `false` when the
+/// budget is exhausted. A failure that follows real progress — applied
+/// work only: the pod on a completed convergence, the router on a
+/// completed reconcile pass or an applied handoff event; never a mere
+/// successful read, which stays available in wedges where convergence
+/// itself is what fails — resets the count first: the budget bounds crash
+/// loops, not the lifetime of a component that keeps doing useful work
+/// between failures. Progress is measured rather than inferred from
+/// elapsed time, because any fixed "healthy after N seconds" threshold
+/// silently exempts every failure detector slower than N — the
+/// reconcile failure budget and the participant stall watchdog both
+/// take a minute to fire, so a time threshold in that range would let
+/// exactly the wedged-but-slowly-failing states the budget exists for
+/// rebuild in place forever.
+pub(crate) fn note_run_failure(
+ consecutive: &mut u32,
+ progress: &AtomicBool,
+ budget: u32,
+ component: &'static str,
+ name: &str,
+ err: &Error,
+) -> bool {
+ if progress.swap(false, Ordering::SeqCst) {
+ *consecutive = 1;
+ } else {
+ *consecutive += 1;
+ }
+ counter!(
+ "personhog_coordination_run_restarts_total",
+ "component" => component
+ )
+ .increment(1);
+ tracing::warn!(
+ component,
+ name,
+ error = %err,
+ consecutive = *consecutive,
+ budget,
+ "coordination run failed; rebuilding in place while the data plane keeps serving"
+ );
+ *consecutive < budget
+}
+
+/// Maintain a lease keepalive until cancelled, treating connection
+/// trouble and lease loss as the different things they are. A broken or
+/// silent keepalive stream is evidence about one connection — the lease
+/// itself lives in etcd's replicated keyspace and remains valid until
+/// its TTL passes without a renewal. Ambiguous failures (stream errors,
+/// unanswered rounds, failure to establish the stream) therefore
+/// rebuild the stream and retry — the endpoint is a service, so a fresh
+/// connection reaches a healthy member — for as long as the last
+/// confirmed renewal is recent enough that the lease cannot be near
+/// expiry.
+///
+/// Only two things end the keepalive with an error. etcd answering a
+/// round with TTL <= 0 is an authoritative statement that the lease is
+/// revoked or expired — immediate. And the renewal margin running out:
+/// after two thirds of the TTL without a confirmed renewal, the caller
+/// 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
+/// bounded by the time left so a hang can never defer the verdict past
+/// the moment the fence must begin.
pub async fn run_lease_keepalive(
store: Arc<PersonhogStore>,
lease_id: i64,
interval: Duration,
+ lease_ttl: i64,
+ granted_at: Instant,
+ component: &'static str,
cancel: CancellationToken,
) -> Result<()> {
- let (mut keeper, mut stream) = store.keep_alive(lease_id).await?;
+ let renewal_margin = Duration::from_secs(lease_ttl.max(0) as u64).mul_f64(2.0 / 3.0);
+ // `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)
+ .max(Duration::from_millis(250))
+ .min(interval.max(Duration::from_millis(250)));
+ // Anchored at the grant, where the server's countdown started — not
+ // at task spawn, which would overstate the first window's runway by
+ // however long registration took.
+ let mut last_renewed = granted_at;
+
+ let margin_exhausted = || {
+ Error::invalid_state(format!(
+ "lease renewal margin exhausted: no confirmed renewal in {renewal_margin:?}"
+ ))
+ };
+
+ 'stream: loop {
+ // (Re)establish the keepalive stream, bounded by the margin.
+ let (mut keeper, mut stream) = loop {
+ let left = renewal_margin.saturating_sub(last_renewed.elapsed());
+ if left.is_zero() {
+ return Err(margin_exhausted());
+ }
+ let attempt = tokio::time::timeout(left.min(interval), store.keep_alive(lease_id));
+ let failure = tokio::select! {
+ _ = cancel.cancelled() => return Ok(()),
+ r = attempt => match r {
+ Ok(Ok(pair)) => break pair,
+ Ok(Err(e)) => e,
+ Err(_) => Error::invalid_state(
+ "keepalive stream establishment timed out".to_string(),
+ ),
+ },
+ };
+ counter!(
+ "personhog_coordination_keepalive_retries_total",
+ "component" => component
+ )
+ .increment(1);
+ tracing::warn!(
+ lease_id,
+ component,
+ error = %failure,
+ since_renewal = ?last_renewed.elapsed(),
+ margin = ?renewal_margin,
+ "keepalive stream failed; retrying within the lease margin"
+ );
+ let pace = retry_pace.min(renewal_margin.saturating_sub(last_renewed.elapsed()));
+ tokio::select! {
+ _ = cancel.cancelled() => return Ok(()),
+ _ = tokio::time::sleep(pace) => {}
+ }
+ };
- loop {
- tokio::select! {
- _ = cancel.cancelled() => return Ok(()),
- _ = tokio::time::sleep(interval) => {
+ // Renew immediately on a fresh stream: if it was rebuilt after
+ // failures, the margin is already burning.
+ loop {
+ let left = renewal_margin.saturating_sub(last_renewed.elapsed());
+ if left.is_zero() {
+ return Err(margin_exhausted());
+ }
+ let round = async {
keeper.keep_alive().await?;
match stream.message().await? {
- None => return Err(Error::leadership_lost()),
- // etcd answers keepalives for a revoked or expired
- // lease with a normal response carrying TTL 0 — the
- // stream stays open, so stream-end alone never
- // detects lease loss.
- Some(resp) if resp.ttl() <= 0 => return Err(Error::leadership_lost()),
- Some(_) => {}
+ // Stream end is a connection fact, not a lease fact:
+ // etcd reports a revoked or expired lease as a normal
+ // response with TTL 0, so closure alone is ambiguous.
+ None => Err(Error::invalid_state("keepalive stream ended".to_string())),
+ Some(resp) if resp.ttl() <= 0 => Ok(false),
+ Some(_) => Ok(true),
}
+ };
+ let outcome = match tokio::time::timeout(left.min(interval), round).await {
+ Ok(r) => r,
+ Err(_) => Err(Error::invalid_state(format!(
+ "keepalive round unanswered within {:?}",
+ left.min(interval)
+ ))),
+ };
+ match outcome {
+ Ok(true) => last_renewed = Instant::now(),
+ // Authoritative: the lease is gone, no margin applies.
+ Ok(false) => return Err(Error::leadership_lost()),
+ Err(e) => {
+ counter!(
+ "personhog_coordination_keepalive_retries_total",
+ "component" => component
+ )
+ .increment(1);
+ tracing::warn!(
+ lease_id,
+ component,
+ error = %e,
+ since_renewal = ?last_renewed.elapsed(),
+ margin = ?renewal_margin,
+ "keepalive round failed; retrying within the lease margin"
+ );
+ let pace =
+ retry_pace.min(renewal_margin.saturating_sub(last_renewed.elapsed()));
+ tokio::select! {
+ _ = cancel.cancelled() => return Ok(()),
+ _ = tokio::time::sleep(pace) => {}
+ }
+ continue 'stream;
+ }
+ }
+ tokio::select! {
+ _ = cancel.cancelled() => return Ok(()),
+ _ = tokio::time::sleep(interval) => {}
}
}
}
diff --git a/rust/personhog-coordination/tests/common/mod.rs b/rust/personhog-coordination/tests/common/mod.rs
index 7b743693dfad..b0ca01fbf1ab 100644
--- a/rust/personhog-coordination/tests/common/mod.rs
+++ b/rust/personhog-coordination/tests/common/mod.rs
@@ -2,11 +2,13 @@
use std::collections::{HashMap, HashSet};
use std::future::{pending, Future};
-use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex as StdMutex, RwLock as StdRwLock};
use std::time::{Duration, Instant};
use async_trait::async_trait;
+use tokio::io::copy_bidirectional;
+use tokio::net::{TcpListener, TcpStream};
use tokio::sync::{Mutex, Notify, RwLock};
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
@@ -310,6 +312,88 @@ pub fn start_router_with_lease_ttl(
}
}
+/// Connect a store to an arbitrary endpoint (e.g. a `FlakyProxy`) under
+/// an explicit prefix, so a component under test can run through a
+/// fault-injected connection while the test asserts against a direct one.
+pub async fn store_at(endpoint: &str, prefix: &str) -> Arc<PersonhogStore> {
+ let config = StoreConfig {
+ endpoints: vec![endpoint.to_string()],
+ prefix: prefix.to_string(),
+ };
+ let inner = EtcdStore::connect(config)
+ .await
+ .expect("failed to connect store");
+ Arc::new(PersonhogStore::new(inner))
+}
+
+/// A byte-forwarding TCP proxy for fault-injecting a component's etcd
+/// connection: `sever` breaks every live connection (in-flight streams
+/// error; reconnects still succeed), and `set_blackholed(true)` also
+/// kills new connections on accept, so recovery is impossible until it
+/// is lifted.
+pub struct FlakyProxy {
+ /// Endpoint URL to hand to `store_at`.
+ pub endpoint: String,
+ conns: Arc<StdMutex<Vec<tokio::task::JoinHandle<()>>>>,
+ blackholed: Arc<AtomicBool>,
+ listener: tokio::task::JoinHandle<()>,
+}
+
+impl FlakyProxy {
+ pub async fn start(upstream: &'static str) -> Self {
+ let socket = TcpListener::bind("127.0.0.1:0").await.expect("bind proxy");
+ let endpoint = format!("http://{}", socket.local_addr().expect("proxy addr"));
+ let conns: Arc<StdMutex<Vec<tokio::task::JoinHandle<()>>>> =
+ Arc::new(StdMutex::new(Vec::new()));
+ let blackholed = Arc::new(AtomicBool::new(false));
+ let conns_bg = Arc::clone(&conns);
+ let blackholed_bg = Arc::clone(&blackholed);
+ let listener = tokio::spawn(async move {
+ loop {
+ let Ok((mut client, _)) = socket.accept().await else {
+ return;
+ };
+ if blackholed_bg.load(Ordering::SeqCst) {
+ drop(client);
+ continue;
+ }
+ let pump = tokio::spawn(async move {
+ let Ok(mut upstream_conn) = TcpStream::connect(upstream).await else {
+ return;
+ };
+ drop(copy_bidirectional(&mut client, &mut upstream_conn).await);
+ });
+ conns_bg.lock().unwrap().push(pump);
+ }
+ });
+ Self {
+ endpoint,
+ conns,
+ blackholed,
+ listener,
+ }
+ }
+
+ /// Break every live connection; the streams running over them error
+ /// out. New connections still succeed unless blackholed.
+ pub fn sever(&self) {
+ for pump in self.conns.lock().unwrap().drain(..) {
+ pump.abort();
+ }
+ }
+
+ pub fn set_blackholed(&self, blackholed: bool) {
+ self.blackholed.store(blackholed, Ordering::SeqCst);
+ }
+}
+
+impl Drop for FlakyProxy {
+ fn drop(&mut self) {
+ self.listener.abort();
+ self.sever();
+ }
+}
+
// ── Mock handlers ───────────────────────────────────────────────
#[derive(Debug, Clone, PartialEq, Eq)]
diff --git a/rust/personhog-coordination/tests/integration.rs b/rust/personhog-coordination/tests/integration.rs
index 817dd07eda77..1cf2db89a602 100644
--- a/rust/personhog-coordination/tests/integration.rs
+++ b/rust/personhog-coordination/tests/integration.rs
@@ -264,7 +264,7 @@ async fn pod_crash_reassigns_partitions(
// Use a short lease for pod0 so crash is detected quickly
let pod0_cancel = CancellationToken::new();
- let _pod0 = start_pod_with_lease_ttl(Arc::clone(&store), "writer-0", 2, pod0_cancel.clone());
+ let _pod0 = start_pod_with_lease_ttl(Arc::clone(&store), "writer-0", 5, pod0_cancel.clone());
let _pod1 = start_pod(Arc::clone(&store), "writer-1", cancel.clone());
// Wait for balanced assignment across both pods
@@ -647,9 +647,9 @@ async fn scale_down_to_one_pod(
// Start 3 pods with short leases so crash detection is fast
let pod0_cancel = CancellationToken::new();
- let _pod0 = start_pod_with_lease_ttl(Arc::clone(&store), "writer-0", 2, pod0_cancel.clone());
+ let _pod0 = start_pod_with_lease_ttl(Arc::clone(&store), "writer-0", 5, pod0_cancel.clone());
let pod1_cancel = CancellationToken::new();
- let _pod1 = start_pod_with_lease_ttl(Arc::clone(&store), "writer-1", 2, pod1_cancel.clone());
+ let _pod1 = start_pod_with_lease_ttl(Arc::clone(&store), "writer-1", 5, pod1_cancel.clone());
let _pod2 = start_pod(Arc::clone(&store), "writer-2", cancel.clone());
// Wait for balanced assignment across all 3 pods
@@ -824,7 +824,7 @@ async fn rolling_update(
_old_pods.push(start_pod_with_lease_ttl(
Arc::clone(&store),
&format!("old-{i}"),
- 2,
+ 5,
old_cancel.clone(),
));
}
diff --git a/rust/personhog-coordination/tests/k3s_integration.rs b/rust/personhog-coordination/tests/k3s_integration.rs
index ab1590e32dca..3f9118f16318 100644
--- a/rust/personhog-coordination/tests/k3s_integration.rs
+++ b/rust/personhog-coordination/tests/k3s_integration.rs
@@ -681,6 +681,8 @@ async fn statefulset_rollout_pod_skips_drain() {
drain_timeout: Duration::from_secs(30),
reconcile_interval: Duration::from_secs(86_400),
reconcile_failure_budget: 12,
+ run_retry_budget: 10,
+ run_retry_backoff: Duration::from_millis(500),
advertise_address: None,
warm_concurrency: 4,
};
diff --git a/rust/personhog-coordination/tests/protocol_hardening.rs b/rust/personhog-coordination/tests/protocol_hardening.rs
index 83756cbe1da7..90287e43c346 100644
--- a/rust/personhog-coordination/tests/protocol_hardening.rs
+++ b/rust/personhog-coordination/tests/protocol_hardening.rs
@@ -11,7 +11,7 @@ mod common;
use std::collections::HashMap;
use std::future::pending;
-use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;
@@ -22,9 +22,9 @@ use assignment_coordination::store::parse_watch_value;
use async_trait::async_trait;
use common::{
revoke_lease_of_key, start_coordinator, start_coordinator_named, start_pod, start_pod_gated,
- start_pod_with_lease_ttl, start_router_with_lease_ttl, test_store, test_store_with_prefix,
- wait_for_condition, CutoverEvent, HandoffEvent, MockCutoverHandler, POLL_INTERVAL,
- WAIT_TIMEOUT,
+ start_pod_with_lease_ttl, start_router_with_lease_ttl, store_at, test_store,
+ test_store_with_prefix, wait_for_condition, CutoverEvent, FlakyProxy, HandoffEvent,
+ MockCutoverHandler, MockHandoffHandler, ETCD_ENDPOINT, POLL_INTERVAL, WAIT_TIMEOUT,
};
use personhog_coordination::error::Result;
use personhog_coordination::routing_table::{RoutingTable, RoutingTableConfig, StashHandler};
@@ -89,15 +89,16 @@ async fn wait_for_event(events: &Arc<Mutex<Vec<HandoffEvent>>>, expected: Handof
/// etcd partition or missed heartbeats) must exit its run loop rather
/// than continue serving as a zombie owner.
#[tokio::test]
-async fn pod_self_fences_when_lease_revoked() {
+async fn pod_self_fences_locally_and_rejoins_after_lease_loss() {
let (store, prefix) = test_store_with_prefix("pod-self-fence").await;
let cancel = CancellationToken::new();
// lease_ttl 5 → 1s heartbeat interval, so the keepalive observes the
// revocation within ~a second.
- let mut pod = start_pod_with_lease_ttl(Arc::clone(&store), "fence-pod-0", 5, cancel.clone());
+ let pod = start_pod_with_lease_ttl(Arc::clone(&store), "fence-pod-0", 5, cancel.clone());
- // Wait until the pod has registered (its lease-bound key exists).
+ // Wait until the pod has registered, then hand it a partition so
+ // the self-fence has something real to release.
let check_store = Arc::clone(&store);
wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
let store = Arc::clone(&check_store);
@@ -110,20 +111,75 @@ async fn pod_self_fences_when_lease_revoked() {
}
})
.await;
+ put_handoff(&store, 0, None, "fence-pod-0", HandoffPhase::Warming).await;
+ let warmed_count = |events: Arc<Mutex<Vec<HandoffEvent>>>| async move {
+ events
+ .lock()
+ .await
+ .iter()
+ .filter(|e| matches!(e, HandoffEvent::Warmed(0)))
+ .count()
+ };
+ let events = Arc::clone(&pod.events);
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let events = Arc::clone(&events);
+ async move { warmed_count(events).await >= 1 }
+ })
+ .await;
revoke_lease_of_key(&format!("{prefix}pods/fence-pod-0")).await;
- // The run loop must observe the dead lease and exit with an error —
- // NOT keep serving. Generous timeout: one heartbeat tick plus slack.
- let join = pod.join_handle.take().expect("join handle");
- let result = tokio::time::timeout(Duration::from_secs(10), join)
- .await
- .expect("pod must self-fence after lease revocation instead of serving as a zombie")
- .expect("pod task must not panic");
- assert!(
- result.is_err(),
- "run() must surface the lease loss as an error so the process restarts"
- );
+ // Lease loss must self-fence: the held partition is released
+ // locally before any rejoin, because the coordinator already treats
+ // the expired lease as death and may be reassigning. The fence must
+ // drain before it releases — release alone unfences and drops the
+ // cache without waiting, letting an already-admitted write ack
+ // after the replacement owner's warm — so `Drained` must precede
+ // `Released` in the fence sequence.
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let events = Arc::clone(&events);
+ async move {
+ events
+ .lock()
+ .await
+ .iter()
+ .any(|e| matches!(e, HandoffEvent::Released(0)))
+ }
+ })
+ .await;
+ {
+ let events = events.lock().await;
+ let drained = events
+ .iter()
+ .position(|e| matches!(e, HandoffEvent::Drained(0)));
+ let released = events
+ .iter()
+ .position(|e| matches!(e, HandoffEvent::Released(0)));
+ assert!(
+ matches!((drained, released), (Some(d), Some(r)) if d < r),
+ "the self-fence must drain (fence + quiesce) before releasing: {events:?}"
+ );
+ }
+
+ // The supervisor then rejoins as a fresh participant instead of
+ // dying: the pod re-registers, and startup convergence re-warms the
+ // still-Warming partition it just released.
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let store = Arc::clone(&check_store);
+ async move {
+ store
+ .list_pods()
+ .await
+ .map(|pods| pods.iter().any(|p| p.pod_name == "fence-pod-0"))
+ .unwrap_or(false)
+ }
+ })
+ .await;
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let events = Arc::clone(&events);
+ async move { warmed_count(events).await >= 2 }
+ })
+ .await;
cancel.cancel();
}
@@ -132,37 +188,44 @@ async fn pod_self_fences_when_lease_revoked() {
/// has already dropped it from the freeze quorum, so if it keeps serving
/// it can forward writes to a draining old owner without stashing.
#[tokio::test]
-async fn router_exits_when_lease_revoked() {
+async fn router_rejoins_with_a_fresh_lease_after_revocation() {
let (store, prefix) = test_store_with_prefix("router-self-fence").await;
let cancel = CancellationToken::new();
- let mut router =
+ let _router =
start_router_with_lease_ttl(Arc::clone(&store), "fence-router-0", 5, cancel.clone());
+ let registered = |store: Arc<PersonhogStore>| async move {
+ store
+ .list_routers()
+ .await
+ .map(|routers| routers.iter().any(|r| r.router_name == "fence-router-0"))
+ .unwrap_or(false)
+ };
let check_store = Arc::clone(&store);
wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
- let store = Arc::clone(&check_store);
- async move {
- store
- .list_routers()
- .await
- .map(|routers| routers.iter().any(|r| r.router_name == "fence-router-0"))
- .unwrap_or(false)
- }
+ registered(Arc::clone(&check_store))
})
.await;
revoke_lease_of_key(&format!("{prefix}routers/fence-router-0")).await;
- let join = router.join_handle.take().expect("join handle");
- let result = tokio::time::timeout(Duration::from_secs(10), join)
- .await
- .expect("router must exit after lease revocation instead of serving with a stale table")
- .expect("router task must not panic");
- assert!(
- result.is_err(),
- "run() must surface the lease loss as an error so the process restarts"
- );
+ // The failed attempt tears down (the revoked lease already removed
+ // the registration, so freeze quorums stop counting the router) and
+ // the supervisor rejoins with a fresh lease instead of dying.
+ // Serving through the gap is safe: any handoff created while the
+ // router is unregistered excludes it from the freeze quorum, so the
+ // old owner fences before a new owner warms and stale forwards
+ // bounce rather than land.
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let store = Arc::clone(&check_store);
+ async move { !registered(store).await }
+ })
+ .await;
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ registered(Arc::clone(&check_store))
+ })
+ .await;
cancel.cancel();
}
@@ -1667,6 +1730,10 @@ async fn a_stalled_watch_loop_trips_the_watchdog_and_deregisters() {
router_name: "wd-router".to_string(),
participant_stall_threshold: Some(Duration::from_secs(1)),
reconcile_interval: Duration::from_secs(86_400),
+ // Budget 1 pins the watchdog's fatal path: one tripped
+ // attempt fails the whole run. The rebuild-in-place path is
+ // covered by the supervisor tests.
+ run_retry_budget: 1,
..RoutingTableConfig::default()
},
);
@@ -1863,6 +1930,170 @@ async fn the_reconcile_pass_reasserts_freeze_acks() {
cancel.cancel();
}
+/// A handoff handler whose `warm_partition` fails while the flag is
+/// set — the injection point for pod attempt failures that do not
+/// involve the lease.
+struct FlakyHandoffHandler {
+ events: Arc<Mutex<Vec<HandoffEvent>>>,
+ fail_warm: Arc<AtomicBool>,
+ warm_failures: Arc<AtomicUsize>,
+}
+
+#[async_trait]
+impl personhog_coordination::pod::HandoffHandler for FlakyHandoffHandler {
+ async fn drain_partition_inflight(&self, partition: u32) -> Result<()> {
+ self.events
+ .lock()
+ .await
+ .push(HandoffEvent::Drained(partition));
+ Ok(())
+ }
+
+ async fn warm_partition(&self, partition: u32) -> Result<()> {
+ if self.fail_warm.load(Ordering::SeqCst) {
+ self.warm_failures.fetch_add(1, Ordering::SeqCst);
+ return Err(personhog_coordination::error::Error::invalid_state(
+ "injected warm failure".to_string(),
+ ));
+ }
+ self.events
+ .lock()
+ .await
+ .push(HandoffEvent::Warmed(partition));
+ Ok(())
+ }
+
+ async fn release_partition(&self, partition: u32) -> Result<()> {
+ self.events
+ .lock()
+ .await
+ .push(HandoffEvent::Released(partition));
+ Ok(())
+ }
+
+ async fn resume_partition(&self, partition: u32) -> Result<()> {
+ self.events
+ .lock()
+ .await
+ .push(HandoffEvent::Resumed(partition));
+ Ok(())
+ }
+}
+
+/// A pod attempt failure that does not involve the lease must retry with
+/// the registration preserved and the held partitions untouched: the
+/// coordinator keeps seeing a live pod (no dead-owner reassignment can
+/// start against a process that is still serving), no partition is
+/// released, and — the cache-preservation proof — nothing is re-warmed
+/// on recovery. This pins the deregistered-but-serving hole closed: an
+/// earlier design revoked the lease on every failed attempt, handing
+/// the coordinator a dead owner while the process kept accepting
+/// writes.
+#[tokio::test]
+async fn a_pod_attempt_failure_preserves_registration_and_partitions() {
+ let store = test_store("pod-attempt-preserves").await;
+ let cancel = CancellationToken::new();
+
+ let events: Arc<Mutex<Vec<HandoffEvent>>> = Arc::new(Mutex::new(Vec::new()));
+ let fail_warm = Arc::new(AtomicBool::new(false));
+ let handler = FlakyHandoffHandler {
+ events: Arc::clone(&events),
+ fail_warm: Arc::clone(&fail_warm),
+ warm_failures: Arc::new(AtomicUsize::new(0)),
+ };
+ let pod = personhog_coordination::pod::PodHandle::new(
+ Arc::clone(&store),
+ personhog_coordination::pod::PodConfig {
+ pod_name: "flaky-pod-0".to_string(),
+ lease_ttl: 10,
+ heartbeat_interval: Duration::from_secs(3),
+ reconcile_interval: Duration::from_secs(86_400),
+ run_retry_backoff: Duration::from_millis(100),
+ ..Default::default()
+ },
+ Arc::new(handler),
+ None,
+ );
+ let token = cancel.child_token();
+ tokio::spawn(async move { pod.run(token).await });
+
+ let registered = |store: Arc<PersonhogStore>| async move {
+ store
+ .list_pods()
+ .await
+ .map(|pods| pods.iter().any(|p| p.pod_name == "flaky-pod-0"))
+ .unwrap_or(false)
+ };
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ registered(Arc::clone(&store))
+ })
+ .await;
+
+ // The pod acquires partition 0 healthily.
+ put_handoff(&store, 0, None, "flaky-pod-0", HandoffPhase::Warming).await;
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let events = Arc::clone(&events);
+ async move {
+ events
+ .lock()
+ .await
+ .iter()
+ .any(|e| matches!(e, HandoffEvent::Warmed(0)))
+ }
+ })
+ .await;
+
+ // Break warming, then hand the pod a second partition: the event
+ // kills the attempt, and re-attempts keep failing at convergence
+ // while the flag holds.
+ fail_warm.store(true, std::sync::atomic::Ordering::SeqCst);
+ put_handoff(&store, 1, None, "flaky-pod-0", HandoffPhase::Warming).await;
+
+ // Let several failed attempts elapse (100ms backoff base), then
+ // assert the invariants of the failure window: still registered
+ // (the session was never given up), partition 0 never released.
+ tokio::time::sleep(Duration::from_millis(800)).await;
+ assert!(
+ registered(Arc::clone(&store)).await,
+ "attempt failures must not cost the pod its registration"
+ );
+ assert!(
+ !events
+ .lock()
+ .await
+ .iter()
+ .any(|e| matches!(e, HandoffEvent::Released(_))),
+ "attempt failures must not release held partitions"
+ );
+
+ // Recovery: partition 1 warms; partition 0 was never re-warmed —
+ // its cache and warm state survived every failed attempt.
+ fail_warm.store(false, std::sync::atomic::Ordering::SeqCst);
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let events = Arc::clone(&events);
+ async move {
+ events
+ .lock()
+ .await
+ .iter()
+ .any(|e| matches!(e, HandoffEvent::Warmed(1)))
+ }
+ })
+ .await;
+ let warmed_zero = events
+ .lock()
+ .await
+ .iter()
+ .filter(|e| matches!(e, HandoffEvent::Warmed(0)))
+ .count();
+ assert_eq!(
+ warmed_zero, 1,
+ "the held partition must never re-warm across failed attempts"
+ );
+
+ cancel.cancel();
+}
+
/// A cutover handler whose `begin_stash` fails while the flag is set —
/// the injection point for reconcile-pass failures, since the pass calls
/// it for every non-terminal handoff before writing the freeze ack.
@@ -1929,6 +2160,7 @@ async fn start_flaky_router(
router_name: router_name.to_string(),
reconcile_interval: Duration::from_millis(200),
reconcile_failure_budget: budget,
+ run_retry_backoff: Duration::from_millis(100),
..RoutingTableConfig::default()
},
);
@@ -2049,6 +2281,58 @@ async fn reconcile_failures_past_the_budget_fail_the_run() {
cancel.cancel();
}
+/// A failed coordination attempt must rebuild in place, not kill the
+/// run: while the handler (standing in for etcd trouble) fails, attempts
+/// tear down and back off; once it recovers, the next attempt
+/// re-registers and catches up on everything missed in the gap — here, a
+/// handoff created while coordination was down gets its freeze ack.
+#[tokio::test]
+async fn a_failed_coordination_attempt_rebuilds_in_place() {
+ let store = test_store("run-rebuilds-in-place").await;
+ let (fail, cancel) = start_flaky_router(&store, "rip-router", 12).await;
+
+ let ack_present = |store: Arc<PersonhogStore>, partition: u32| async move {
+ store
+ .list_freeze_acks(partition)
+ .await
+ .expect("list acks")
+ .iter()
+ .any(|a| a.router_name == "rip-router")
+ };
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ ack_present(Arc::clone(&store), 0)
+ })
+ .await;
+
+ // Break the handler, then deliver an event: the event arm fails the
+ // attempt, and re-bootstraps keep failing while the handler is down.
+ // The teardown of the failed attempt deregisters the router.
+ fail.store(true, std::sync::atomic::Ordering::SeqCst);
+ put_handoff(&store, 1, None, "keeper-pod", HandoffPhase::Freezing).await;
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let store = Arc::clone(&store);
+ async move {
+ !store
+ .list_routers()
+ .await
+ .expect("list routers")
+ .iter()
+ .any(|r| r.router_name == "rip-router")
+ }
+ })
+ .await;
+
+ // Recovery: the next attempt bootstraps, re-registers, and the
+ // fresh load acks the handoff that arrived during the outage.
+ fail.store(false, std::sync::atomic::Ordering::SeqCst);
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ ack_present(Arc::clone(&store), 1)
+ })
+ .await;
+
+ cancel.cancel();
+}
+
/// A cutover handler whose stash has fully settled: `stash_pending`
/// reports no entry, the way the router does once a drain has evicted
/// the partition from its stash table.
@@ -2354,3 +2638,394 @@ async fn concurrent_warms_are_bounded_by_warm_concurrency() {
cancel.cancel();
}
+
+// ============================================================
+// Lease loss is observed promptly at every live-lease await
+// ============================================================
+//
+// The session's keepalive task fails fast when the lease dies, but a
+// signal only fences if the supervisor is listening. Every await the
+// session makes while holding a lease must race the heartbeat handle:
+// an unraced await defers the self-fence for its full duration, and the
+// coordinator — which starts reassigning at TTL expiry — does not wait.
+// These pin the two awaits that were unraced: the backoff nap between
+// failed attempts, and the graceful drain.
+
+/// A lease revoked while the supervisor naps between failed attempts
+/// must self-fence when the keepalive notices — not when the nap ends.
+/// The nap here is far longer than the assertion window, so this fails
+/// if detection waits out the backoff.
+#[tokio::test]
+async fn lease_loss_during_attempt_backoff_self_fences_promptly() {
+ let (store, prefix) = test_store_with_prefix("pod-backoff-fence").await;
+ let cancel = CancellationToken::new();
+
+ let events: Arc<Mutex<Vec<HandoffEvent>>> = Arc::new(Mutex::new(Vec::new()));
+ let fail_warm = Arc::new(AtomicBool::new(false));
+ let handler = FlakyHandoffHandler {
+ events: Arc::clone(&events),
+ fail_warm: Arc::clone(&fail_warm),
+ warm_failures: Arc::new(AtomicUsize::new(0)),
+ };
+ let pod = personhog_coordination::pod::PodHandle::new(
+ Arc::clone(&store),
+ personhog_coordination::pod::PodConfig {
+ pod_name: "backoff-fence-pod".to_string(),
+ lease_ttl: 5,
+ heartbeat_interval: Duration::from_secs(1),
+ reconcile_interval: Duration::from_secs(86_400),
+ // One failed attempt naps 8s — far past the 4s assertion
+ // window below.
+ run_retry_backoff: Duration::from_secs(8),
+ ..Default::default()
+ },
+ Arc::new(handler),
+ None,
+ );
+ let token = cancel.child_token();
+ tokio::spawn(async move { pod.run(token).await });
+
+ // Acquire partition 0 healthily so the self-fence has something to
+ // release.
+ put_handoff(&store, 0, None, "backoff-fence-pod", HandoffPhase::Warming).await;
+ wait_for_event(&events, HandoffEvent::Warmed(0)).await;
+
+ // A failing warm for partition 1 kills the attempt; the supervisor
+ // enters its nap. The sleep positions the revocation inside the 8s
+ // nap — if it ever lands before the nap instead, the attempt-select
+ // race detects it and the test still passes, just via the path that
+ // was already covered.
+ fail_warm.store(true, Ordering::SeqCst);
+ put_handoff(&store, 1, None, "backoff-fence-pod", HandoffPhase::Warming).await;
+ tokio::time::sleep(Duration::from_millis(500)).await;
+
+ revoke_lease_of_key(&format!("{prefix}pods/backoff-fence-pod")).await;
+
+ // Well inside the nap: the self-fence must already have run.
+ wait_for_condition(Duration::from_secs(4), POLL_INTERVAL, || {
+ let events = Arc::clone(&events);
+ async move { events.lock().await.contains(&HandoffEvent::Released(0)) }
+ })
+ .await;
+
+ cancel.cancel();
+}
+
+/// A lease revoked during the graceful drain must switch to the local
+/// self-fence immediately: the pod serves its partitions until their
+/// handoffs complete, and with the lease gone the coordinator is
+/// already reassigning them via the dead-owner path. Draining leaseless
+/// until the drain timeout is the same zombie window the attempt-path
+/// fence closes.
+#[tokio::test]
+async fn lease_loss_during_graceful_drain_self_fences_promptly() {
+ let (store, prefix) = test_store_with_prefix("pod-drain-fence").await;
+ let cancel = CancellationToken::new();
+
+ let (handler, events) = MockHandoffHandler::new();
+ let pod = personhog_coordination::pod::PodHandle::new(
+ Arc::clone(&store),
+ personhog_coordination::pod::PodConfig {
+ pod_name: "drain-fence-pod".to_string(),
+ lease_ttl: 5,
+ heartbeat_interval: Duration::from_secs(1),
+ reconcile_interval: Duration::from_secs(86_400),
+ // No coordinator completes the handoffs, so an undetected
+ // lease loss would leave the drain waiting out this full
+ // timeout.
+ drain_timeout: Duration::from_secs(30),
+ ..Default::default()
+ },
+ Arc::new(handler),
+ None,
+ );
+ let token = cancel.child_token();
+ let join = tokio::spawn(async move { pod.run(token).await });
+
+ put_handoff(&store, 0, None, "drain-fence-pod", HandoffPhase::Warming).await;
+ wait_for_event(&events, HandoffEvent::Warmed(0)).await;
+
+ // Graceful shutdown: the pod flips to Draining and waits for its
+ // partition's outbound handoff, which never comes.
+ cancel.cancel();
+ let check_store = Arc::clone(&store);
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, move || {
+ let store = Arc::clone(&check_store);
+ async move {
+ store
+ .list_pods()
+ .await
+ .map(|pods| {
+ pods.iter()
+ .any(|p| p.pod_name == "drain-fence-pod" && p.status == PodStatus::Draining)
+ })
+ .unwrap_or(false)
+ }
+ })
+ .await;
+
+ revoke_lease_of_key(&format!("{prefix}pods/drain-fence-pod")).await;
+
+ // Well inside the 30s drain timeout: the self-fence must have
+ // released the partition and the run must have exited.
+ wait_for_condition(Duration::from_secs(4), POLL_INTERVAL, || {
+ let events = Arc::clone(&events);
+ async move { events.lock().await.contains(&HandoffEvent::Released(0)) }
+ })
+ .await;
+ tokio::time::timeout(Duration::from_secs(5), join)
+ .await
+ .expect("run exits promptly after the drain-time self-fence")
+ .expect("run task")
+ .expect("run returns Ok on graceful shutdown");
+}
+
+// ============================================================
+// Keepalive: connection blips are not lease loss
+// ============================================================
+//
+// The lease lives in etcd's replicated keyspace and stays valid until
+// its TTL passes without renewal — a broken keepalive stream is a fact
+// about one connection, not about the lease. The keepalive therefore
+// rebuilds and retries through connection trouble while the last
+// confirmed renewal is recent, and only declares loss on etcd's
+// authoritative TTL<=0 answer or when the renewal margin (two thirds of
+// the TTL, reserving the final third for the fence) runs out. These run
+// a pod through a fault-injecting TCP proxy: a severed connection with
+// runway left must not fence; a blackholed one must fence at the
+// margin, not immediately and not never.
+
+/// A routine single-member blip: the pod's etcd connection breaks and
+/// immediately becomes reconnectable. The pod must keep its lease, its
+/// registration, and its partitions — no self-fence, no re-warm.
+#[tokio::test]
+async fn a_connection_blip_does_not_fence_the_pod() {
+ let proxy = FlakyProxy::start("127.0.0.1:2379").await;
+ let prefix = format!("/test-keepalive-blip-{}/", uuid::Uuid::new_v4());
+ let pod_store = store_at(&proxy.endpoint, &prefix).await;
+ let direct_store = store_at(ETCD_ENDPOINT, &prefix).await;
+
+ let cancel = CancellationToken::new();
+ let (handler, events) = MockHandoffHandler::new();
+ let pod = personhog_coordination::pod::PodHandle::new(
+ Arc::clone(&pod_store),
+ personhog_coordination::pod::PodConfig {
+ pod_name: "blip-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,
+ );
+ let token = cancel.child_token();
+ tokio::spawn(async move { pod.run(token).await });
+
+ put_handoff(&direct_store, 0, None, "blip-pod", HandoffPhase::Warming).await;
+ wait_for_event(&events, HandoffEvent::Warmed(0)).await;
+
+ proxy.sever();
+
+ // Old behavior fences within a heartbeat tick of the blip. With the
+ // renewal margin, the keepalive rebuilds its stream instead.
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ assert!(
+ !events.lock().await.contains(&HandoffEvent::Released(0)),
+ "a reconnectable blip must not self-fence"
+ );
+
+ // Well past the original TTL from the last pre-blip renewal: the
+ // registration only survives if renewals resumed through the
+ // rebuilt stream.
+ tokio::time::sleep(Duration::from_secs(8)).await;
+ assert!(
+ !events.lock().await.contains(&HandoffEvent::Released(0)),
+ "the pod must hold its partition through the blip"
+ );
+ let pods = direct_store.list_pods().await.expect("list pods");
+ assert!(
+ pods.iter().any(|p| p.pod_name == "blip-pod"),
+ "the lease must have been renewed through the rebuilt stream"
+ );
+
+ cancel.cancel();
+}
+
+/// A sustained etcd outage: the connection breaks and stays broken. The
+/// pod must keep retrying while the lease still has runway — fencing
+/// early buys no safety, the coordinator cannot have reassigned anything
+/// — and must fence when the renewal margin runs out, leaving the final
+/// third of the TTL for the fence to complete before expiry.
+#[tokio::test]
+async fn a_sustained_outage_fences_at_the_renewal_margin() {
+ let proxy = FlakyProxy::start("127.0.0.1:2379").await;
+ let prefix = format!("/test-keepalive-margin-{}/", uuid::Uuid::new_v4());
+ let pod_store = store_at(&proxy.endpoint, &prefix).await;
+ let direct_store = store_at(ETCD_ENDPOINT, &prefix).await;
+
+ let cancel = CancellationToken::new();
+ let (handler, events) = MockHandoffHandler::new();
+ let pod = personhog_coordination::pod::PodHandle::new(
+ Arc::clone(&pod_store),
+ personhog_coordination::pod::PodConfig {
+ pod_name: "margin-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,
+ );
+ let token = cancel.child_token();
+ tokio::spawn(async move { pod.run(token).await });
+
+ put_handoff(&direct_store, 0, None, "margin-pod", HandoffPhase::Warming).await;
+ wait_for_event(&events, HandoffEvent::Warmed(0)).await;
+
+ proxy.set_blackholed(true);
+ proxy.sever();
+
+ // Inside the margin (two thirds of the 6s TTL): still retrying, not
+ // fenced — the lease is still valid and the coordinator cannot have
+ // moved anything.
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ assert!(
+ !events.lock().await.contains(&HandoffEvent::Released(0)),
+ "fencing inside the margin trades availability for nothing"
+ );
+
+ // Margin exhausted: the self-fence must run, well before the pod
+ // could be confused with one that never notices.
+ wait_for_condition(Duration::from_secs(8), POLL_INTERVAL, || {
+ let events = Arc::clone(&events);
+ async move { events.lock().await.contains(&HandoffEvent::Released(0)) }
+ })
+ .await;
+
+ cancel.cancel();
+}
+
+/// The run budget bounds crash loops, not lifetime failures: an attempt
+/// that did real work before failing resets the consecutive count. The
+/// reset is keyed on measured progress, not elapsed time — a time
+/// threshold silently exempts every failure detector slower than it
+/// (the reconcile budget and the stall watchdog both take a minute),
+/// letting wedged components rebuild in place forever. Here a pod
+/// alternates real work and one fast failure more times than its
+/// budget; each failure follows progress, so the run must stay alive
+/// throughout.
+#[tokio::test]
+async fn progress_between_failures_keeps_the_run_alive() {
+ let store = test_store("pod-progress-reset").await;
+ let cancel = CancellationToken::new();
+
+ let events: Arc<Mutex<Vec<HandoffEvent>>> = Arc::new(Mutex::new(Vec::new()));
+ let fail_warm = Arc::new(AtomicBool::new(false));
+ let warm_failures = Arc::new(AtomicUsize::new(0));
+ let handler = FlakyHandoffHandler {
+ events: Arc::clone(&events),
+ fail_warm: Arc::clone(&fail_warm),
+ warm_failures: Arc::clone(&warm_failures),
+ };
+ let pod = personhog_coordination::pod::PodHandle::new(
+ Arc::clone(&store),
+ personhog_coordination::pod::PodConfig {
+ pod_name: "progress-pod".to_string(),
+ lease_ttl: 10,
+ heartbeat_interval: Duration::from_secs(3),
+ reconcile_interval: Duration::from_secs(86_400),
+ run_retry_budget: 3,
+ // Long enough that each cycle's injected failure is observed
+ // and cleared before the rebuild retries — exactly one
+ // no-progress failure per cycle.
+ run_retry_backoff: Duration::from_secs(2),
+ ..Default::default()
+ },
+ Arc::new(handler),
+ None,
+ );
+ let token = cancel.child_token();
+ tokio::spawn(async move { pod.run(token).await });
+
+ // Five work-then-fail cycles against a budget of three: only the
+ // progress reset keeps the run alive past the third.
+ for i in 0..5u32 {
+ fail_warm.store(true, Ordering::SeqCst);
+ put_handoff(&store, i, None, "progress-pod", HandoffPhase::Warming).await;
+ let observed = Arc::clone(&warm_failures);
+ let target = (i + 1) as usize;
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, move || {
+ let observed = Arc::clone(&observed);
+ async move { observed.load(Ordering::SeqCst) >= target }
+ })
+ .await;
+ fail_warm.store(false, Ordering::SeqCst);
+ // The rebuilt attempt re-converges the same handoff and warms it
+ // — the progress that must reset the budget.
+ wait_for_event(&events, HandoffEvent::Warmed(i)).await;
+ }
+
+ cancel.cancel();
+}
+
+/// Exhausting the run budget must fence before the registration
+/// disappears, and no-op convergences must not reset the budget on the
+/// way there. The pod holds partition 0 settled while every attempt
+/// dies on a poisoned partition-1 warm with no applied work in between:
+/// the budget must actually exhaust (settled partition 0's successful
+/// no-op re-convergence on every attempt is a read, not progress), and
+/// the exit must release partition 0 before the teardown revokes the
+/// lease — revocation deregisters instantly, and the dead-owner path it
+/// triggers has no fence of its own.
+#[tokio::test]
+async fn budget_exhaustion_fences_before_deregistering() {
+ let store = test_store("pod-fatal-fence").await;
+ let cancel = CancellationToken::new();
+
+ let events: Arc<Mutex<Vec<HandoffEvent>>> = Arc::new(Mutex::new(Vec::new()));
+ let fail_warm = Arc::new(AtomicBool::new(false));
+ let handler = FlakyHandoffHandler {
+ events: Arc::clone(&events),
+ fail_warm: Arc::clone(&fail_warm),
+ warm_failures: Arc::new(AtomicUsize::new(0)),
+ };
+ let pod = personhog_coordination::pod::PodHandle::new(
+ Arc::clone(&store),
+ personhog_coordination::pod::PodConfig {
+ pod_name: "fatal-fence-pod".to_string(),
+ lease_ttl: 10,
+ heartbeat_interval: Duration::from_secs(3),
+ reconcile_interval: Duration::from_secs(86_400),
+ run_retry_budget: 3,
+ run_retry_backoff: Duration::from_millis(50),
+ ..Default::default()
+ },
+ Arc::new(handler),
+ None,
+ );
+ let token = cancel.child_token();
+ let join = tokio::spawn(async move { pod.run(token).await });
+
+ put_handoff(&store, 0, None, "fatal-fence-pod", HandoffPhase::Warming).await;
+ wait_for_event(&events, HandoffEvent::Warmed(0)).await;
+
+ fail_warm.store(true, Ordering::SeqCst);
+ put_handoff(&store, 1, None, "fatal-fence-pod", HandoffPhase::Warming).await;
+
+ let result = tokio::time::timeout(Duration::from_secs(15), join)
+ .await
+ .expect("the budget must exhaust — no-op convergences must not keep resetting it")
+ .expect("run task");
+ assert!(result.is_err(), "budget exhaustion must surface the error");
+ assert!(
+ events.lock().await.contains(&HandoffEvent::Released(0)),
+ "the held partition must be fenced and released before the lease is revoked"
+ );
+ let pods = store.list_pods().await.expect("list pods");
+ assert!(
+ !pods.iter().any(|p| p.pod_name == "fatal-fence-pod"),
+ "the teardown must deregister on the way out"
+ );
+}
diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rs
index 660217fa7d83..fa906d342335 100644
--- a/rust/personhog-leader/src/main.rs
+++ b/rust/personhog-leader/src/main.rs
@@ -75,7 +75,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// stop in phase 1, only after the drain finishes — signalling them
// together with coordination black-holed every partition for the whole
// drain (dead server, still the registered owner). The coordination
- // graceful window must exceed the pod's drain timeout (30s), and the
+ // graceful window must exceed the pod's drain timeout (30s) plus the pre-revoke fence's short bound (3s), and the
// global timeout must fit both phases.
let mut manager = Manager::builder("personhog-leader")
.with_global_shutdown_timeout(Duration::from_secs(60))
diff --git a/rust/personhog-router/src/config.rs b/rust/personhog-router/src/config.rs
index a7ced2642ffd..d85ee8382b23 100644
--- a/rust/personhog-router/src/config.rs
+++ b/rust/personhog-router/src/config.rs
@@ -197,6 +197,18 @@ pub struct Config {
#[envconfig(default = "12")]
pub router_reconcile_failure_budget: u32,
+ /// How many consecutive coordination-attempt failures the routing
+ /// table's run supervisor tolerates (rebuilding coordination in
+ /// place while the data plane keeps serving) before giving up and
+ /// letting the process restart. A healthy attempt resets the count.
+ #[envconfig(default = "10")]
+ pub router_run_retry_budget: u32,
+
+ /// Base backoff in milliseconds between coordination attempts;
+ /// doubles per consecutive failure up to a fixed cap.
+ #[envconfig(default = "500")]
+ pub router_run_retry_backoff_ms: u64,
+
/// How long a handoff may sit in Warming before the coordinator
/// cancels it by replacement. Warming replays the partition's
/// changelog, so its budget is far above the general handoff
diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rs
index eac69e08d2a1..99d6d5e0ea38 100644
--- a/rust/personhog-router/src/main.rs
+++ b/rust/personhog-router/src/main.rs
@@ -292,6 +292,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
heartbeat_interval: config.heartbeat_interval(),
participant_stall_threshold: config.participant_stall_threshold(),
reconcile_failure_budget: config.router_reconcile_failure_budget,
+ run_retry_budget: config.router_run_retry_budget,
+ run_retry_backoff: Duration::from_millis(config.router_run_retry_backoff_ms),
reconcile_interval: config.router_reconcile_interval(),
};
diff --git a/rust/personhog-test-harness/src/cli.rs b/rust/personhog-test-harness/src/cli.rs
index c7e8d3dc9434..eb734ee9252b 100644
--- a/rust/personhog-test-harness/src/cli.rs
+++ b/rust/personhog-test-harness/src/cli.rs
@@ -36,7 +36,7 @@ pub enum Command {
/// traffic anywhere the router does not serve the database this harness
/// seeds, and every database operation is confined to the configured
/// validation table.
- Traffic(TrafficArgs),
+ Traffic(Box<TrafficArgs>),
}
#[derive(Args, Clone)]
@@ -423,4 +423,12 @@ pub struct TrafficArgs {
/// etcd key prefix, matching the routers' ETCD_PREFIX.
#[arg(long, env = "CHAOS_ETCD_PREFIX", default_value = "/personhog/")]
pub chaos_etcd_prefix: String,
+
+ /// Namespace of the etcd cluster's own pods. Enables the
+ /// `etcd_bounce` scenario (abruptly kill one member of a healthy
+ /// three-member cluster); absent, that scenario is excluded. The
+ /// harness ServiceAccount additionally needs pod list/delete RBAC in
+ /// this namespace.
+ #[arg(long, env = "CHAOS_ETCD_NAMESPACE")]
+ pub chaos_etcd_namespace: Option<String>,
}
diff --git a/rust/personhog-test-harness/src/main.rs b/rust/personhog-test-harness/src/main.rs
index ec528f692823..be2cd95fd738 100644
--- a/rust/personhog-test-harness/src/main.rs
+++ b/rust/personhog-test-harness/src/main.rs
@@ -31,6 +31,6 @@ async fn main() -> Result<()> {
Command::Blast(args) => scenarios::blast::run(args).await,
Command::Consistency(args) => scenarios::consistency::run(args).await,
Command::Gate(args) => scenarios::gate::run(*args).await,
- Command::Traffic(args) => scenarios::traffic::run(args).await,
+ Command::Traffic(args) => scenarios::traffic::run(*args).await,
}
}
diff --git a/rust/personhog-test-harness/src/scenarios/blast.rs b/rust/personhog-test-harness/src/scenarios/blast.rs
index d53d4415e696..3cb4e978d8ca 100644
--- a/rust/personhog-test-harness/src/scenarios/blast.rs
+++ b/rust/personhog-test-harness/src/scenarios/blast.rs
@@ -141,7 +141,11 @@ pub async fn run_traffic(
}
Err(e) => {
collector.writes.record_failure();
- traffic_metrics::record_write_failed(traffic_metrics::LANE_BLAST, &e);
+ traffic_metrics::record_write_failed(
+ traffic_metrics::LANE_BLAST,
+ &e,
+ stop.load(Ordering::Relaxed),
+ );
// `{:#}` prints the full anyhow chain — the outer
// context alone hides the gRPC status underneath.
tracing::warn!(person_id, error = format!("{e:#}"), "write failed");
diff --git a/rust/personhog-test-harness/src/scenarios/chaos.rs b/rust/personhog-test-harness/src/scenarios/chaos.rs
index 69a6af3dcfb5..058efe2258d9 100644
--- a/rust/personhog-test-harness/src/scenarios/chaos.rs
+++ b/rust/personhog-test-harness/src/scenarios/chaos.rs
@@ -27,7 +27,7 @@
use std::collections::HashSet;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
-use std::time::{Duration, SystemTime, UNIX_EPOCH};
+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result};
use k8s_openapi::api::core::v1::Pod;
@@ -46,6 +46,10 @@ pub enum TargetKind {
Leader,
Router,
Writer,
+ /// The coordination store itself. Deliberately not part of the
+ /// random-draw target pool: only the dedicated `EtcdBounce`
+ /// scenario may touch it, under its own quorum guard.
+ Etcd,
}
impl TargetKind {
@@ -54,6 +58,7 @@ impl TargetKind {
TargetKind::Leader => "leader",
TargetKind::Router => "router",
TargetKind::Writer => "writer",
+ TargetKind::Etcd => "etcd",
}
}
}
@@ -109,6 +114,14 @@ enum Scenario {
/// Kill the coordinator, wait for a successor to win the election,
/// kill that one too — election churn plus orphaned reconciliation.
CoordinatorDoubleTap,
+ /// Abruptly kill one etcd member of a ≥3-member cluster: quorum
+ /// survives, state survives (persistent volumes), but every client
+ /// stream pinned to that member breaks at once — the coordination
+ /// blip that must never restart the fleet. The expected signature
+ /// is run-supervisor rebuilds (`run_restarts_total` up) with zero
+ /// container restarts, zero handoffs, and zero client-visible
+ /// errors.
+ EtcdBounce,
}
impl Scenario {
@@ -119,6 +132,7 @@ impl Scenario {
Scenario::StaggeredFollowUp => "staggered_follow_up",
Scenario::CoordinatorKill => "coordinator_kill",
Scenario::CoordinatorDoubleTap => "coordinator_double_tap",
+ Scenario::EtcdBounce => "etcd_bounce",
}
}
@@ -128,6 +142,10 @@ impl Scenario {
Scenario::CoordinatorKill | Scenario::CoordinatorDoubleTap
)
}
+
+ fn needs_etcd_target(self) -> bool {
+ matches!(self, Scenario::EtcdBounce)
+ }
}
/// Scenario draw weights. Singles dominate so the common case stays the
@@ -138,14 +156,17 @@ const SCENARIO_WEIGHTS: &[(Scenario, u32)] = &[
(Scenario::StaggeredFollowUp, 12),
(Scenario::CoordinatorKill, 8),
(Scenario::CoordinatorDoubleTap, 8),
+ (Scenario::EtcdBounce, 8),
];
/// Draw a scenario, excluding coordinator scenarios when no etcd access
-/// is configured (their weight redistributes over the rest).
-fn pick_scenario(rng: &mut impl Rng, coordinator_available: bool) -> Scenario {
+/// is configured and the etcd bounce when no etcd target is configured
+/// (their weight redistributes over the rest).
+fn pick_scenario(rng: &mut impl Rng, coordinator_available: bool, etcd_target: bool) -> Scenario {
let pool: Vec<(Scenario, u32)> = SCENARIO_WEIGHTS
.iter()
.filter(|(s, _)| coordinator_available || !s.needs_coordinator())
+ .filter(|(s, _)| etcd_target || !s.needs_etcd_target())
.copied()
.collect();
let total: u32 = pool.iter().map(|(_, w)| w).sum();
@@ -180,6 +201,11 @@ pub struct ChaosConfig {
/// etcd endpoints + key prefix of the stack under test. Enables the
/// coordinator scenarios; without it they are excluded from the draw.
pub etcd: Option<(String, String)>,
+ /// The etcd cluster's own pods. Enables the `EtcdBounce` scenario;
+ /// without it that scenario is excluded from the draw. Kept out of
+ /// `targets` so the general kill scenarios can never draw etcd —
+ /// only the bounce, with its quorum guard, may touch it.
+ pub etcd_target: Option<TargetSpec>,
}
pub async fn run(cfg: ChaosConfig, shutdown: Arc<AtomicBool>) {
@@ -230,7 +256,7 @@ pub async fn run(cfg: ChaosConfig, shutdown: Arc<AtomicBool>) {
return;
}
- let scenario = pick_scenario(&mut rng, store.is_some());
+ let scenario = pick_scenario(&mut rng, store.is_some(), cfg.etcd_target.is_some());
tracing::info!(scenario = scenario.label(), "chaos scenario starting");
// Pods this scenario has already killed, kept out of every later
// step's min-alive count regardless of how fast k8s reflects the
@@ -302,6 +328,34 @@ async fn execute(
Scenario::CoordinatorKill => {
kill_coordinator(client, cfg, store, scenario, rng, killed).await;
}
+ Scenario::EtcdBounce => {
+ let Some(target) = &cfg.etcd_target else {
+ return;
+ };
+ // Quorum guard: only bounce when all three members are
+ // ready, so the kill leaves two — a healthy majority. The
+ // point is a connection blip, not an availability test;
+ // taking etcd below quorum would halt coordination for the
+ // whole bed and test nothing this scenario is for.
+ let ready = match list_ready(client, target).await {
+ Ok(ready) => ready,
+ Err(e) => {
+ tracing::warn!(error = %e, namespace = %target.namespace, "listing etcd pods failed");
+ counter!("personhog_traffic_chaos_skipped_total", "reason" => "list_failed")
+ .increment(1);
+ return;
+ }
+ };
+ if ready.len() < 3 {
+ counter!("personhog_traffic_chaos_skipped_total", "reason" => "etcd_quorum_guard")
+ .increment(1);
+ return;
+ }
+ // Always abrupt: a graceful etcd shutdown hands off cleanly,
+ // but the failure this scenario reproduces is the sudden
+ // stream break every client sees when a member vanishes.
+ kill_one(client, target, KillMode::Abrupt, scenario, rng, killed).await;
+ }
Scenario::CoordinatorDoubleTap => {
let Some(first) = kill_coordinator(client, cfg, store, scenario, rng, killed).await
else {
@@ -310,7 +364,7 @@ async fn execute(
// The successor needs the old election lease to lapse (abrupt
// kills leave it until TTL) plus a campaign; poll generously.
let deadline = Duration::from_secs(25);
- let start = std::time::Instant::now();
+ let start = Instant::now();
let successor = loop {
if shutdown.load(Ordering::SeqCst) {
return;
@@ -566,7 +620,8 @@ mod tests {
fn coordinator_scenarios_excluded_without_etcd() {
let mut rng = StdRng::seed_from_u64(7);
for _ in 0..1000 {
- assert!(!pick_scenario(&mut rng, false).needs_coordinator());
+ assert!(!pick_scenario(&mut rng, false, false).needs_coordinator());
+ assert!(!pick_scenario(&mut rng, false, false).needs_etcd_target());
}
}
diff --git a/rust/personhog-test-harness/src/scenarios/consistency.rs b/rust/personhog-test-harness/src/scenarios/consistency.rs
index f095b39e483b..b902cef0e097 100644
--- a/rust/personhog-test-harness/src/scenarios/consistency.rs
+++ b/rust/personhog-test-harness/src/scenarios/consistency.rs
@@ -226,7 +226,11 @@ pub async fn run_probers(
}
Err(e) => {
collector.writes.record_failure();
- traffic_metrics::record_write_failed(traffic_metrics::LANE_PROBER, &e);
+ traffic_metrics::record_write_failed(
+ traffic_metrics::LANE_PROBER,
+ &e,
+ stop.load(Ordering::Relaxed),
+ );
tracing::warn!(person_id, error = %e, "probe write failed");
continue;
}
@@ -289,7 +293,11 @@ pub async fn run_probers(
collector.reads.record_failure();
traffic_metrics::record_read_failed(
traffic_metrics::LANE_PROBER,
- traffic_metrics::status_reason(&e),
+ if stop.load(Ordering::Relaxed) {
+ traffic_metrics::REASON_SHUTDOWN
+ } else {
+ traffic_metrics::status_reason(&e)
+ },
);
tracing::warn!(person_id, error = %e, "probe read failed");
}
diff --git a/rust/personhog-test-harness/src/scenarios/traffic.rs b/rust/personhog-test-harness/src/scenarios/traffic.rs
index 76c168d0e83e..84e503b8fc50 100644
--- a/rust/personhog-test-harness/src/scenarios/traffic.rs
+++ b/rust/personhog-test-harness/src/scenarios/traffic.rs
@@ -276,6 +276,11 @@ fn chaos_config(args: &TrafficArgs) -> ChaosConfig {
.chaos_etcd_endpoints
.clone()
.map(|endpoints| (endpoints, args.chaos_etcd_prefix.clone())),
+ etcd_target: args.chaos_etcd_namespace.as_ref().map(|ns| TargetSpec {
+ kind: TargetKind::Etcd,
+ namespace: ns.clone(),
+ selector: "app.kubernetes.io/name=etcd".to_string(),
+ }),
}
}
@@ -422,6 +427,7 @@ mod tests {
#[test]
fn vacuous_or_panicking_configurations_are_rejected() {
let valid = TrafficArgs {
+ chaos_etcd_namespace: None,
router_url: "http://localhost:1".to_string(),
enabled: true,
team_id: 900_101,
diff --git a/rust/personhog-test-harness/src/stack/etcd.rs b/rust/personhog-test-harness/src/stack/etcd.rs
index fbfdb4a10319..bb501a077f4f 100644
--- a/rust/personhog-test-harness/src/stack/etcd.rs
+++ b/rust/personhog-test-harness/src/stack/etcd.rs
@@ -1,6 +1,7 @@
use anyhow::{bail, Context, Result};
use assignment_coordination::store::{EtcdStore, StoreConfig};
use personhog_coordination::store::PersonhogStore;
+use std::time::{Duration, Instant};
pub async fn connect(endpoints: &str, prefix: &str) -> Result<PersonhogStore> {
let config = StoreConfig {
@@ -78,9 +79,9 @@ pub async fn revoke_coordinator_lease_if_held_by(
pub async fn wait_for_leader(
store: &PersonhogStore,
holder: &str,
- deadline: std::time::Duration,
+ deadline: Duration,
) -> Result<()> {
- let start = std::time::Instant::now();
+ let start = Instant::now();
loop {
if let Some(leader) = store.get_leader().await.unwrap_or(None) {
if leader.holder == holder {
@@ -90,7 +91,7 @@ pub async fn wait_for_leader(
if start.elapsed() > deadline {
bail!("{holder} did not acquire coordinator leadership within {deadline:?}");
}
- tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+ tokio::time::sleep(Duration::from_millis(100)).await;
}
}
diff --git a/rust/personhog-test-harness/src/stack/mod.rs b/rust/personhog-test-harness/src/stack/mod.rs
index 50925388f062..480d05de62a0 100644
--- a/rust/personhog-test-harness/src/stack/mod.rs
+++ b/rust/personhog-test-harness/src/stack/mod.rs
@@ -385,8 +385,12 @@ impl Stack {
}
/// SIGCONT the paused zombie. It wakes believing it still owns its
- /// partitions; whatever it does next (self-fence, exit, re-register)
- /// must not corrupt state that has moved to the new owner.
+ /// partitions; the contract is that it detects the revoked lease,
+ /// self-fences locally, and rejoins with a fresh session — at which
+ /// point the rebalancer may legitimately assign it partitions again.
+ /// It therefore returns to the live set: convergence counts it as a
+ /// valid owner, verification reads data it serves, and check_alive
+ /// fails the run if the self-fence path crashes it instead.
pub fn resume_zombie(&mut self) -> Result<String> {
let (pod_name, proc) = self
.paused
@@ -394,7 +398,7 @@ impl Stack {
.context("no paused zombie leader to resume")?;
proc.sigcont();
tracing::info!(pod = %pod_name, "SIGCONTed zombie leader");
- self.retired.push(proc);
+ self.leaders.push((pod_name.clone(), proc));
Ok(pod_name)
}
@@ -410,12 +414,12 @@ impl Stack {
/// wiring.
async fn coordinator_router_index(&self) -> Result<usize> {
let traffic_router = format!("harness-router-{}", self.config.routers - 1);
- let deadline = std::time::Instant::now() + Duration::from_secs(5);
+ let deadline = Instant::now() + Duration::from_secs(5);
let holder = loop {
if let Some(leader) = self.store.get_leader().await? {
break leader.holder;
}
- if std::time::Instant::now() >= deadline {
+ if Instant::now() >= deadline {
bail!("no coordinator elected within 5s; cannot target coordinator chaos");
}
tokio::time::sleep(Duration::from_millis(100)).await;
diff --git a/rust/personhog-test-harness/src/traffic_metrics.rs b/rust/personhog-test-harness/src/traffic_metrics.rs
index 7f106fd70b0a..7ca608b9a2e9 100644
--- a/rust/personhog-test-harness/src/traffic_metrics.rs
+++ b/rust/personhog-test-harness/src/traffic_metrics.rs
@@ -57,12 +57,19 @@ pub fn record_write_ok(lane: &'static str, elapsed: Duration) {
/// Record a write the stack refused or dropped. Latency is deliberately
/// not recorded: a timeout's duration is the deadline, not the stack's
/// service time, and mixing the two distorts the percentiles.
-pub fn record_write_failed(lane: &'static str, err: &anyhow::Error) {
+/// Reason label for failures observed after the shutdown signal: the
+/// harness's exit races its own in-flight requests (and any deploy
+/// rolling the stack under it), so these are quarantined under one
+/// reason instead of polluting the genuine failure reasons the
+/// dashboards are read by.
+pub const REASON_SHUTDOWN: &str = "shutdown";
+
+pub fn record_write_failed(lane: &'static str, err: &anyhow::Error, shutting_down: bool) {
counter!(
"personhog_traffic_writes_total",
"lane" => lane,
"outcome" => "failed",
- "reason" => status_reason(err),
+ "reason" => if shutting_down { REASON_SHUTDOWN } else { status_reason(err) },
)
.increment(1);
}