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 optimizations and monitoring (#82913)

Zach Brown1437d41c05ca
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index d726599f46d2..ee9b56d757ed 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -8577,6 +8577,7 @@ dependencies = [
"axum 0.7.9",
"bytes",
"common-alloc",
+ "common-metrics",
"dashmap 6.1.0",
"envconfig",
"flate2",
diff --git a/rust/common/assignment-coordination/src/store.rs b/rust/common/assignment-coordination/src/store.rs
index de8d05ac55f8..575c8611a90d 100644
--- a/rust/common/assignment-coordination/src/store.rs
+++ b/rust/common/assignment-coordination/src/store.rs
@@ -32,13 +32,18 @@ pub struct EtcdStore {
/// Records one etcd operation's wall time on drop, so every return path
/// (including errors) lands in the histogram. Includes this layer's
/// (de)serialization, which is negligible next to the etcd round trip.
-struct OpTimer {
+///
+/// Public so an operation driven outside this store still lands in the
+/// same histogram: a lease renewal runs off the `LeaseKeeper` this store
+/// handed out, never through a method here, and it is the highest-rate
+/// etcd call the fleet makes.
+pub struct OpTimer {
op: &'static str,
start: std::time::Instant,
}
impl OpTimer {
- fn new(op: &'static str) -> Self {
+ pub fn new(op: &'static str) -> Self {
Self {
op,
start: std::time::Instant::now(),
@@ -53,6 +58,20 @@ impl Drop for OpTimer {
}
}
+/// Bytes moved by one etcd operation, keys included. Payload size is the
+/// axis on which coordination outgrows its store — etcd caps a request at
+/// `--max-request-bytes`, and a record whose size scales with fleet size
+/// crosses that limit long before op counts or latency show strain — so
+/// it is measured next to duration rather than inferred from it.
+fn record_payload_bytes(op: &'static str, bytes: usize) {
+ metrics::histogram!("assignment_coordination_etcd_payload_bytes", "op" => op)
+ .record(bytes as f64);
+}
+
+fn kvs_bytes(kvs: &[etcd_client::KeyValue]) -> usize {
+ kvs.iter().map(|kv| kv.key().len() + kv.value().len()).sum()
+}
+
impl EtcdStore {
pub async fn connect(config: StoreConfig) -> Result<Self> {
// Transport-level liveness so a silent network partition fails
@@ -97,11 +116,14 @@ impl EtcdStore {
pub async fn get_raw(&self, key: &str) -> Result<Option<Vec<u8>>> {
let _t = OpTimer::new("get_raw");
let resp = self.client.clone().get(key, None).await?;
+ record_payload_bytes("get_raw", kvs_bytes(resp.kvs()));
Ok(resp.kvs().first().map(|kv| kv.value().to_vec()))
}
pub async fn put_raw(&self, key: &str, value: impl Into<Vec<u8>>) -> Result<()> {
let _t = OpTimer::new("put_raw");
+ let value = value.into();
+ record_payload_bytes("put_raw", key.len() + value.len());
self.client.clone().put(key, value, None).await?;
Ok(())
}
@@ -111,6 +133,7 @@ impl EtcdStore {
pub async fn get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
let _t = OpTimer::new("get");
let resp = self.client.clone().get(key, None).await?;
+ record_payload_bytes("get", kvs_bytes(resp.kvs()));
match resp.kvs().first() {
Some(kv) => Ok(Some(serde_json::from_slice(kv.value())?)),
None => Ok(None),
@@ -120,6 +143,7 @@ impl EtcdStore {
pub async fn get_versioned<T: DeserializeOwned>(&self, key: &str) -> Result<Option<(T, i64)>> {
let _t = OpTimer::new("get_versioned");
let resp = self.client.clone().get(key, None).await?;
+ record_payload_bytes("get_versioned", kvs_bytes(resp.kvs()));
match resp.kvs().first() {
Some(kv) => {
let value = serde_json::from_slice(kv.value())?;
@@ -141,6 +165,7 @@ impl EtcdStore {
) -> Result<Option<(T, i64)>> {
let _t = OpTimer::new("get_with_mod_revision");
let resp = self.client.clone().get(key, None).await?;
+ record_payload_bytes("get_with_mod_revision", kvs_bytes(resp.kvs()));
match resp.kvs().first() {
Some(kv) => {
let value = serde_json::from_slice(kv.value())?;
@@ -150,10 +175,45 @@ impl EtcdStore {
}
}
+ /// Like `get`, but also returns the store revision the read was
+ /// taken at, to anchor a `watch_key_from` so a key that vanishes
+ /// before the watch attaches is still reported. The revision comes
+ /// from the response header, so it is meaningful even when the key
+ /// is absent — exactly the case a waiter anchors on.
+ pub async fn get_with_revision<T: DeserializeOwned>(
+ &self,
+ key: &str,
+ ) -> Result<(Option<T>, i64)> {
+ let _t = OpTimer::new("get_with_revision");
+ let resp = self.client.clone().get(key, None).await?;
+ record_payload_bytes("get_with_revision", kvs_bytes(resp.kvs()));
+ let revision = resp.header().map(|h| h.revision()).unwrap_or(0);
+ match resp.kvs().first() {
+ Some(kv) => Ok((Some(serde_json::from_slice(kv.value())?), revision)),
+ None => Ok((None, revision)),
+ }
+ }
+
pub async fn list<T: DeserializeOwned>(&self, prefix: &str) -> Result<Vec<T>> {
Ok(self.list_with_revision(prefix).await?.0)
}
+ /// The keys under `prefix`, without their values. For callers that
+ /// need to know what exists rather than what it says — etcd leaves
+ /// the values out of the response, so the cost does not scale with
+ /// how large the records are.
+ pub async fn list_keys(&self, prefix: &str) -> Result<Vec<String>> {
+ let _t = OpTimer::new("list_keys");
+ let options = GetOptions::new().with_prefix().with_keys_only();
+ let resp = self.client.clone().get(prefix, Some(options)).await?;
+ record_payload_bytes("list_keys", kvs_bytes(resp.kvs()));
+ Ok(resp
+ .kvs()
+ .iter()
+ .filter_map(|kv| kv.key_str().ok().map(str::to_string))
+ .collect())
+ }
+
/// Like `list`, but also returns the etcd store revision the snapshot
/// was taken at. Pair with `watch_from(prefix, revision + 1)` for a
/// gap-free snapshot-then-watch handshake: every event at or before
@@ -166,6 +226,7 @@ impl EtcdStore {
let _t = OpTimer::new("list_with_revision");
let options = GetOptions::new().with_prefix();
let resp = self.client.clone().get(prefix, Some(options)).await?;
+ record_payload_bytes("list_with_revision", kvs_bytes(resp.kvs()));
let revision = resp.header().map(|h| h.revision()).unwrap_or(0);
let items = resp
.kvs()
@@ -185,6 +246,7 @@ impl EtcdStore {
let _t = OpTimer::new("list_with_mod_revisions");
let options = GetOptions::new().with_prefix();
let resp = self.client.clone().get(prefix, Some(options)).await?;
+ record_payload_bytes("list_with_mod_revisions", kvs_bytes(resp.kvs()));
resp.kvs()
.iter()
.map(|kv| Ok((serde_json::from_slice(kv.value())?, kv.mod_revision())))
@@ -212,6 +274,7 @@ impl EtcdStore {
) -> Result<()> {
let _t = OpTimer::new("put");
let value = serde_json::to_string(value)?;
+ record_payload_bytes("put", key.len() + value.len());
let options = lease_id.map(|id| PutOptions::new().with_lease(id));
self.client.clone().put(key, value, options).await?;
Ok(())
@@ -253,8 +316,25 @@ impl EtcdStore {
Ok(stream)
}
+ /// Watch a single key — not a prefix — from an explicit revision
+ /// (inclusive). Waiters on one key use this so an unrelated sibling
+ /// key sharing the same string prefix cannot wake them.
+ pub async fn watch_key_from(&self, key: &str, start_revision: i64) -> Result<WatchStream> {
+ let _t = OpTimer::new("watch_key_from");
+ let options = WatchOptions::new().with_start_revision(start_revision);
+ let stream = self.client.clone().watch(key, Some(options)).await?;
+ Ok(stream)
+ }
+
// ── Transactions ─────────────────────────────────────────────
+ /// Deliberately not in `record_payload_bytes`: a transaction's size
+ /// lives in the request, which is no longer reachable once the `Txn`
+ /// is built, and its response carries only what its reads returned —
+ /// nothing, for the plan transaction that actually approaches
+ /// `--max-request-bytes`. A histogram here would sit at zero under
+ /// the name an operator reaches for first. `apply_plan` measures the
+ /// request side directly instead.
pub async fn txn(&self, txn: Txn) -> Result<TxnResponse> {
let _t = OpTimer::new("txn");
Ok(self.client.clone().txn(txn).await?)
@@ -289,11 +369,13 @@ impl EtcdStore {
&self,
lease_id: i64,
) -> Result<(etcd_client::LeaseKeeper, etcd_client::LeaseKeepAliveStream)> {
+ let _t = OpTimer::new("keep_alive");
let (keeper, stream) = self.client.clone().lease_keep_alive(lease_id).await?;
Ok((keeper, stream))
}
pub async fn revoke_lease(&self, lease_id: i64) -> Result<()> {
+ let _t = OpTimer::new("revoke_lease");
self.client.clone().lease_revoke(lease_id).await?;
Ok(())
}
diff --git a/rust/common/metrics/src/lib.rs b/rust/common/metrics/src/lib.rs
index 0d0e60175272..d17043e0edf5 100644
--- a/rust/common/metrics/src/lib.rs
+++ b/rust/common/metrics/src/lib.rs
@@ -99,12 +99,32 @@ fn install_metrics_routes(
.layer(axum::middleware::from_fn(track_metrics))
}
+/// Buckets for etcd payload sizes, straddling the server's
+/// `--max-request-bytes` (1.5 MiB plus gRPC overhead) so a request or a
+/// response creeping toward the limit is visible before etcd starts
+/// rejecting it. The default ladder tops out at 10_000, which a list of
+/// a few hundred coordination records clears in one step.
+///
+/// Shared because the metric is emitted by the store layer itself, so
+/// every binary that opens an `EtcdStore` reports it — and a metric name
+/// carrying two different ladders across jobs cannot be aggregated.
+pub const ETCD_PAYLOAD_SIZE_BUCKETS_BYTES: &[f64] = &[
+ 1024.0, 8192.0, 65536.0, 262144.0, 524288.0, 1048576.0, 1572864.0, 2097152.0, 4194304.0,
+];
+
fn build_prometheus_builder(product: Option<String>) -> PrometheusBuilder {
const BUCKETS: &[f64] = &[
1.0, 5.0, 10.0, 50.0, 100.0, 250.0, 500.0, 1000.0, 2000.0, 5000.0, 10000.0,
];
- let mut builder = PrometheusBuilder::new().set_buckets(BUCKETS).unwrap();
+ let mut builder = PrometheusBuilder::new()
+ .set_buckets(BUCKETS)
+ .unwrap()
+ .set_buckets_for_metric(
+ Matcher::Full("assignment_coordination_etcd_payload_bytes".into()),
+ ETCD_PAYLOAD_SIZE_BUCKETS_BYTES,
+ )
+ .unwrap();
if let Some(product) = product {
builder = builder.add_global_label("product", product);
}
diff --git a/rust/ingestion-control-plane/src/personhog.rs b/rust/ingestion-control-plane/src/personhog.rs
index fa52bc6fbbec..1208ea7ad7d4 100644
--- a/rust/ingestion-control-plane/src/personhog.rs
+++ b/rust/ingestion-control-plane/src/personhog.rs
@@ -33,6 +33,20 @@ pub struct RawKv {
pub lease: i64,
}
+/// The freeze-quorum membership a handoff requires, from the same
+/// snapshot. `None` — nothing recorded, or a reference whose record is
+/// absent — is the coordinator's own fallback: require every live
+/// router.
+fn resolve_quorum<'a>(
+ quorums: &'a HashMap<String, Vec<String>>,
+ handoff: &'a HandoffState,
+) -> Option<&'a [String]> {
+ match &handoff.freeze_quorum_ref {
+ Some(id) => quorums.get(id).map(Vec::as_slice),
+ None => handoff.freeze_quorum.as_deref(),
+ }
+}
+
/// The coordination prefix, parsed into records. Unparseable or unknown
/// keys are carried as findings instead of failing the snapshot — an ops
/// tool must render a broken keyspace, not error on it.
@@ -42,6 +56,9 @@ pub struct RawSnapshot {
pub routers: Vec<(RegisteredRouter, i64)>,
pub assignments: Vec<PartitionAssignment>,
pub handoffs: Vec<HandoffState>,
+ /// Freeze-quorum membership by record id, so a handoff that refers
+ /// to one can be judged from the same snapshot.
+ pub freeze_quorums: HashMap<String, Vec<String>>,
pub freeze_acks: Vec<RouterFreezeAck>,
pub drained_acks: Vec<PodDrainedAck>,
pub warmed_acks: Vec<PodWarmedAck>,
@@ -90,6 +107,10 @@ pub fn parse_snapshot(kvs: &[RawKv], prefix: &str, revision: i64) -> RawSnapshot
if let Some(handoff) = parse::<HandoffState>(kv, errors) {
snapshot.handoffs.push(handoff);
}
+ } else if let Some(id) = suffix.strip_prefix("freeze_quorums/") {
+ if let Some(members) = parse::<Vec<String>>(kv, errors) {
+ snapshot.freeze_quorums.insert(id.to_string(), members);
+ }
} else if suffix.starts_with("freeze_acks/") {
if let Some(ack) = parse::<RouterFreezeAck>(kv, errors) {
snapshot.freeze_acks.push(ack);
@@ -223,13 +244,14 @@ fn waiting_on(
freeze_acks: &[RouterFreezeAck],
drained_acks: &[PodDrainedAck],
warmed_acks: &[PodWarmedAck],
+ quorum: Option<&[String]>,
) -> Option<String> {
match handoff.phase {
HandoffPhase::Freezing => {
- if freeze_quorum_met(routers, freeze_acks, handoff) {
+ if freeze_quorum_met(routers, freeze_acks, handoff, quorum) {
Some("freeze quorum met; waiting on the coordinator to advance".to_string())
} else {
- let missing = missing_freeze_ackers(routers, freeze_acks, handoff);
+ let missing = missing_freeze_ackers(routers, freeze_acks, handoff, quorum);
Some(format!(
"waiting on freeze acks from {}",
missing.join(", ")
@@ -424,6 +446,7 @@ pub fn derive_view(
&freeze_acks,
&drained_acks,
&warmed_acks,
+ resolve_quorum(&raw.freeze_quorums, h),
);
let new_owner_registered = pod_registered(&h.new_owner);
@@ -473,7 +496,12 @@ pub fn derive_view(
phase_age_secs: age,
past_deadline,
waiting_on: waiting,
- missing_freeze_ackers: missing_freeze_ackers(&routers, &freeze_acks, h),
+ missing_freeze_ackers: missing_freeze_ackers(
+ &routers,
+ &freeze_acks,
+ h,
+ resolve_quorum(&raw.freeze_quorums, h),
+ ),
old_owner_registered: h.old_owner.as_deref().map(pod_registered),
new_owner_registered,
}
diff --git a/rust/personhog-coordination/README.md b/rust/personhog-coordination/README.md
index 34867b68804c..dc013c817dac 100644
--- a/rust/personhog-coordination/README.md
+++ b/rust/personhog-coordination/README.md
@@ -14,7 +14,7 @@ Etcd gives us the building blocks we need without rolling our own consensus:
- **Leases** for failure detection: pod keys auto-delete when a pod crashes, triggering reassignment
- **Watches** for reactivity: components react to state changes instead of polling
-- **Transactions (CAS)** for leader election: only one coordinator runs at a time
+- **Transactions (CAS)** for leader election: only one coordinator runs at a time. Standby candidates watch the leader key rather than campaigning on a timer, so election traffic tracks how often leadership changes instead of how many candidates are running
- **Strong consistency**: all participants see the same state
## Components
@@ -44,7 +44,7 @@ Partitions that need to move go through a four-phase state machine. The protocol
Freezing --> Draining --> Warming --> Complete --> (deleted)
```
-1. **Freezing**: Coordinator creates the handoff, snapshotting the then-registered routers into the record's `freeze_quorum`. Routers begin buffering ("stashing") incoming writes for the partition and write a `RouterFreezeAck`. The old owner does *not* yet drain — it continues serving until the quorum has acked, because while a single router still forwards traffic to the old owner the inflight count cannot meaningfully be observed as zero. The required ackers are the creation-time snapshot intersected with the live registry, so the requirement only ever shrinks: a router that dies drops out, and one that registers later is never added (it anchors its watch after the handoff, may never see the `Freezing` event, and its table starts fail-closed, so its ack is neither obtainable nor needed). Once every required router has written an ack matching the current handoff's `handoff_id`, the coordinator advances to `Draining` via a compare-and-swap on the handoff key's `mod_revision`.
+1. **Freezing**: Coordinator creates the handoff, snapshotting the then-registered routers into a membership record the handoff refers to by `freeze_quorum_ref`. Routers begin buffering ("stashing") incoming writes for the partition and write a `RouterFreezeAck`. The old owner does *not* yet drain — it continues serving until the quorum has acked, because while a single router still forwards traffic to the old owner the inflight count cannot meaningfully be observed as zero. The required ackers are the creation-time snapshot intersected with the live registry, so the requirement only ever shrinks: a router that dies drops out, and one that registers later is never added (it anchors its watch after the handoff and its table starts fail-closed, so it cannot be routing to the old owner and its ack is not needed — it writes one anyway as it bootstraps, which is what keeps the pre-membership fallback satisfiable). Once every required router has written an ack matching the current handoff's `handoff_id`, the coordinator advances to `Draining` via a compare-and-swap on the handoff key's `mod_revision`.
2. **Draining**: No router can forward new requests to the old owner anymore (every router is stashing). The old owner waits for its inflight request handlers to complete, then writes a `PodDrainedAck`. Because the leader's produce path awaits the Kafka delivery future before returning success, "no inflight" implies "every write this pod ever acked is durable in Kafka." When the ack arrives (or the old owner is no longer registered), the coordinator advances to `Warming`.
@@ -56,6 +56,26 @@ The handoff record carries `old_owner: Option<String>`. `None` denotes an initia
Every handoff carries a unique `handoff_id`, and every ack (`RouterFreezeAck`, `PodDrainedAck`, `PodWarmedAck`) echoes it. Quorum checks count only acks whose id matches the current handoff, so a stale ack left over from an earlier handoff of the same partition can never satisfy a later one.
+#### Where the freeze quorum's membership lives
+
+Every handoff a plan creates shares one membership — the router registry as the coordinator saw it — so the plan writes it once under `freeze_quorums/{id}` and each handoff carries only that id. Written into each handoff instead, it grew with the fleet, and a plan transaction grew with the fleet times the partition count: at a few hundred of each it passed etcd's `--max-request-bytes`, which rejects the whole transaction, and it was paid again by every list of handoffs. The coordinator's reconcile tick deletes membership records no live handoff refers to, listing the ids before the handoffs so a record written mid-sweep is never a candidate.
+
+Resolution fails closed. An id whose record is missing reads as *unknown* membership, which falls back to requiring every live router — the same rule as a record that predates the field. Both are stricter than any recorded membership, so a lost or prematurely collected record can only delay a handoff. The distinction that matters is against *empty* membership, which requires nobody: that is a real snapshot (zero routers registered at creation), and it must never be what an unresolvable reference degrades to.
+
+Only the coordinator judges the quorum, and only one coordinator leads at a time, which is what makes the roll safe. A new leader reading a record written before this change uses the membership it carries inline. An old leader reading a record written after it sees no membership at all and falls back to requiring every live router — satisfiable, since a router that joins late acks in-progress handoffs as it bootstraps, so a mid-roll failover slows a handoff rather than wedging it.
+
+##### Accepted degradations
+
+Each is bounded by something that already exists, and none of them can advance a handoff early or lose an acked write. Detail lives at the code site.
+
+| What degrades | When it happens | What bounds it |
+| --- | --- | --- |
+| A handoff loses its membership reference and falls back to requiring every live router | An old-binary leader advances that handoff mid-roll: phase advances rewrite the whole record, and its struct has nowhere to carry the reference through | The roll — a finished one cannot produce it. The fallback is the stricter rule, so it only ever delays a handoff. Not counted: `unresolved_freeze_quorums_total` sees references that fail to resolve, never ones stripped |
+| A pod stays registered as `Draining`, and graceful handoffs toward it park until it expires | Both the drain's bounded setup and the bounded revoke time out against a hung etcd | One lease TTL, the same window a pod crashing right after registering already costs |
+| A cancelled session leaves a registered phantom — a pod phantom parks writes behind plans toward it, a router phantom stalls freezes created in its window | A session begin is cancelled after its registration may have landed, and the bounded revoke times out too | One lease TTL, as above |
+
+A watcher etcd cancels — compaction, watcher pressure — is delivered as an ordinary response with `canceled` set and nothing ever after it. Every watch loop that must stay live treats that response as a failed attempt (`live_watch_response`), so it surfaces in the same restart-and-rebuild path as a broken stream rather than parking the loop on a dead watcher. Two loops handle it differently: the pod's own-registration watch — best-effort acceleration of a teardown that completes without it — ends for the session instead, and the standby's leader watch waits out its fallback window and re-reads, so a cancelled watch never observes an opening slower than a stalled one and no failure mode costs etcd more than the healthy cadence.
+
#### Why the Freezing/Draining split matters
If a single phase served both purposes (router stash *and* old-owner drain in parallel), a slow router could send a final write to the old owner *after* the old owner observed inflight=0 momentarily and wrote `DrainedAck`. The coordinator would then advance to Warming based on a stale ack. The old owner would still process that final write, advancing Kafka HWM past the point warming snapshots, and the new owner's cache would be missing the record — silently stale. Sequencing the phases ensures "no inflight" actually means "no producer can append more."
diff --git a/rust/personhog-coordination/src/coordinator.rs b/rust/personhog-coordination/src/coordinator.rs
index 8cfc98d357ab..2e23cfb36b03 100644
--- a/rust/personhog-coordination/src/coordinator.rs
+++ b/rust/personhog-coordination/src/coordinator.rs
@@ -1,4 +1,6 @@
+use std::collections::hash_map::DefaultHasher;
use std::collections::{HashMap, HashSet};
+use std::hash::{Hash, Hasher};
use std::str::from_utf8;
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -31,7 +33,17 @@ pub struct CoordinatorConfig {
pub name: String,
pub leader_lease_ttl: i64,
pub keepalive_interval: Duration,
- pub election_retry_interval: Duration,
+ /// How long a standby waits on its leader-key watch before
+ /// re-reading the key — the bound on how long a stalled watch can
+ /// hide an opening, and the retry pace when the election cannot be
+ /// observed at all.
+ pub standby_poll_interval: Duration,
+
+ pub run_retry_backoff: Duration,
+ /// How long without a bad ending before the pace starts over —
+ /// without decay, a bad spell in the morning charges an isolated
+ /// evening failure the cap instead of the base.
+ pub backoff_decay_window: Duration,
/// How long to wait after the first pod event before rebalancing, to batch
/// rapid pod registrations into a single rebalance.
pub rebalance_debounce_interval: Duration,
@@ -79,16 +91,19 @@ impl Default for CoordinatorConfig {
fn default() -> Self {
Self {
name: "coordinator-0".to_string(),
- // A crashed leader blocks every handoff until its election
- // lease expires and a survivor's next campaign fires, so the
- // worst-case coordinator outage is ttl + retry. 5s + 1s keeps
- // that near the pod-crash detection window, while the 1s
- // keepalive gives the leader several attempts within the TTL
- // before it abdicates. Graceful exits don't wait on any of
- // this — the lease is revoked on the way out.
+ // Succession follows the key's deletion, so the TTL bounds
+ // a crashed leader's outage: 5s sits near the pod-crash
+ // detection window, and the 1s keepalive gives several
+ // renewal attempts inside it. Graceful exits revoke instead.
leader_lease_ttl: 5,
keepalive_interval: Duration::from_secs(1),
- election_retry_interval: Duration::from_secs(1),
+ // An idle standby's whole etcd cost: one read and one watch
+ // stream per interval, bounding a silently stalled watch.
+ standby_poll_interval: Duration::from_secs(5),
+ // Doubles per consecutive bad ending, capped at the lease
+ // TTL (see `pace_after_ending`'s invariant).
+ run_retry_backoff: Duration::from_millis(500),
+ backoff_decay_window: Duration::from_secs(300),
rebalance_debounce_interval: Duration::from_secs(1),
reconcile_interval: Duration::from_secs(5),
handoff_deadline: Duration::from_secs(120),
@@ -122,6 +137,122 @@ pub struct Coordinator {
k8s_awareness: Option<Arc<K8sAwareness>>,
}
+/// How long the election lease revoke may take before shutdown stops
+/// waiting for it.
+///
+/// INVARIANT: one keepalive round's join plus this revoke must fit the
+/// coordinator's graceful budget with room; the router's
+/// `validate_lease_timescales` refuses a configuration that breaks it.
+/// Deliberately not the pod's number — its budget differs, and matching
+/// the two constants is what once put this one at its ceiling.
+pub const REVOKE_TIMEOUT: Duration = Duration::from_secs(2);
+
+/// How much of a paced wait the per-candidate offset may remove. Wide
+/// enough to separate candidates that failed together, small enough that
+/// the pace still restrains a wedged one.
+const JITTER_FRACTION: f64 = 0.25;
+
+/// A stable fraction in [0, 1) derived from a candidate's name. The
+/// disturbances that end terms are shared, so the fleet must not walk
+/// its ladders in lockstep — derived rather than random so the wait is
+/// reproducible in a test.
+fn jitter_offset(name: &str) -> f64 {
+ let mut hasher = DefaultHasher::new();
+ name.hash(&mut hasher);
+ // Keep the 53 bits an f64 can hold exactly, so the ratio is a uniform
+ // fraction rather than a rounded one.
+ (hasher.finish() >> 11) as f64 / (1u64 << 53) as f64
+}
+
+/// Shorten a wait by this candidate's own offset.
+///
+/// Downward only, so a caller's own bound on the wait still holds after
+/// jittering and no site needs a second clamp.
+fn jittered(wait: Duration, name: &str) -> Duration {
+ wait.mul_f64(1.0 - JITTER_FRACTION * jitter_offset(name))
+}
+
+/// The wait before campaigning again after a term ended badly, growing
+/// while endings keep arriving. A free function so the invariant below
+/// is checkable without a store.
+///
+/// Every bad ending shares this one pace — the etcd writes a campaign
+/// spends are what it restrains. A candidate that could not observe the
+/// election retries at the poll cadence instead, having spent only
+/// reads.
+///
+/// INVARIANT: the wait never exceeds `leader_lease_ttl` — pacing past
+/// it would make a candidate slower to take a free election than to
+/// wait out a crashed leader's lease.
+fn pace_after_ending(
+ config: &CoordinatorConfig,
+ consecutive: &mut u32,
+ last: &mut Option<Instant>,
+) -> Duration {
+ let quiet = last.is_none_or(|at| at.elapsed() >= config.backoff_decay_window);
+ *last = Some(Instant::now());
+ *consecutive = if quiet {
+ 1
+ } else {
+ consecutive.saturating_add(1)
+ };
+ let cap = Duration::from_secs(config.leader_lease_ttl.max(0) as u64);
+ let paced = config
+ .run_retry_backoff
+ .saturating_mul(2u32.saturating_pow(consecutive.saturating_sub(1)))
+ .min(cap);
+ jittered(paced, &config.name)
+}
+
+/// A cancellation this coordinator intends, and what to attribute it to
+/// once it has landed.
+///
+/// Counted after the transaction rather than when the plan is built: a
+/// concurrent coordinator can win the same partition, and counting at
+/// intent attributes cancellations this coordinator never made — to
+/// named routers, in the case of the missing-acker counter.
+struct Cancellation {
+ reason: &'static str,
+ missing_ackers: Vec<String>,
+}
+
+impl Cancellation {
+ fn record(&self) {
+ counter!(
+ "personhog_coordination_handoffs_cancelled_total",
+ "reason" => self.reason,
+ )
+ .increment(1);
+ for router in &self.missing_ackers {
+ counter!(
+ "personhog_coordination_freeze_ack_missing_total",
+ "router" => router.clone(),
+ )
+ .increment(1);
+ }
+ }
+}
+
+/// A cancellation with no successor and no live owner to reaffirm
+/// toward, applied as its own guarded transaction after the plan.
+struct FallbackDelete {
+ predecessor: HandoffState,
+ mod_revision: i64,
+ cancellation: Cancellation,
+}
+
+/// Why a standby stopped waiting on the leader-key watch.
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Woke {
+ /// The leader key was deleted: the election is open.
+ Opened,
+ /// The fallback interval elapsed; re-read in case the watch is
+ /// stalled without having errored.
+ Fallback,
+ /// The stream ended or errored, so it can no longer be trusted.
+ StreamLost,
+}
+
/// What prompted a phase-advance evaluation. Only ack-triggered
/// evaluations record the ack-to-advance span: a departure or tick can
/// legitimately advance a handoff on acks that arrived long before, and
@@ -150,27 +281,225 @@ impl Coordinator {
/// Run the coordinator loop. Continuously attempts leader election;
/// when elected, runs the coordination loop until leadership is lost
/// or cancellation is requested.
- pub async fn run(&self, cancel: CancellationToken) -> Result<()> {
+ pub async fn run(&self, cancel: CancellationToken) {
util::preregister_coordinator_metrics();
+ // Paces retries only — nothing here escalates. It grows while
+ // bad endings keep arriving and starts over after a quiet
+ // window, so a wedged coordinator settles at the cap while an
+ // isolated failure long after a bad spell still costs the base.
+ let mut consecutive_endings = 0u32;
+ let mut last_ending: Option<Instant> = None;
loop {
if cancel.is_cancelled() {
- return Ok(());
+ return;
}
- // Awaited to completion, never raced against cancellation:
- // dropping try_lead mid-cleanup would strand the election
- // lease until TTL expiry, stalling every handoff while the
- // next coordinator's campaign waits it out. try_lead observes
- // `cancel` internally and returns promptly on shutdown.
- match self.try_lead(cancel.clone()).await {
- Ok(true) => tracing::info!(name = %self.config.name, "leadership ended normally"),
+ // Campaign only into an opening: a campaign costs etcd
+ // writes whether or not it wins, and every standby pays it.
+ let attempt = match self.await_election_opening(&cancel).await {
+ Ok(()) if cancel.is_cancelled() => return,
+ // Awaited to completion, never raced: dropping try_lead
+ // mid-cleanup would strand the election lease until TTL
+ // expiry. It observes `cancel` internally.
+ Ok(()) => self.try_lead(cancel.clone()).await,
+ // Not a failed term — this candidate held nothing — so
+ // no ending pace and no run-failure sample; it retries
+ // at the poll cadence, which is the load a healthy
+ // standby already costs. Shutdown first: exit teardown
+ // errors here before losing the race against `cancel`,
+ // and counting that would put a sample on every
+ // rollout.
+ Err(_) if cancel.is_cancelled() => return,
+ Err(e) => {
+ counter!("personhog_coordination_election_observation_failures_total")
+ .increment(1);
+ let wait = jittered(self.config.standby_poll_interval, &self.config.name);
+ tracing::warn!(
+ name = %self.config.name,
+ error = %e,
+ wait = ?wait,
+ "could not observe the election; retrying"
+ );
+ if self.wait_or_shutdown(&cancel, wait).await {
+ return;
+ }
+ continue;
+ }
+ };
+ match attempt {
+ Ok(true) => {
+ tracing::info!(name = %self.config.name, "leadership ended normally");
+ }
Ok(false) => {}
+ Err(e) if e.is_leadership_lost() => {
+ tracing::info!(name = %self.config.name, "abdicated; a successor takes over");
+ // Counted so a lease that cannot renew is visible as
+ // the flap it is.
+ counter!("personhog_coordination_abdications_total").increment(1);
+ // Paced like any other bad ending: try_lead revoked
+ // on the way out, so an unpaced retry flaps forever
+ // with no term long enough to move a handoff.
+ let wait = self.pace_after_ending(&mut consecutive_endings, &mut last_ending);
+ if self.wait_or_shutdown(&cancel, wait).await {
+ return;
+ }
+ }
Err(e) => {
- tracing::warn!(name = %self.config.name, error = %e, "leader loop ended with error")
+ let wait = self.pace_after_ending(&mut consecutive_endings, &mut last_ending);
+ util::record_run_failure(
+ "coordinator",
+ &self.config.name,
+ consecutive_endings,
+ &e,
+ );
+ if self.wait_or_shutdown(&cancel, wait).await {
+ return;
+ }
}
}
- tokio::select! {
+ }
+ }
+
+ /// This candidate's own [`pace_after_ending`], which carries the
+ /// contract and the invariant.
+ fn pace_after_ending(&self, consecutive: &mut u32, last: &mut Option<Instant>) -> Duration {
+ pace_after_ending(&self.config, consecutive, last)
+ }
+
+ /// Wait, or report that shutdown arrived first.
+ async fn wait_or_shutdown(&self, cancel: &CancellationToken, delay: Duration) -> bool {
+ tokio::select! {
+ _ = cancel.cancelled() => true,
+ _ = tokio::time::sleep(delay) => false,
+ }
+ }
+
+ /// Give up the election lease, bounded: unbounded, this cleanup
+ /// waits out the very etcd outage that usually runs it, holding
+ /// shutdown past the charts' grace. The lease expires on its TTL
+ /// regardless.
+ async fn revoke_election_lease(&self, lease_id: i64) -> Result<()> {
+ tokio::time::timeout(REVOKE_TIMEOUT, self.store.revoke_lease(lease_id))
+ .await
+ .unwrap_or_else(|_| {
+ tracing::warn!(
+ name = %self.config.name,
+ lease_id,
+ "election lease revoke timed out; it expires on its TTL"
+ );
+ Ok(())
+ })
+ }
+
+ /// Block until this candidate has something to campaign for: no
+ /// leader is recorded, or the one that is recorded goes away.
+ /// Returns immediately on cancellation.
+ ///
+ /// Standing by costs one read and one idle watch per fallback
+ /// interval, in place of a campaign per retry interval. The
+ /// fallback re-read bounds the leaderless window whether the watch
+ /// stalls or is lost, and a lost watch waits out its window before
+ /// re-creating, so no failure mode costs more than the healthy
+ /// cadence.
+ pub async fn await_election_opening(&self, cancel: &CancellationToken) -> Result<()> {
+ loop {
+ // The revision this read returns anchors the watch, so a
+ // leader that vanishes before the watch attaches is still
+ // delivered. Both etcd calls race cancellation: unbounded,
+ // each would outlive the shutdown budget against a dark
+ // etcd.
+ let read = tokio::select! {
_ = cancel.cancelled() => return Ok(()),
- _ = tokio::time::sleep(self.config.election_retry_interval) => {}
+ read = self.store.get_leader_with_revision() => read,
+ };
+ let (leader, revision) = read?;
+ let Some(leader) = leader else {
+ return Ok(());
+ };
+ tracing::debug!(
+ name = %self.config.name,
+ leader = %leader.holder,
+ "another coordinator is leader, standing by"
+ );
+
+ let stream = tokio::select! {
+ _ = cancel.cancelled() => return Ok(()),
+ stream = self.store.watch_leader_from(revision + 1) => stream,
+ };
+ let mut stream = stream?;
+ // A deadline for the whole wait: per-message construction
+ // would restart it on every response and bound nothing.
+ let fallback_at = tokio::time::Instant::now() + self.config.standby_poll_interval;
+ let woke = loop {
+ let message = tokio::select! {
+ _ = cancel.cancelled() => return Ok(()),
+ _ = tokio::time::sleep_until(fallback_at) => break Woke::Fallback,
+ message = stream.message() => message,
+ };
+ // A stream that ends or errors leaves this candidate
+ // blind, so re-read rather than trusting it further.
+ let response = match message {
+ Ok(Some(response)) => response,
+ Ok(None) => {
+ tracing::debug!(
+ name = %self.config.name,
+ "leader watch stream ended; re-reading"
+ );
+ break Woke::StreamLost;
+ }
+ Err(e) => {
+ tracing::debug!(
+ name = %self.config.name,
+ error = %e,
+ "leader watch stream failed; re-reading"
+ );
+ break Woke::StreamLost;
+ }
+ };
+ // etcd cancels a watcher with an ordinary response and
+ // delivers nothing after it; awaiting further would
+ // look idle rather than blind.
+ if response.canceled() {
+ tracing::debug!(
+ name = %self.config.name,
+ reason = response.cancel_reason(),
+ compact_revision = response.compact_revision(),
+ "leader watch cancelled by etcd; re-reading"
+ );
+ break Woke::StreamLost;
+ }
+ if response
+ .events()
+ .iter()
+ .any(|event| event.event_type() == EventType::Delete)
+ {
+ break Woke::Opened;
+ }
+ };
+ match woke {
+ Woke::Opened => return Ok(()),
+ // The fallback re-read: loop to a fresh look and a
+ // fresh watch.
+ Woke::Fallback => {}
+ Woke::StreamLost => {
+ // Shutdown first, as at the run-level arm: exit
+ // teardown errors the stream before the cancel race
+ // resolves, and counting it would sample every
+ // rollout.
+ if cancel.is_cancelled() {
+ return Ok(());
+ }
+ // Counted: without a series, a flapping etcd is
+ // indistinguishable from a healthy fleet.
+ counter!("personhog_coordination_election_watch_interruptions_total")
+ .increment(1);
+ // Wait out the window before re-creating, so a
+ // flapping watcher costs the healthy cadence — one
+ // read and one create per interval — and never more.
+ tokio::select! {
+ _ = cancel.cancelled() => return Ok(()),
+ _ = tokio::time::sleep_until(fallback_at) => {}
+ }
+ }
}
}
}
@@ -181,18 +510,37 @@ 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> {
+ // Every campaign costs etcd a lease grant, a transaction and,
+ // when it loses, a revoke. Against wins, this is what says
+ // whether the fleet is electing or merely polling.
+ counter!("personhog_coordination_election_campaigns_total").increment(1);
let granted_at = Instant::now();
- let lease_id = self.store.grant_lease(self.config.leader_lease_ttl).await?;
+ // Both campaign calls race cancellation, or a hanging etcd
+ // holds shutdown past the graceful budget. A grant abandoned
+ // mid-flight leaves a lease nothing hangs off; it expires on
+ // its TTL.
+ let lease_id = tokio::select! {
+ _ = cancel.cancelled() => return Ok(false),
+ granted = self.store.grant_lease(self.config.leader_lease_ttl) => granted?,
+ };
- let acquired = match self
- .store
- .try_acquire_leadership(&self.config.name, lease_id)
- .await
- {
- Ok(acquired) => acquired,
- Err(e) => {
- drop(self.store.revoke_lease(lease_id).await);
- return Err(e);
+ let acquired = tokio::select! {
+ // The CAS may still land server-side after this arm wins;
+ // the revoke tears the lease down, and the key is
+ // lease-bound, so either way nothing outlives shutdown
+ // longer than the TTL.
+ _ = cancel.cancelled() => {
+ drop(self.revoke_election_lease(lease_id).await);
+ return Ok(false);
+ }
+ acquired = self.store.try_acquire_leadership(&self.config.name, lease_id) => {
+ match acquired {
+ Ok(acquired) => acquired,
+ Err(e) => {
+ drop(self.revoke_election_lease(lease_id).await);
+ return Err(e);
+ }
+ }
}
};
@@ -200,7 +548,7 @@ impl Coordinator {
tracing::debug!(name = %self.config.name, "another coordinator is leader, standing by");
// Nothing hangs off the lease; revoke it rather than leaking
// one lease per election retry from every standby candidate.
- drop(self.store.revoke_lease(lease_id).await);
+ drop(self.revoke_election_lease(lease_id).await);
return Ok(false);
}
@@ -255,6 +603,14 @@ impl Coordinator {
};
let result = tokio::select! {
+ // Raced here as well: the loop's bootstrap is a run of
+ // unbounded store calls before its first select, and the
+ // keepalive cannot preempt them on a graceful exit (its
+ // token is a child of `cancel`, so `lease_lost` never
+ // fires). Dropping the loop mid-bootstrap is safe — every
+ // downstream effect is idempotent — and the teardown below
+ // still runs, which is what spares the successor the TTL.
+ _ = cancel.cancelled() => Ok(()),
_ = lease_lost.cancelled() => Err(Error::leadership_lost()),
result = self.run_coordination_loop(cancel.clone()) => result,
};
@@ -265,7 +621,7 @@ impl Coordinator {
// Revoke so the next candidate's campaign wins immediately instead
// of waiting out the lease TTL.
- drop(self.store.revoke_lease(lease_id).await);
+ drop(self.revoke_election_lease(lease_id).await);
reset_coordinator_gauges();
@@ -273,15 +629,10 @@ impl Coordinator {
}
async fn run_coordination_loop(&self, cancel: CancellationToken) -> Result<()> {
- // Anchor every watch to a single revision taken BEFORE bootstrap.
- // The coordinator must observe ack writes (PodDrainedAck,
- // PodWarmedAck, RouterFreezeAck) to advance handoffs; anchoring
- // guarantees that any event from this revision on is delivered
- // even if it lands before a watch finishes attaching, so nothing
- // written during (or racing) bootstrap can be missed. Bootstrap
- // reads happen after this point and may double-observe events the
- // watches also deliver — all downstream work is idempotent
- // (CAS-guarded phase transitions, tolerant cleanup).
+ // Anchor every watch to one revision taken BEFORE bootstrap, so
+ // an ack written while a watch is still attaching is delivered
+ // rather than missed. Bootstrap reads may double-observe what
+ // the watches also deliver; all downstream work is idempotent.
let anchor = self.store.current_revision().await? + 1;
let pods_stream = self.store.watch_pods_from(anchor).await?;
let handoffs_stream = self.store.watch_handoffs_from(anchor).await?;
@@ -424,7 +775,7 @@ impl Coordinator {
_ = cancel.cancelled() => return Ok(()),
_ = replan.notified() => {}
msg = stream.message() => {
- let resp = msg?.ok_or_else(|| Error::invalid_state("pod watch stream ended".to_string()))?;
+ let resp = util::live_watch_response(msg?, "pod")?;
Self::log_pod_events(&resp);
}
}
@@ -436,7 +787,7 @@ impl Coordinator {
_ = cancel.cancelled() => return Ok(()),
_ = tokio::time::sleep_until(deadline) => break,
msg = stream.message() => {
- let resp = msg?.ok_or_else(|| Error::invalid_state("pod watch stream ended".to_string()))?;
+ let resp = util::live_watch_response(msg?, "pod")?;
Self::log_pod_events(&resp);
}
}
@@ -473,7 +824,7 @@ impl Coordinator {
tokio::select! {
_ = cancel.cancelled() => return Ok(()),
msg = stream.message() => {
- let resp = msg?.ok_or_else(|| Error::invalid_state("handoff watch stream ended".to_string()))?;
+ let resp = util::live_watch_response(msg?, "handoff")?;
for event in resp.events() {
if event.event_type() == EventType::Put {
match parse_watch_value::<HandoffState>(event) {
@@ -526,7 +877,7 @@ impl Coordinator {
tokio::select! {
_ = cancel.cancelled() => return Ok(()),
msg = stream.message() => {
- let resp = msg?.ok_or_else(|| Error::invalid_state(format!("{kind} ack watch stream ended")))?;
+ let resp = util::live_watch_response(msg?, kind)?;
for event in resp.events() {
if event.event_type() == EventType::Put {
let partition = event.kv().and_then(|kv| {
@@ -544,15 +895,10 @@ impl Coordinator {
}
}
- /// React to router departures. The freeze quorum's required set is
- /// the handoff's creation snapshot intersected with the live
- /// registry, so a router leaving — deregistering at shutdown, or its
- /// lease expiring after a crash — can newly satisfy the quorum of
- /// every in-flight freeze. Nothing else fires an event for that:
- /// without this watch, such handoffs wait for the reconcile tick.
- /// Registrations (Put events) are ignored — a router that joins
- /// after a handoff's creation is never added to its quorum, so a Put
- /// can't change any evaluation.
+ /// React to router departures, which can newly satisfy every
+ /// in-flight freeze's quorum and fire no other event. Puts are
+ /// ignored: a router joining after a handoff's creation never
+ /// enters its quorum.
async fn run_router_departure_watch(
mut stream: WatchStream,
store: &PersonhogStore,
@@ -562,9 +908,7 @@ impl Coordinator {
tokio::select! {
_ = cancel.cancelled() => return Ok(()),
msg = stream.message() => {
- let resp = msg?.ok_or_else(|| {
- Error::invalid_state("router watch stream ended".to_string())
- })?;
+ let resp = util::live_watch_response(msg?, "router")?;
let departed = resp
.events()
.iter()
@@ -592,14 +936,25 @@ impl Coordinator {
cancel: CancellationToken,
) -> Result<()> {
let mut tick = tokio::time::interval(interval);
+ // As the pod's and router's passes do. The default replays every
+ // missed tick back to back, which would fire this body's read
+ // fan-out — one pass per in-flight handoff — in a tight loop
+ // exactly when etcd is too slow to have kept up with it.
+ tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
tokio::select! {
_ = cancel.cancelled() => return Ok(()),
_ = tick.tick() => {
+ // INVARIANT: listed before the handoffs — a
+ // membership written after this read is not a
+ // candidate, so the sweep cannot collect a record a
+ // newer handoff refers to.
+ let quorum_candidates = store.list_freeze_quorum_ids().await;
let handoffs = store.list_handoffs().await?;
for handoff in &handoffs {
Self::handle_handoff_update_static(&store, handoff).await?;
- Self::check_phase_advance(&store, handoff.partition, AdvanceTrigger::Other).await?;
+ Self::check_phase_advance(&store, handoff.partition, AdvanceTrigger::Other)
+ .await?;
}
// Advancement first, planning second: a handoff that
// can still progress gets every chance to before the
@@ -629,6 +984,71 @@ impl Coordinator {
tracing::debug!(error = %e, "skipping cluster gauge refresh");
}
}
+ // Last, with the gauge refresh, because it is
+ // housekeeping by the same standard: only its two
+ // reads above need their order, while its deletes
+ // are a round trip per orphan that a read-only etcd
+ // would otherwise charge ahead of every handoff and
+ // the planner wake.
+ Self::collect_stale_freeze_quorums(&store, quorum_candidates, &handoffs).await;
+ }
+ }
+ }
+ }
+
+ /// Delete the freeze-quorum records no live handoff refers to.
+ /// Housekeeping without a transaction: a record left behind costs
+ /// kilobytes until the next tick, and one deleted in error only
+ /// makes its handoff fall back to requiring every live router —
+ /// neither can advance a handoff early. A wrong delete surfaces in
+ /// `unresolved_freeze_quorums_total` only from a process that has
+ /// to read; a cached coordinator neutralizes it silently.
+ async fn collect_stale_freeze_quorums(
+ store: &PersonhogStore,
+ candidates: Result<Vec<String>>,
+ handoffs: &[HandoffState],
+ ) {
+ let candidates = match candidates {
+ Ok(ids) => ids,
+ Err(e) => {
+ // Counted: a sweep that never runs is otherwise
+ // indistinguishable from one with nothing to collect.
+ counter!(
+ "personhog_coordination_freeze_quorum_sweep_failures_total",
+ "stage" => "list"
+ )
+ .increment(1);
+ tracing::debug!(error = %e, "skipping freeze quorum sweep");
+ return;
+ }
+ };
+ let referenced: HashSet<&str> = handoffs
+ .iter()
+ .filter_map(|h| h.freeze_quorum_ref.as_deref())
+ .collect();
+ for id in candidates
+ .iter()
+ .filter(|id| !referenced.contains(id.as_str()))
+ {
+ match store.delete_freeze_quorum(id).await {
+ Ok(()) => {
+ // The cheap half of the sweep's observability: a
+ // rate here that outpaces plan creation is the shape
+ // a sweep collecting records it should have spared
+ // would take.
+ counter!("personhog_coordination_freeze_quorums_collected_total").increment(1);
+ tracing::debug!(quorum_id = %id, "collected unreferenced freeze quorum");
+ }
+ Err(e) => {
+ // Counted, not only logged: the router runs at INFO,
+ // so a sweep whose every delete fails is otherwise
+ // silent while its backlog grows one record per plan.
+ counter!(
+ "personhog_coordination_freeze_quorum_sweep_failures_total",
+ "stage" => "delete"
+ )
+ .increment(1);
+ tracing::debug!(quorum_id = %id, error = %e, "freeze quorum sweep failed")
}
}
}
@@ -661,10 +1081,11 @@ impl Coordinator {
HandoffPhase::Freezing => {
let routers = store.list_routers().await?;
let freeze_acks = store.list_freeze_acks(partition).await?;
+ let quorum = store.resolve_freeze_quorum(&handoff).await?;
// Quorum semantics live in `protocol::freeze_quorum_met`
// (shared with the stateright model).
- if freeze_quorum_met(&routers, &freeze_acks, &handoff) {
+ if freeze_quorum_met(&routers, &freeze_acks, &handoff, quorum.as_deref()) {
// Initial assignments (no old owner) skip Draining
// entirely — there's no inflight to wait for. Advance
// straight to Warming.
@@ -705,8 +1126,12 @@ impl Coordinator {
tracing::info!(
partition,
handoff_id = %handoff.handoff_id,
- missing_freeze_ackers =
- ?missing_freeze_ackers(&routers, &freeze_acks, &handoff),
+ missing_freeze_ackers = ?missing_freeze_ackers(
+ &routers,
+ &freeze_acks,
+ &handoff,
+ quorum.as_deref()
+ ),
"freeze quorum not yet met"
);
}
@@ -903,6 +1328,10 @@ impl Coordinator {
// come and go (see `HandoffState::freeze_quorum`).
let routers = store.list_routers().await?;
let freeze_quorum: Vec<String> = routers.iter().map(|r| r.router_name.clone()).collect();
+ // One record for the whole plan: the membership is the same for
+ // every handoff it creates, and inlining it per handoff is what
+ // made a large plan exceed etcd's maximum request size.
+ let freeze_quorum_id = util::new_handoff_id();
let now = util::now_seconds();
let handoff_objects: Vec<HandoffState> = plan
@@ -919,7 +1348,8 @@ impl Coordinator {
phase: HandoffPhase::Freezing,
started_at: now,
handoff_id: util::new_handoff_id(),
- freeze_quorum: Some(freeze_quorum.clone()),
+ freeze_quorum: None,
+ freeze_quorum_ref: Some(freeze_quorum_id.clone()),
created_at_ms: now_ms,
phase_entered_at_ms: now_ms,
})
@@ -945,14 +1375,24 @@ impl Coordinator {
.collect();
let mut creations: Vec<HandoffState> = Vec::new();
let mut replacements: Vec<HandoffReplacement> = Vec::new();
- let mut fallback_deletes: Vec<(HandoffState, i64)> = Vec::new();
+ let mut fallback_deletes: Vec<FallbackDelete> = Vec::new();
let mut replaced_dispositions: Vec<&'static str> = Vec::new();
+ // Held until the plan transaction lands; see `Cancellation`.
+ let mut planned_cancellations: Vec<Cancellation> = Vec::new();
for handoff in handoff_objects {
match cancelled_by_partition.remove(&handoff.partition) {
Some((predecessor, mod_revision)) => {
- Self::log_cancellation(store, &routers, &predecessor, &registered, "successor")
- .await;
+ planned_cancellations.push(
+ Self::describe_cancellation(
+ store,
+ &routers,
+ &predecessor,
+ &registered,
+ "successor",
+ )
+ .await,
+ );
replacements.push(HandoffReplacement {
handoff,
expected_mod_revision: mod_revision,
@@ -968,8 +1408,16 @@ impl Coordinator {
.filter(|owner| registered.contains(owner.as_str()));
match owner {
Some(owner) => {
- Self::log_cancellation(store, &routers, &predecessor, &registered, "reaffirm")
- .await;
+ planned_cancellations.push(
+ Self::describe_cancellation(
+ store,
+ &routers,
+ &predecessor,
+ &registered,
+ "reaffirm",
+ )
+ .await,
+ );
replacements.push(HandoffReplacement {
handoff: HandoffState {
partition: predecessor.partition,
@@ -982,7 +1430,12 @@ impl Coordinator {
phase: HandoffPhase::Complete,
started_at: now,
handoff_id: util::new_handoff_id(),
+ // A reaffirm requires no acks at all, which
+ // an empty membership states directly — no
+ // record to resolve, and never the legacy
+ // fallback.
freeze_quorum: Some(Vec::new()),
+ freeze_quorum_ref: None,
created_at_ms: now_ms,
phase_entered_at_ms: now_ms,
},
@@ -991,9 +1444,19 @@ impl Coordinator {
replaced_dispositions.push("reaffirm");
}
None => {
- Self::log_cancellation(store, &routers, &predecessor, &registered, "delete")
- .await;
- fallback_deletes.push((predecessor, mod_revision));
+ let cancellation = Self::describe_cancellation(
+ store,
+ &routers,
+ &predecessor,
+ &registered,
+ "delete",
+ )
+ .await;
+ fallback_deletes.push(FallbackDelete {
+ predecessor,
+ mod_revision,
+ cancellation,
+ });
}
}
}
@@ -1035,9 +1498,25 @@ impl Coordinator {
})
.collect();
+ let references_quorum = creations
+ .iter()
+ .chain(replacements.iter().map(|r| &r.handoff))
+ .any(|handoff| handoff.freeze_quorum_ref.is_some());
if (!creations.is_empty() || !replacements.is_empty())
&& !store
- .apply_plan(&[], &creations, &replacements, &preconditions)
+ .apply_plan(
+ &[],
+ &creations,
+ &replacements,
+ &preconditions,
+ // A plan whose cancellations all resolve to reaffirms
+ // creates no handoff that refers to a membership, and
+ // that is the common shape when a wedged freeze had
+ // sound placement. Writing one anyway leaves a record
+ // for the next sweep to delete, during the mass
+ // cancellation when etcd is least well.
+ references_quorum.then_some((&freeze_quorum_id, &freeze_quorum)),
+ )
.await?
{
// A concurrent invocation (the empty-set re-trigger racing a
@@ -1061,6 +1540,9 @@ impl Coordinator {
"handoff created"
);
}
+ for cancellation in &planned_cancellations {
+ cancellation.record();
+ }
for disposition in &replaced_dispositions {
counter!(
"personhog_coordination_handoffs_replaced_total",
@@ -1074,11 +1556,15 @@ impl Coordinator {
// its own, which is what the safety argument needs, and a stale
// guard only ever skips a cancel for a record that changed under
// us.
- for (predecessor, mod_revision) in fallback_deletes {
+ for delete in fallback_deletes {
if store
- .delete_handoff_and_acks_if_unchanged(predecessor.partition, mod_revision)
+ .delete_handoff_and_acks_if_unchanged(
+ delete.predecessor.partition,
+ delete.mod_revision,
+ )
.await?
{
+ delete.cancellation.record();
counter!(
"personhog_coordination_handoffs_replaced_total",
"disposition" => "delete",
@@ -1113,23 +1599,36 @@ impl Coordinator {
/// one specific non-acking router, and naming it turns the diagnosis
/// into reading a label. Attribution is best-effort; a failed ack
/// read must not block the replacement.
- async fn log_cancellation(
+ /// Describe a cancellation and log the intent, returning what to
+ /// count once it has actually happened.
+ async fn describe_cancellation(
store: &PersonhogStore,
routers: &[RegisteredRouter],
predecessor: &HandoffState,
registered: &HashSet<&str>,
disposition: &'static str,
- ) {
+ ) -> Cancellation {
let reason = if registered.contains(predecessor.new_owner.as_str()) {
"phase_deadline"
} else {
"dead_new_owner"
};
+ // Attribution only. A read that fails here must not be turned
+ // into an answer: `None` means "no membership recorded", which
+ // widens the requirement to every live router, so a transient
+ // error would name every one of them as a blocker — during the
+ // mass cancellation when etcd is least well and the accusation
+ // is least true.
let missing_ackers = if predecessor.phase == HandoffPhase::Freezing {
- match store.list_freeze_acks(predecessor.partition).await {
- Ok(acks) => missing_freeze_ackers(routers, &acks, predecessor),
- Err(e) => {
- tracing::warn!(error = %e, "could not read freeze acks for attribution");
+ match (
+ store.resolve_freeze_quorum(predecessor).await,
+ store.list_freeze_acks(predecessor.partition).await,
+ ) {
+ (Ok(quorum), Ok(acks)) => {
+ missing_freeze_ackers(routers, &acks, predecessor, quorum.as_deref())
+ }
+ (Err(e), _) | (_, Err(e)) => {
+ tracing::warn!(error = %e, "could not attribute the missing freeze acks");
Vec::new()
}
}
@@ -1146,17 +1645,9 @@ impl Coordinator {
missing_freeze_ackers = ?missing_ackers,
"cancelling handoff by replacement"
);
- counter!(
- "personhog_coordination_handoffs_cancelled_total",
- "reason" => reason,
- )
- .increment(1);
- for router in &missing_ackers {
- counter!(
- "personhog_coordination_freeze_ack_missing_total",
- "router" => router.clone(),
- )
- .increment(1);
+ Cancellation {
+ reason,
+ missing_ackers,
}
}
@@ -1537,6 +2028,110 @@ fn base_policy(status: PodStatus) -> Option<PlacementPolicy> {
mod tests {
use super::*;
+ fn paced_config(name: &str) -> CoordinatorConfig {
+ CoordinatorConfig {
+ name: name.to_string(),
+ leader_lease_ttl: 5,
+ run_retry_backoff: Duration::from_millis(500),
+ backoff_decay_window: Duration::from_secs(300),
+ ..CoordinatorConfig::default()
+ }
+ }
+
+ /// The pace must never delay a campaign longer than the lease TTL it
+ /// sits inside. A term that ended released the election, so this wait
+ /// holds up a succession that is already open — past the TTL a paced
+ /// candidate is slower to take a free election than it would have
+ /// been to wait out a crashed leader's lease.
+ #[test]
+ fn the_pace_never_exceeds_the_lease_ttl_it_delays() {
+ let config = paced_config("coordinator-0");
+ let mut consecutive = 0;
+ let mut last = None;
+ let ttl = Duration::from_secs(config.leader_lease_ttl as u64);
+
+ for ending in 1..=20 {
+ let wait = pace_after_ending(&config, &mut consecutive, &mut last);
+ assert!(
+ wait <= ttl,
+ "ending {ending} paced {wait:?}, past the {ttl:?} lease TTL"
+ );
+ }
+ }
+
+ /// It still has to grow, or it is not a pace at all: a coordinator
+ /// that keeps failing would campaign as fast as it can against an
+ /// etcd that is already unwell.
+ #[test]
+ fn the_pace_grows_while_endings_keep_arriving() {
+ let config = paced_config("coordinator-0");
+ let mut consecutive = 0;
+ let mut last = None;
+
+ let first = pace_after_ending(&config, &mut consecutive, &mut last);
+ let second = pace_after_ending(&config, &mut consecutive, &mut last);
+ assert!(
+ second > first,
+ "a second ending inside the decay window must pace harder than the first"
+ );
+ }
+
+ /// And it has to start over once the endings stop, or a bad spell in
+ /// the morning leaves every candidate at the cap that evening.
+ #[test]
+ fn a_quiet_window_starts_the_pace_over() {
+ // A window the test can actually wait out, rather than rewinding
+ // `last` by subtracting from `Instant::now()` — that subtraction
+ // panics on a host whose monotonic clock is younger than the
+ // window, which a fresh CI VM's is.
+ let config = CoordinatorConfig {
+ backoff_decay_window: Duration::from_millis(5),
+ ..paced_config("coordinator-0")
+ };
+ let mut consecutive = 0;
+ let mut last = None;
+
+ let first = pace_after_ending(&config, &mut consecutive, &mut last);
+ pace_after_ending(&config, &mut consecutive, &mut last);
+ // An ending older than the decay window is the same evidence as
+ // never having had one.
+ std::thread::sleep(config.backoff_decay_window);
+ let after_quiet = pace_after_ending(&config, &mut consecutive, &mut last);
+
+ assert_eq!(
+ after_quiet, first,
+ "an ending after a quiet window must cost the base pace again"
+ );
+ }
+
+ /// Candidates fail together — one etcd slowdown ends every term at
+ /// once — so an unjittered pace walks the whole fleet up the same
+ /// ladder and fires their campaigns in the same instant, against an
+ /// etcd that has just recovered.
+ #[test]
+ fn candidates_pace_differently_from_one_another() {
+ let waits: HashSet<Duration> = ["router-0", "router-1", "router-2", "router-3"]
+ .iter()
+ .map(|name| {
+ let config = paced_config(name);
+ let (mut consecutive, mut last) = (0, None);
+ // Third ending: far enough up the ladder that the offset
+ // is a meaningful share of the wait.
+ for _ in 0..3 {
+ pace_after_ending(&config, &mut consecutive, &mut last);
+ }
+ pace_after_ending(&config, &mut consecutive, &mut last)
+ })
+ .collect();
+
+ assert_eq!(
+ waits.len(),
+ 4,
+ "every candidate at the same ladder position must wait a distinct time; \
+ two of four differing would still let most of the fleet campaign in lockstep"
+ );
+ }
+
fn make_pod(name: &str) -> RegisteredPod {
RegisteredPod {
pod_name: name.to_string(),
diff --git a/rust/personhog-coordination/src/error.rs b/rust/personhog-coordination/src/error.rs
index 4deaa1d46e14..6c1198cd838a 100644
--- a/rust/personhog-coordination/src/error.rs
+++ b/rust/personhog-coordination/src/error.rs
@@ -34,6 +34,16 @@ impl Error {
pub fn leadership_lost() -> Self {
Self::Store(assignment_coordination::error::Error::LeadershipLost)
}
+
+ /// Whether losing the election lease is what ended this term. An
+ /// abdication is the protocol working — a successor takes over and
+ /// reconciles — so it is not evidence that this process is unhealthy.
+ pub fn is_leadership_lost(&self) -> bool {
+ matches!(
+ self,
+ Self::Store(assignment_coordination::error::Error::LeadershipLost)
+ )
+ }
}
pub type Result<T> = std::result::Result<T, Error>;
diff --git a/rust/personhog-coordination/src/pod.rs b/rust/personhog-coordination/src/pod.rs
index 8d2dc10e00f0..2629d623ddd8 100644
--- a/rust/personhog-coordination/src/pod.rs
+++ b/rust/personhog-coordination/src/pod.rs
@@ -2,7 +2,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::sync::{Arc, Mutex as StdMutex};
use std::time::{Duration, Instant};
use async_trait::async_trait;
@@ -10,7 +10,7 @@ use etcd_client::{EventType, WatchStream};
use futures::future::BoxFuture;
use futures::stream::{FuturesUnordered, StreamExt};
use metrics::{counter, gauge, histogram};
-use tokio::sync::{Mutex, Notify, Semaphore, SemaphorePermit};
+use tokio::sync::{Notify, Semaphore, SemaphorePermit};
use tokio::task::JoinError;
use tokio_util::sync::CancellationToken;
@@ -222,6 +222,26 @@ pub struct PodConfig {
pub warm_concurrency: usize,
}
+/// How long either exit path waits for its lease revoke before moving
+/// on: unbounded, it waits out the very etcd outage that usually runs
+/// it, while the registration expires by TTL anyway. Public because the
+/// leader binary validates its shutdown budget against it at startup.
+pub const REVOKE_TIMEOUT: Duration = Duration::from_secs(5);
+
+/// The fence's drain bound on the shutdown path: its value there is
+/// stopping admissions and a short straggler grace — anything the
+/// graceful drain ahead of it could not quiesce will not quiesce now.
+/// Public because the leader binary sums it into its budget check.
+pub const SHUTDOWN_FENCE_BOUND: Duration = Duration::from_secs(3);
+
+/// How long the drain's bookkeeping (Draining write, involvement
+/// snapshot, watch creation) may take before degrading to the
+/// fence-and-revoke teardown. These run before the drain's own timeout
+/// starts, and an etcd whose KV path stalls while its lease path stays
+/// healthy would otherwise hold shutdown here indefinitely. Public
+/// because the leader binary sums it into its budget check.
+pub const DRAIN_SETUP_BOUND: Duration = Duration::from_secs(5);
+
impl Default for PodConfig {
fn default() -> Self {
Self {
@@ -261,15 +281,21 @@ pub struct PodHandle {
store: Arc<PersonhogStore>,
config: PodConfig,
handler: Arc<dyn HandoffHandler>,
- /// Partitions warmed by this process — local, dies with the process —
- /// each with the provenance of its warm. `converge` consults it to
- /// decide whether a Serving/Acquiring partition still needs a warm,
- /// and `drain()` waits for it to empty.
- warmed_partitions: Mutex<HashMap<u32, WarmProvenance>>,
+ /// Partitions warmed by this process — local, dies with the process
+ /// — each with the provenance of its warm.
+ ///
+ /// A std mutex on purpose, for both maps: an async lock leaves a
+ /// suspension point between the warm installing in the data plane
+ /// and the insert recording it, and a lane dropped there leaves a
+ /// warm the self-fence cannot see. Guards held across an await are
+ /// a compile error (`run` is spawned, the guard is not `Send`) and
+ /// a clippy lint besides.
+ warmed_partitions: StdMutex<HashMap<u32, WarmProvenance>>,
/// Partitions this process has write-fenced via a drain — local,
/// consulted so convergence to Serving only issues a resume when a
- /// fence actually exists.
- fenced_partitions: Mutex<HashSet<u32>>,
+ /// fence actually exists. See `warmed_partitions` for why the lock
+ /// is synchronous.
+ fenced_partitions: StdMutex<HashSet<u32>>,
/// Signalled when a partition is released, waking `drain()` without polling.
drain_notify: Notify,
/// Bounds concurrent `warm_partition` calls to `warm_concurrency`.
@@ -314,8 +340,8 @@ impl PodHandle {
store,
config,
handler,
- warmed_partitions: Mutex::new(HashMap::new()),
- fenced_partitions: Mutex::new(HashSet::new()),
+ warmed_partitions: StdMutex::new(HashMap::new()),
+ fenced_partitions: StdMutex::new(HashSet::new()),
drain_notify: Notify::new(),
warm_slots,
fence_poisoned: AtomicBool::new(false),
@@ -371,14 +397,18 @@ impl PodHandle {
/// 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<()> {
+ util::preregister_pod_metrics();
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,
+ // Cancel-aware internally — see `begin_session` for why the
+ // race lives inside the call rather than around it.
+ let (lease_id, granted_at) = match self.begin_session(&cancel).await {
+ Ok(None) => return Ok(()),
+ Ok(Some(session)) => session,
Err(e) => {
if cancel.is_cancelled() {
return Ok(());
@@ -572,7 +602,7 @@ impl PodHandle {
// 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)
+ SHUTDOWN_FENCE_BOUND.min(self.config.drain_timeout)
} else {
self.config.drain_timeout
};
@@ -596,7 +626,11 @@ impl PodHandle {
drop(registration_watch.await);
heartbeat_cancel.cancel();
drop(heartbeat_handle.await);
- drop(self.store.revoke_lease(lease_id).await);
+ // Bounded like the lease-loss path's revoke: this path
+ // is on the shutdown clock, and an unbounded revoke
+ // against a hung etcd would spend the termination grace
+ // the drain and fence are budgeted out of.
+ drop(tokio::time::timeout(REVOKE_TIMEOUT, 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
@@ -640,10 +674,7 @@ impl PodHandle {
// being on this branch, and the store has no request
// timeouts of its own — unbounded it could hold up the
// fence or the next session for as long as the outage.
- drop(
- tokio::time::timeout(Duration::from_secs(5), self.store.revoke_lease(lease_id))
- .await,
- );
+ drop(tokio::time::timeout(REVOKE_TIMEOUT, self.store.revoke_lease(lease_id)).await);
}
if let Some(e) = fatal {
@@ -684,16 +715,40 @@ impl PodHandle {
}
/// Grant a fresh lease and register under it — the start of a
- /// coordination session.
- async fn begin_session(&self) -> Result<(i64, Instant)> {
+ /// coordination session. Returns `None` when cancellation arrived
+ /// first.
+ ///
+ /// The race lives inside because the two steps abandon differently:
+ /// an abandoned grant leaves only a lease that expires on its TTL,
+ /// but an abandoned registration can still land — a phantom pod the
+ /// coordinator plans toward — so past the grant, any abandonment
+ /// revokes the lease, which deletes a landed registration or makes
+ /// etcd reject a late one. Only a revoke that itself times out
+ /// leaves the phantom, TTL-bounded; see the README's residual.
+ async fn begin_session(&self, cancel: &CancellationToken) -> Result<Option<(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?;
+ let lease_id = tokio::select! {
+ _ = cancel.cancelled() => return Ok(None),
+ granted = self.store.grant_lease(self.config.lease_ttl) => granted?,
+ };
+ let registered = tokio::select! {
+ _ = cancel.cancelled() => {
+ drop(tokio::time::timeout(REVOKE_TIMEOUT, self.store.revoke_lease(lease_id)).await);
+ return Ok(None);
+ }
+ registered = self.register(lease_id) => registered,
+ };
+ if let Err(e) = registered {
+ // A failed registration may also have half-landed; the same
+ // revoke clears it rather than leaving the lease to its TTL.
+ drop(tokio::time::timeout(REVOKE_TIMEOUT, self.store.revoke_lease(lease_id)).await);
+ return Err(e);
+ }
tracing::info!(pod = %self.config.pod_name, "registered with etcd");
- Ok((lease_id, granted_at))
+ Ok(Some((lease_id, granted_at)))
}
/// See `util::note_run_failure` for the progress-based reset
@@ -769,8 +824,14 @@ impl PodHandle {
/// 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;
+ let warmed = self
+ .warmed_partitions
+ .lock()
+ .expect("warmed partitions lock poisoned");
+ let fenced = self
+ .fenced_partitions
+ .lock()
+ .expect("fenced partitions lock poisoned");
warmed
.keys()
.copied()
@@ -842,14 +903,19 @@ impl PodHandle {
// not. The run is about to end poisoned either way.
continue;
}
- self.warmed_partitions.lock().await.remove(&partition);
- self.fenced_partitions.lock().await.remove(&partition);
+ self.warmed_partitions
+ .lock()
+ .expect("warmed partitions lock poisoned")
+ .remove(&partition);
+ self.fenced_partitions
+ .lock()
+ .expect("fenced partitions lock poisoned")
+ .remove(&partition);
}
// Whatever is left, not zero. A partition whose drain never
// quiesced is still held, and reporting none held would hide it
// at the one moment the count is worth reading.
- gauge!("personhog_coordination_partitions_held")
- .set(self.held_partition_count().await as f64);
+ gauge!("personhog_coordination_partitions_held").set(self.held_partition_count() as f64);
if !failures.is_empty() {
return Err(Error::invalid_state(format!(
"self-fence completed with {} failure(s): {}",
@@ -911,32 +977,49 @@ impl PodHandle {
return Ok(());
}
- self.store
- .update_pod_status(&self.config.pod_name, PodStatus::Draining, lease_id)
- .await?;
+ // The bookkeeping is bounded as one unit: a timeout surfaces as
+ // an error, and a failed drain already degrades to the
+ // fence-and-revoke teardown, which is exactly what a shutdown
+ // stuck on a stalled KV path should do.
+ let setup = async {
+ self.store
+ .update_pod_status(&self.config.pod_name, PodStatus::Draining, lease_id)
+ .await?;
- tracing::info!(
- pod = %self.config.pod_name,
- reason = %reason,
- "set status to Draining, waiting for partition handoffs"
- );
+ tracing::info!(
+ pod = %self.config.pod_name,
+ reason = %reason,
+ "set status to Draining, waiting for partition handoffs"
+ );
+
+ if self.held_partition_count() == 0 {
+ return Ok(None);
+ }
- if self.held_partition_count().await == 0 {
+ // Keep converging during drain so partitions release as the
+ // coordinator completes their handoffs. Reconcile first — a
+ // Complete written while the main loop was winding down would
+ // otherwise be missed — and anchor the fresh watch to the
+ // snapshot's revision.
+ let (initial, snapshot_revision) = self.involved_partitions().await?;
+ let stream = self
+ .store
+ .watch_handoffs_from(snapshot_revision + 1)
+ .await?;
+ Ok::<_, Error>(Some((initial, stream)))
+ };
+ let Some((initial, stream)) = tokio::time::timeout(DRAIN_SETUP_BOUND, setup)
+ .await
+ .map_err(|_| {
+ Error::invalid_state(format!(
+ "drain setup exceeded {DRAIN_SETUP_BOUND:?}; degrading to fence and revoke"
+ ))
+ })??
+ else {
tracing::info!(pod = %self.config.pod_name, "no partitions to drain");
return Ok(());
- }
-
- // Keep converging during drain so partitions release as the
- // coordinator completes their handoffs. Reconcile first — a
- // Complete written while the main loop was winding down would
- // otherwise be missed — and anchor the fresh watch to the
- // snapshot's revision.
+ };
let drain_cancel = CancellationToken::new();
- let (initial, snapshot_revision) = self.involved_partitions().await?;
- let stream = self
- .store
- .watch_handoffs_from(snapshot_revision + 1)
- .await?;
tokio::select! {
r = self.watch_handoff_loop(stream, drain_cancel.clone(), initial, progress) => {
@@ -946,7 +1029,7 @@ impl PodHandle {
tracing::info!(pod = %self.config.pod_name, "all partitions drained successfully");
},
_ = tokio::time::sleep(self.config.drain_timeout) => {
- let remaining = self.held_partition_count().await;
+ let remaining = self.held_partition_count();
tracing::warn!(
pod = %self.config.pod_name,
remaining_partitions = remaining,
@@ -963,9 +1046,15 @@ impl PodHandle {
/// or write-fenced. `drain()` waits for this to reach zero: a fenced
/// partition's outbound handoff is still in flight, and the pod must
/// stay alive to release it at Complete.
- async fn held_partition_count(&self) -> usize {
- let warmed = self.warmed_partitions.lock().await;
- let fenced = self.fenced_partitions.lock().await;
+ fn held_partition_count(&self) -> usize {
+ let warmed = self
+ .warmed_partitions
+ .lock()
+ .expect("warmed partitions lock poisoned");
+ let fenced = self
+ .fenced_partitions
+ .lock()
+ .expect("fenced partitions lock poisoned");
warmed
.keys()
.chain(fenced.iter())
@@ -977,7 +1066,7 @@ impl PodHandle {
/// Woken reactively by `drain_notify` each time a partition is released.
async fn wait_for_drain(&self) {
loop {
- if self.held_partition_count().await == 0 {
+ if self.held_partition_count() == 0 {
return;
}
self.drain_notify.notified().await;
@@ -1011,8 +1100,20 @@ impl PodHandle {
// this pod in still need convergence — that is how a warm or
// fence left over from a departed ownership gets released when
// the Complete event that should have done it was missed.
- partitions.extend(self.warmed_partitions.lock().await.keys().copied());
- partitions.extend(self.fenced_partitions.lock().await.iter().copied());
+ partitions.extend(
+ self.warmed_partitions
+ .lock()
+ .expect("warmed partitions lock poisoned")
+ .keys()
+ .copied(),
+ );
+ partitions.extend(
+ self.fenced_partitions
+ .lock()
+ .expect("fenced partitions lock poisoned")
+ .iter()
+ .copied(),
+ );
tracing::info!(
pod,
@@ -1023,6 +1124,53 @@ impl PodHandle {
Ok((partitions, rev_a.min(rev_h)))
}
+ /// Whether this pod still holds something for the partition: a warm
+ /// cache or a write fence. Local state outlives the durable record
+ /// that created it, which is what makes a pod care about a handoff
+ /// that no longer names it — a cancellation leaves the old owner
+ /// fenced, and only the fence says so.
+ fn holds_local_state(&self, partition: u32) -> bool {
+ if self
+ .warmed_partitions
+ .lock()
+ .expect("warmed partitions lock poisoned")
+ .contains_key(&partition)
+ {
+ return true;
+ }
+ self.fenced_partitions
+ .lock()
+ .expect("fenced partitions lock poisoned")
+ .contains(&partition)
+ }
+}
+
+/// Whether a handoff event concerns the pod that observed it — the
+/// scoping that keeps a fleet-wide rebalance from costing every pod a
+/// convergence (two point reads) on every partition's event.
+///
+/// `handoff` is `None` for a deletion, which carries no owners; only
+/// the pod's own involvement can decide, and must — a cancelled handoff
+/// has to reach the old owner holding its fence and the new owner still
+/// warming. `converging` covers the warm window, where the pod holds
+/// neither cache nor fence yet: dispatching coalesces onto the running
+/// convergence, which re-derives once the warm completes.
+///
+/// Split out so both directions can be pinned: widening this to always
+/// return true costs nothing any convergence test observes.
+fn event_concerns_pod(
+ pod_name: &str,
+ handoff: Option<&HandoffState>,
+ holds_local_state: bool,
+ converging: bool,
+) -> bool {
+ let named = handoff.is_some_and(|h| {
+ h.old_owner.as_deref() == Some(pod_name) || h.new_owner.as_str() == pod_name
+ });
+ named || holds_local_state || converging
+}
+
+impl PodHandle {
/// Re-derive and apply the desired state for one partition from fresh
/// point reads. Every watch event is just a signal to look again —
/// convergence acts on observed durable state, never on remembered
@@ -1083,7 +1231,12 @@ impl PodHandle {
match desired {
DesiredState::Serving => {
- if !self.warmed_partitions.lock().await.contains_key(&partition) {
+ if !self
+ .warmed_partitions
+ .lock()
+ .expect("warmed partitions lock poisoned")
+ .contains_key(&partition)
+ {
tracing::info!(pod, partition, "converging to Serving: warming");
let _warm_slot = self.acquire_warm_slot().await?;
let start = Instant::now();
@@ -1092,7 +1245,7 @@ impl PodHandle {
.record(start.elapsed().as_secs_f64() * 1000.0);
self.warmed_partitions
.lock()
- .await
+ .expect("warmed partitions lock poisoned")
.insert(partition, WarmProvenance::Serving);
did_work = true;
}
@@ -1118,10 +1271,18 @@ impl PodHandle {
// first would leave the data plane fenced with no branch
// left to re-enter — writes rejected forever while the
// convergence reports success.
- if self.fenced_partitions.lock().await.contains(&partition) {
+ if self
+ .fenced_partitions
+ .lock()
+ .expect("fenced partitions lock poisoned")
+ .contains(&partition)
+ {
tracing::info!(pod, partition, "converging to Serving: resuming writes");
self.handler.resume_partition(partition).await?;
- self.fenced_partitions.lock().await.remove(&partition);
+ self.fenced_partitions
+ .lock()
+ .expect("fenced partitions lock poisoned")
+ .remove(&partition);
did_work = true;
}
}
@@ -1132,7 +1293,11 @@ impl PodHandle {
// waits for is meaningful. The produce path awaits Kafka
// delivery before returning, so "no inflight handlers"
// implies "every acked write is durable in Kafka."
- let newly_fencing = !self.fenced_partitions.lock().await.contains(&partition);
+ let newly_fencing = !self
+ .fenced_partitions
+ .lock()
+ .expect("fenced partitions lock poisoned")
+ .contains(&partition);
if newly_fencing {
tracing::info!(pod, partition, "converging to Drained: fencing + draining");
did_work = true;
@@ -1144,7 +1309,10 @@ impl PodHandle {
// later convergence to Serving, seeing no fence recorded,
// would skip the resume that lifts it. Recording early
// only risks a redundant resume, which is a no-op.
- self.fenced_partitions.lock().await.insert(partition);
+ self.fenced_partitions
+ .lock()
+ .expect("fenced partitions lock poisoned")
+ .insert(partition);
let start = Instant::now();
self.handler.drain_partition_inflight(partition).await?;
if newly_fencing {
@@ -1179,20 +1347,28 @@ impl PodHandle {
// replays only from the writer's committed offset, so a
// stale cache below that offset would keep hitting;
// release first and rebuild from clean.
- let valid = self.warmed_partitions.lock().await.get(&partition).is_some_and(
+ let valid = self.warmed_partitions.lock().expect("warmed partitions lock poisoned").get(&partition).is_some_and(
|provenance| {
matches!(provenance, WarmProvenance::Handoff(id) if *id == handoff.handoff_id)
},
);
if !valid {
- if self.warmed_partitions.lock().await.contains_key(&partition) {
+ if self
+ .warmed_partitions
+ .lock()
+ .expect("warmed partitions lock poisoned")
+ .contains_key(&partition)
+ {
tracing::info!(
pod,
partition,
"converging to Acquiring: releasing a warm from an earlier era"
);
self.handler.release_partition(partition).await?;
- self.warmed_partitions.lock().await.remove(&partition);
+ self.warmed_partitions
+ .lock()
+ .expect("warmed partitions lock poisoned")
+ .remove(&partition);
}
tracing::info!(pod, partition, "converging to Acquiring: warming");
let _warm_slot = self.acquire_warm_slot().await?;
@@ -1200,16 +1376,22 @@ impl PodHandle {
self.handler.warm_partition(partition).await?;
histogram!("personhog_coordination_partition_warm_ms", "trigger" => "handoff")
.record(start.elapsed().as_secs_f64() * 1000.0);
- self.warmed_partitions.lock().await.insert(
- partition,
- WarmProvenance::Handoff(handoff.handoff_id.clone()),
- );
+ self.warmed_partitions
+ .lock()
+ .expect("warmed partitions lock poisoned")
+ .insert(
+ partition,
+ WarmProvenance::Handoff(handoff.handoff_id.clone()),
+ );
did_work = true;
}
// The warm above re-admits writes for this partition as
// part of taking ownership, so clearing the record here
// matches the data plane rather than diverging from it.
- self.fenced_partitions.lock().await.remove(&partition);
+ self.fenced_partitions
+ .lock()
+ .expect("fenced partitions lock poisoned")
+ .remove(&partition);
self.store
.put_warmed_ack(&PodWarmedAck {
pod_name: pod.clone(),
@@ -1230,13 +1412,27 @@ impl PodHandle {
// dispatched for it again and its cache, floors, and
// producer leaked for the life of the process. Release is
// idempotent, so a retry that re-runs it costs nothing.
- let was_warmed = self.warmed_partitions.lock().await.contains_key(&partition);
- let was_fenced = self.fenced_partitions.lock().await.contains(&partition);
+ let was_warmed = self
+ .warmed_partitions
+ .lock()
+ .expect("warmed partitions lock poisoned")
+ .contains_key(&partition);
+ let was_fenced = self
+ .fenced_partitions
+ .lock()
+ .expect("fenced partitions lock poisoned")
+ .contains(&partition);
if was_warmed || was_fenced {
tracing::info!(pod, partition, "converging to Released: releasing");
self.handler.release_partition(partition).await?;
- self.warmed_partitions.lock().await.remove(&partition);
- self.fenced_partitions.lock().await.remove(&partition);
+ self.warmed_partitions
+ .lock()
+ .expect("warmed partitions lock poisoned")
+ .remove(&partition);
+ self.fenced_partitions
+ .lock()
+ .expect("fenced partitions lock poisoned")
+ .remove(&partition);
counter!("personhog_coordination_partition_releases_total").increment(1);
self.drain_notify.notify_one();
did_work = true;
@@ -1244,8 +1440,7 @@ impl PodHandle {
}
}
- gauge!("personhog_coordination_partitions_held")
- .set(self.held_partition_count().await as f64);
+ gauge!("personhog_coordination_partitions_held").set(self.held_partition_count() as f64);
Ok(did_work)
}
@@ -1472,8 +1667,14 @@ impl PodHandle {
}
}
msg = stream.message() => {
- let resp = msg?.ok_or_else(|| Error::invalid_state("handoff watch stream ended".to_string()))?;
+ let resp = util::live_watch_response(msg?, "handoff")?;
for event in resp.events() {
+ let mut unreadable = false;
+ // Convergence still reads durable state rather
+ // than trusting the payload; the payload only
+ // decides whether to look. See
+ // `event_concerns_pod` for what makes an event
+ // this pod's business.
let partition = match event.event_type() {
EventType::Put => match parse_watch_value::<HandoffState>(event) {
Ok(handoff) => {
@@ -1482,18 +1683,51 @@ impl PodHandle {
handoff.phase,
handoff.phase_entered_at_ms,
);
- Some(handoff.partition)
+ let partition = handoff.partition;
+ if event_concerns_pod(
+ &self.config.pod_name,
+ Some(&handoff),
+ self.holds_local_state(partition),
+ in_flight.contains(&partition),
+ ) {
+ Some(partition)
+ } else {
+ None
+ }
}
Err(e) => {
tracing::error!(pod = %self.config.pod_name, error = %e, "failed to parse handoff");
+ unreadable = true;
None
}
},
- EventType::Delete => event
+ EventType::Delete => match event
.kv()
.and_then(|kv| from_utf8(kv.key()).ok())
- .and_then(store::extract_partition_from_key),
+ .and_then(store::extract_partition_from_key)
+ {
+ Some(p)
+ if event_concerns_pod(
+ &self.config.pod_name,
+ None,
+ self.holds_local_state(p),
+ in_flight.contains(&p),
+ ) =>
+ {
+ Some(p)
+ }
+ Some(_) => None,
+ None => {
+ unreadable = true;
+ None
+ }
+ },
};
+ util::record_handoff_event_disposition(match (partition, unreadable) {
+ (Some(_), _) => "converged",
+ (None, true) => "unreadable",
+ (None, false) => "skipped",
+ });
if let Some(partition) = partition {
dispatch(
self,
@@ -1611,6 +1845,13 @@ async fn watch_own_registration(
message = stream.message() => message,
};
let Ok(Some(response)) = message else { return };
+ // A cancelled watcher delivers nothing further. This watch is
+ // defense-in-depth: the session teardown it accelerates still
+ // happens without it, so ending is safe.
+ if response.canceled() {
+ tracing::warn!(pod = %pod_name, "registration watch cancelled by etcd; watch ends");
+ return;
+ }
for event in response.events() {
if event.event_type() != EventType::Delete {
continue;
@@ -1629,14 +1870,9 @@ async fn watch_own_registration(
pod = %pod_name,
"registration deleted; surrendering serving authority immediately"
);
- // Deliberately redundant: the session teardown below
- // surrenders too, so deleting this line leaves every
- // test green. What it buys is the interval — the pod
- // stops answering on the watch event rather than
- // whenever teardown finishes, and until it does it is
- // serving strong reads on a claim the cluster has
- // already withdrawn. The residual gap is etcd's watch
- // delivery latency, which no call can close.
+ // Deliberately redundant with the session teardown's
+ // surrender: this one stops strong reads at watch
+ // delivery rather than when teardown finishes.
authority.surrender();
// Surrendering alone would leave a pod that holds a live
// lease, refuses every read, and never registers again —
@@ -1667,6 +1903,84 @@ mod tests {
}
}
+ /// An event a pod is party to must reach a convergence, by any of
+ /// the three routes — and one it is not party to must not. The skip
+ /// direction is the one worth having: every integration test passed
+ /// before the scoping existed, so nothing else asserts it.
+ #[test]
+ fn an_event_reaches_only_the_pods_it_concerns() {
+ let cases = [
+ (
+ "named as the old owner",
+ Some(handoff(Some(POD), OTHER, HandoffPhase::Freezing)),
+ false,
+ false,
+ true,
+ ),
+ (
+ "named as the new owner",
+ Some(handoff(Some(OTHER), POD, HandoffPhase::Warming)),
+ false,
+ false,
+ true,
+ ),
+ (
+ // A replacement overwrites the handoff key in place, so
+ // an old owner dropped from the successor sees a put
+ // naming two other pods. Only the fence it still holds
+ // says the fence should come off.
+ "unnamed but still holding a fence or a cache",
+ Some(handoff(Some(OTHER), THIRD, HandoffPhase::Freezing)),
+ true,
+ false,
+ true,
+ ),
+ (
+ "unnamed but converging it right now",
+ Some(handoff(Some(OTHER), THIRD, HandoffPhase::Freezing)),
+ false,
+ true,
+ true,
+ ),
+ (
+ "a deletion, while holding local state for it",
+ None,
+ true,
+ false,
+ true,
+ ),
+ (
+ "a deletion, while still warming for it",
+ None,
+ false,
+ true,
+ true,
+ ),
+ (
+ "another pods' handoff, holding nothing and converging nothing",
+ Some(handoff(Some(OTHER), THIRD, HandoffPhase::Freezing)),
+ false,
+ false,
+ false,
+ ),
+ (
+ "a deletion for a partition this pod has nothing to do with",
+ None,
+ false,
+ false,
+ false,
+ ),
+ ];
+
+ for (case, handoff, holds_local_state, converging, expected) in cases {
+ assert_eq!(
+ event_concerns_pod(POD, handoff.as_ref(), holds_local_state, converging),
+ expected,
+ "{case}"
+ );
+ }
+ }
+
fn handoff(old_owner: Option<&str>, new_owner: &str, phase: HandoffPhase) -> HandoffState {
HandoffState {
partition: 1,
@@ -1676,6 +1990,7 @@ mod tests {
started_at: 0,
handoff_id: "h-test".to_string(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
diff --git a/rust/personhog-coordination/src/protocol.rs b/rust/personhog-coordination/src/protocol.rs
index bc5a3ee1158f..ad54f576f9b9 100644
--- a/rust/personhog-coordination/src/protocol.rs
+++ b/rust/personhog-coordination/src/protocol.rs
@@ -135,37 +135,41 @@ pub fn freeze_quorum_met(
routers: &[RegisteredRouter],
freeze_acks: &[RouterFreezeAck],
handoff: &HandoffState,
+ quorum: Option<&[String]>,
) -> bool {
let acked: HashSet<&str> = freeze_acks
.iter()
.filter(|a| a.handoff_id == handoff.handoff_id)
.map(|a| a.router_name.as_str())
.collect();
- required_freeze_ackers(routers, handoff).all(|name| acked.contains(name))
+ required_freeze_ackers(routers, quorum).all(|name| acked.contains(name))
}
-/// The routers whose freeze ack this handoff needs: those it was created
-/// with that are still registered.
+/// The routers whose freeze ack a handoff needs: the membership it was
+/// created with, intersected with those still registered.
///
/// Intersecting the snapshot with the live set makes the requirement
/// monotonic — it can only shrink. A router that dies drops out (it is no
/// longer routing, so it cannot reach the old owner), and one that joins
/// later is never added (safe to exclude — see
-/// [`HandoffState::freeze_quorum`] for why).
+/// [`HandoffState::freeze_quorum_ref`] for why).
+///
+/// `quorum` is the membership already resolved from the record. `None`
+/// means none was recorded — a pre-upgrade record, or a reference that
+/// no longer resolves — and falls back to requiring every live router,
+/// the rule such records were written under and the stricter of the
+/// two. `Some` is authoritative even when empty: zero routers
+/// registered at creation means nobody must ack.
pub fn required_freeze_ackers<'a>(
routers: &'a [RegisteredRouter],
- handoff: &'a HandoffState,
+ quorum: Option<&'a [String]>,
) -> impl Iterator<Item = &'a str> + 'a {
routers
.iter()
.map(|r| r.router_name.as_str())
- // `None` is a pre-upgrade record: fall back to requiring every
- // live router, which is what it was written under. A `Some`
- // snapshot is authoritative even when empty — zero routers at
- // creation means nobody must ack, not "apply the legacy rule".
- .filter(move |name| match &handoff.freeze_quorum {
+ .filter(move |name| match quorum {
None => true,
- Some(quorum) => quorum.iter().any(|member| member == name),
+ Some(members) => members.iter().any(|member| member == name),
})
}
@@ -220,13 +224,14 @@ pub fn missing_freeze_ackers(
routers: &[RegisteredRouter],
freeze_acks: &[RouterFreezeAck],
handoff: &HandoffState,
+ quorum: Option<&[String]>,
) -> Vec<String> {
let acked: HashSet<&str> = freeze_acks
.iter()
.filter(|a| a.handoff_id == handoff.handoff_id)
.map(|a| a.router_name.as_str())
.collect();
- required_freeze_ackers(routers, handoff)
+ required_freeze_ackers(routers, quorum)
.filter(|name| !acked.contains(name))
.map(str::to_string)
.collect()
@@ -284,6 +289,7 @@ mod tests {
started_at: 0,
handoff_id: String::new(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
@@ -314,12 +320,17 @@ mod tests {
/// nothing can satisfy and no cleanup path removes.
#[test]
fn a_router_that_joined_after_creation_is_not_required() {
- let mut h = handoff(0, Some("pod-a"), "pod-b");
- h.freeze_quorum = Some(vec!["router-0".to_string()]);
+ let h = handoff(0, Some("pod-a"), "pod-b");
+ let quorum = ["router-0".to_string()];
let acks = [freeze_ack("router-0", &h)];
assert!(
- freeze_quorum_met(&[router("router-0"), router("late-joiner")], &acks, &h),
+ freeze_quorum_met(
+ &[router("router-0"), router("late-joiner")],
+ &acks,
+ &h,
+ Some(&quorum)
+ ),
"a router registered after creation must not block the quorum"
);
}
@@ -381,14 +392,19 @@ mod tests {
/// one.
#[test]
fn missing_ackers_names_the_holdout_and_ignores_stale_acks() {
- let mut h = handoff(0, Some("pod-a"), "pod-b");
- h.freeze_quorum = Some(vec!["router-0".to_string(), "router-1".to_string()]);
+ let h = handoff(0, Some("pod-a"), "pod-b");
+ let quorum = ["router-0".to_string(), "router-1".to_string()];
let mut stale = freeze_ack("router-1", &h);
stale.handoff_id = "a-previous-handoff".to_string();
let acks = [freeze_ack("router-0", &h), stale];
assert_eq!(
- missing_freeze_ackers(&[router("router-0"), router("router-1")], &acks, &h),
+ missing_freeze_ackers(
+ &[router("router-0"), router("router-1")],
+ &acks,
+ &h,
+ Some(&quorum)
+ ),
vec!["router-1".to_string()],
"router-1's stale ack proves nothing about this handoff"
);
@@ -399,17 +415,22 @@ mod tests {
/// owner, so its ack stays mandatory.
#[test]
fn a_router_present_at_creation_is_still_required() {
- let mut h = handoff(0, Some("pod-a"), "pod-b");
- h.freeze_quorum = Some(vec!["router-0".to_string(), "router-1".to_string()]);
+ let h = handoff(0, Some("pod-a"), "pod-b");
+ let quorum = ["router-0".to_string(), "router-1".to_string()];
let acks = [freeze_ack("router-0", &h)];
assert!(
- !freeze_quorum_met(&[router("router-0"), router("router-1")], &acks, &h),
+ !freeze_quorum_met(
+ &[router("router-0"), router("router-1")],
+ &acks,
+ &h,
+ Some(&quorum)
+ ),
"a snapshot member that has not acked must block the quorum"
);
// ...until it departs: a router that is gone cannot route.
assert!(
- freeze_quorum_met(&[router("router-0")], &acks, &h),
+ freeze_quorum_met(&[router("router-0")], &acks, &h, Some(&quorum)),
"a departed snapshot member must drop out of the requirement"
);
}
@@ -421,14 +442,13 @@ mod tests {
#[test]
fn an_absent_snapshot_requires_every_live_router() {
let h = handoff(0, Some("pod-a"), "pod-b");
- assert!(h.freeze_quorum.is_none());
let acks = [freeze_ack("router-0", &h)];
assert!(
- !freeze_quorum_met(&[router("router-0"), router("router-1")], &acks, &h),
- "without a snapshot every live router must still be required"
+ !freeze_quorum_met(&[router("router-0"), router("router-1")], &acks, &h, None),
+ "without a membership every live router must still be required"
);
- assert!(freeze_quorum_met(&[router("router-0")], &acks, &h));
+ assert!(freeze_quorum_met(&[router("router-0")], &acks, &h, None));
}
/// A captured-but-empty snapshot is not the legacy fallback: zero
@@ -438,11 +458,11 @@ mod tests {
/// the wedge for exactly this corner.
#[test]
fn an_empty_snapshot_requires_nobody() {
- let mut h = handoff(0, Some("pod-a"), "pod-b");
- h.freeze_quorum = Some(Vec::new());
+ let h = handoff(0, Some("pod-a"), "pod-b");
+ let quorum: [String; 0] = [];
assert!(
- freeze_quorum_met(&[router("late-joiner")], &[], &h),
+ freeze_quorum_met(&[router("late-joiner")], &[], &h, Some(&quorum)),
"a router that registered after a zero-router creation must not be required"
);
}
diff --git a/rust/personhog-coordination/src/routing_table.rs b/rust/personhog-coordination/src/routing_table.rs
index 0151e0ab468a..0ef373ede5e3 100644
--- a/rust/personhog-coordination/src/routing_table.rs
+++ b/rust/personhog-coordination/src/routing_table.rs
@@ -231,6 +231,12 @@ pub struct RoutingTableConfig {
/// Base backoff between coordination attempts; doubles per
/// consecutive failure up to a fixed cap.
pub run_retry_backoff: Duration,
+ /// How many freeze acks may share one transaction. Not a tuning
+ /// knob but a mirror of the server's `--max-txn-ops`: a batch above
+ /// it is refused outright, while a smaller one only costs an extra
+ /// round trip. Defaults to etcd's own default, so it needs setting
+ /// only against a server configured otherwise.
+ pub max_txn_ops: usize,
}
impl Default for RoutingTableConfig {
@@ -248,6 +254,7 @@ impl Default for RoutingTableConfig {
reconcile_failure_budget: 12,
run_retry_budget: 10,
run_retry_backoff: Duration::from_millis(500),
+ max_txn_ops: 128,
}
}
}
@@ -272,6 +279,13 @@ impl Default for RoutingTableConfig {
/// `RouterFreezeAck` so the coordinator can collect freeze quorum. At
/// `Complete` the table flips to the new owner and `drain_stash` flushes
/// any buffered requests through the standard forwarding path.
+/// How long any of the routing table's lease revokes may take before
+/// its exit path stops waiting. The routing table's own bound, not the
+/// coordinator's constant: they happen to agree today, but each answers
+/// to its own component budget, and sharing one number across two
+/// budgets is how a retune of either silently reshapes the other.
+const REVOKE_TIMEOUT: Duration = Duration::from_secs(2);
+
pub struct RoutingTable {
store: Arc<PersonhogStore>,
config: RoutingTableConfig,
@@ -401,7 +415,9 @@ impl RoutingTable {
/// 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.
+ /// slate. The cancellation exits before registration are the one
+ /// shape apart: nothing exists to tear down yet, and the mid-
+ /// registration exit revokes its own lease inline.
///
/// The `handler` implements stashing and drain. It's invoked on handoff
/// phase transitions: `begin_stash` at Freezing, `drain_stash` at Complete.
@@ -417,10 +433,29 @@ impl RoutingTable {
// 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
+ // Register this router so the coordinator can count it for ack
+ // quorum. Both calls race cancellation; past the grant, any
+ // abandonment revokes the known lease, since a registration
+ // that landed anyway would stall every freeze in its TTL
+ // window.
let granted_at = Instant::now();
- let lease_id = self.store.grant_lease(self.config.lease_ttl).await?;
- self.register_router(lease_id).await?;
+ let lease_id = tokio::select! {
+ _ = cancel.cancelled() => return Ok(()),
+ granted = self.store.grant_lease(self.config.lease_ttl) => granted?,
+ };
+ let registered = tokio::select! {
+ _ = cancel.cancelled() => {
+ drop(tokio::time::timeout(REVOKE_TIMEOUT, self.store.revoke_lease(lease_id)).await);
+ return Ok(());
+ }
+ registered = self.register_router(lease_id) => registered,
+ };
+ if let Err(e) = registered {
+ // A failed registration may also have half-landed; revoking
+ // clears it rather than leaving the lease to its TTL.
+ drop(tokio::time::timeout(REVOKE_TIMEOUT, self.store.revoke_lease(lease_id)).await);
+ return Err(e);
+ }
// From here to the supervised select below, this router is
// registered — counted in every freeze quorum — but not yet
@@ -454,17 +489,17 @@ impl RoutingTable {
};
let (pods_stream, handoff_stream) = tokio::select! {
_ = cancel.cancelled() => {
- drop(self.store.revoke_lease(lease_id).await);
+ drop(tokio::time::timeout(REVOKE_TIMEOUT, 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);
+ drop(tokio::time::timeout(REVOKE_TIMEOUT, self.store.revoke_lease(lease_id)).await);
return Err(e);
}
Err(_) => {
- drop(self.store.revoke_lease(lease_id).await);
+ drop(tokio::time::timeout(REVOKE_TIMEOUT, self.store.revoke_lease(lease_id)).await);
return Err(Error::invalid_state(format!(
"router bootstrap exceeded {BOOTSTRAP_DEADLINE:?} while registered"
)));
@@ -555,6 +590,7 @@ impl RoutingTable {
let last_progress = Arc::clone(&last_progress);
let reconcile_interval = self.config.reconcile_interval;
let reconcile_failure_budget = self.config.reconcile_failure_budget;
+ let max_txn_ops = self.config.max_txn_ops;
let token = cancel.child_token();
let progress = Arc::clone(progress);
tasks.spawn(async move {
@@ -572,6 +608,7 @@ impl RoutingTable {
stamp_interval,
reconcile_interval,
reconcile_failure_budget,
+ max_txn_ops,
progress,
)
.await
@@ -604,9 +641,12 @@ impl RoutingTable {
// next TTL window stalls waiting for a freeze ack this router
// will never write. Still best-effort — an unreachable etcd lets
// the lease lapse by TTL — but loudly so: this line is the proof
- // a graceful shutdown reached its deregistration.
- match self.store.revoke_lease(lease_id).await {
- Ok(()) => {
+ // a graceful shutdown reached its deregistration. Bounded,
+ // because an etcd that hangs rather than erring would otherwise
+ // spend this component's whole shutdown budget here and turn the
+ // proof into a lifecycle-abandonment log.
+ match tokio::time::timeout(REVOKE_TIMEOUT, self.store.revoke_lease(lease_id)).await {
+ Ok(Ok(())) => {
metrics::counter!(
"personhog_coordination_router_deregistered_total",
"outcome" => "revoked"
@@ -617,7 +657,7 @@ impl RoutingTable {
"router deregistered, freeze quorums no longer count it"
);
}
- Err(e) => {
+ Ok(Err(e)) => {
metrics::counter!(
"personhog_coordination_router_deregistered_total",
"outcome" => "revoke_failed"
@@ -630,6 +670,19 @@ impl RoutingTable {
freezes created meanwhile stall on it"
);
}
+ Err(_) => {
+ metrics::counter!(
+ "personhog_coordination_router_deregistered_total",
+ "outcome" => "revoke_failed"
+ )
+ .increment(1);
+ tracing::warn!(
+ router = %self.config.router_name,
+ "router lease revoke unanswered after {REVOKE_TIMEOUT:?}; the request may \
+ still land — if it does not, registration lapses by TTL and freezes \
+ created meanwhile stall on it"
+ );
+ }
}
result
@@ -662,6 +715,7 @@ impl RoutingTable {
// already at Complete arrive as a normal Put event through the
// watch loop below.
let (handoffs, snapshot_revision) = self.store.list_handoffs_with_revision().await?;
+ let mut acks = Vec::new();
for handoff in handoffs {
if matches!(
handoff.phase,
@@ -680,23 +734,27 @@ impl RoutingTable {
.begin_stash(handoff.partition, &handoff.new_owner)
.await?;
- // Only write a FreezeAck while still in Freezing — once
- // the coordinator advanced past Freezing, the freeze
- // quorum has been collected and a late ack would be
- // either redundant or, worse, mistakenly counted toward
- // a future handoff for the same partition.
+ // Only ack while still in Freezing — once the
+ // coordinator advanced, the quorum has been collected
+ // and a late ack is redundant (quorum evaluation matches
+ // on handoff_id, so it can never count elsewhere).
if handoff.phase == HandoffPhase::Freezing {
- let ack = RouterFreezeAck {
+ acks.push(RouterFreezeAck {
router_name: self.config.router_name.clone(),
partition: handoff.partition,
acked_at: util::now_seconds(),
acked_at_ms: 0,
handoff_id: handoff.handoff_id.clone(),
- };
- self.store.put_freeze_ack(&ack).await?;
+ });
}
}
}
+ // One batched write after every stash above is open: a restart
+ // during a fleet-wide freeze otherwise pays one round trip per
+ // frozen partition, serially, with the freeze quorum waiting.
+ self.store
+ .put_freeze_acks(&acks, self.config.max_txn_ops)
+ .await?;
let assignments = self.store.list_assignments().await?;
// Live registrations overlay assignment-carried addresses: an
@@ -746,7 +804,7 @@ impl RoutingTable {
tokio::select! {
_ = cancel.cancelled() => return Ok(()),
msg = stream.message() => {
- let resp = msg?.ok_or_else(|| Error::invalid_state("pod watch stream ended".to_string()))?;
+ let resp = util::live_watch_response(msg?, "pod")?;
for event in resp.events() {
if event.event_type() != EventType::Put {
continue;
@@ -785,6 +843,7 @@ impl RoutingTable {
stamp_interval: Duration,
reconcile_interval: Duration,
reconcile_failure_budget: u32,
+ max_txn_ops: usize,
progress: Arc<AtomicBool>,
) -> Result<()> {
let mut consecutive_reconcile_failures: u32 = 0;
@@ -835,6 +894,7 @@ impl RoutingTable {
&handler,
&lanes,
&router_name,
+ max_txn_ops,
)
.await
{
@@ -863,18 +923,19 @@ impl RoutingTable {
}
}
msg = stream.message() => {
- let resp = msg?.ok_or_else(|| Error::invalid_state("handoff watch stream ended".to_string()))?;
+ let resp = util::live_watch_response(msg?, "handoff")?;
+ let mut acks = Vec::new();
for event in resp.events() {
match event.event_type() {
EventType::Put => {
if Self::handle_handoff_put(
event,
- store.as_ref(),
&table,
&addresses,
&handler,
&lanes,
&router_name,
+ &mut acks,
).await?
{
progress.store(true, Ordering::SeqCst);
@@ -905,6 +966,11 @@ impl RoutingTable {
}
}
}
+ // One write per response, after every event's stash
+ // is open: a response carrying a plan's worth of
+ // freezes costs one round trip instead of one per
+ // partition.
+ store.put_freeze_acks(&acks, max_txn_ops).await?;
}
}
}
@@ -932,6 +998,7 @@ impl RoutingTable {
handler: &Arc<dyn StashHandler>,
lanes: &Arc<DrainLanes>,
router_name: &str,
+ max_txn_ops: usize,
) -> Result<()> {
// Registrations are the address authority; refresh them wholesale
// so a pod that re-registered at a new address is dialable even
@@ -948,6 +1015,7 @@ impl RoutingTable {
let handoffs = store.list_handoffs().await?;
let mut constrained: HashSet<u32> = HashSet::new();
+ let mut acks = Vec::new();
for handoff in &handoffs {
constrained.insert(handoff.partition);
match handoff.phase {
@@ -957,14 +1025,13 @@ impl RoutingTable {
.begin_stash(handoff.partition, &handoff.new_owner)
.await?;
if handoff.phase == HandoffPhase::Freezing {
- let ack = RouterFreezeAck {
+ acks.push(RouterFreezeAck {
router_name: router_name.to_string(),
partition: handoff.partition,
acked_at: util::now_seconds(),
acked_at_ms: 0,
handoff_id: handoff.handoff_id.clone(),
- };
- store.put_freeze_ack(&ack).await?;
+ });
}
}
HandoffPhase::Complete => {
@@ -997,6 +1064,10 @@ impl RoutingTable {
}
}
+ // One batched write after every stash above is open; deferring
+ // an ack only delays the quorum, never lies to it.
+ store.put_freeze_acks(&acks, max_txn_ops).await?;
+
let assignments = store.list_assignments().await?;
for assignment in assignments {
if constrained.contains(&assignment.partition) {
@@ -1030,12 +1101,12 @@ impl RoutingTable {
async fn handle_handoff_put(
event: &etcd_client::Event,
- store: &PersonhogStore,
table: &Arc<RwLock<HashMap<u32, String>>>,
addresses: &Arc<StdRwLock<HashMap<String, String>>>,
handler: &Arc<dyn StashHandler>,
lanes: &Arc<DrainLanes>,
router_name: &str,
+ acks: &mut Vec<RouterFreezeAck>,
) -> Result<bool> {
let handoff: HandoffState = match parse_watch_value(event) {
Ok(h) => h,
@@ -1069,18 +1140,19 @@ impl RoutingTable {
.begin_stash(handoff.partition, &handoff.new_owner)
.await?;
- // Only write a FreezeAck in Freezing — routers can arrive
- // late, observe a later phase, and must not re-ack a
- // quorum that has already cleared.
+ // Only ack in Freezing — routers can arrive late,
+ // observe a later phase, and must not re-ack a quorum
+ // that has already cleared. Collected, not written: the
+ // watch loop flushes one batch per response, after every
+ // event's stash is open.
if handoff.phase == HandoffPhase::Freezing {
- let ack = RouterFreezeAck {
+ acks.push(RouterFreezeAck {
router_name: router_name.to_string(),
partition: handoff.partition,
acked_at: util::now_seconds(),
acked_at_ms: 0,
handoff_id: handoff.handoff_id.clone(),
- };
- store.put_freeze_ack(&ack).await?;
+ });
}
}
HandoffPhase::Complete => {
diff --git a/rust/personhog-coordination/src/store.rs b/rust/personhog-coordination/src/store.rs
index fc590fb8c582..eda453731cd9 100644
--- a/rust/personhog-coordination/src/store.rs
+++ b/rust/personhog-coordination/src/store.rs
@@ -1,4 +1,6 @@
+use std::collections::HashMap;
use std::str::from_utf8;
+use std::sync::{Arc, Mutex as StdMutex};
use assignment_coordination::store::EtcdStore;
use etcd_client::{Compare, CompareOp, DeleteOptions, PutOptions, Txn, TxnOp, WatchStream};
@@ -32,6 +34,9 @@ enum StoreKey<'a> {
WarmedAck { partition: u32, pod: &'a str },
WarmedAcksForPartition(u32),
WarmedAcksPrefix,
+ // Freeze quorum membership, shared by every handoff one plan creates.
+ FreezeQuorum(&'a str),
+ FreezeQuorumsPrefix,
Leader,
Generation,
TotalPartitions,
@@ -63,6 +68,8 @@ impl StoreKey<'_> {
}
StoreKey::WarmedAcksForPartition(p) => format!("{prefix}warmed_acks/{p}/"),
StoreKey::WarmedAcksPrefix => format!("{prefix}warmed_acks/"),
+ StoreKey::FreezeQuorum(id) => format!("{prefix}freeze_quorums/{id}"),
+ StoreKey::FreezeQuorumsPrefix => format!("{prefix}freeze_quorums/"),
StoreKey::Leader => format!("{prefix}coordinator/leader"),
StoreKey::Generation => format!("{prefix}generation"),
StoreKey::TotalPartitions => format!("{prefix}config/total_partitions"),
@@ -77,11 +84,34 @@ impl StoreKey<'_> {
#[derive(Clone)]
pub struct PersonhogStore {
inner: EtcdStore,
+ /// Freeze-quorum memberships already read, by record id. Records
+ /// are written once and only ever deleted, so an id identifies one
+ /// immutable value and caching cannot go stale; a plan's handoffs
+ /// share one id, so this turns a few hundred reads per reconcile
+ /// pass into one.
+ ///
+ /// INVARIANT: the cached value keeps `Some` (recorded membership)
+ /// distinct from `None` (record absent — requires every live
+ /// router). Flattening them would advance a handoff no router had
+ /// stopped routing for.
+ freeze_quorums: Arc<StdMutex<HashMap<String, Option<Vec<String>>>>>,
+}
+
+/// Counts store calls by the method that made them. The shared etcd
+/// layer labels by primitive — `get`, `list_with_revision` — which is
+/// too coarse to attribute load: a single `get` label covers the
+/// coordinator's handoff read, a pod's convergence read, and every
+/// other single-key lookup in the system.
+pub(crate) fn count_call(site: &'static str) {
+ metrics::counter!("personhog_coordination_store_calls_total", "site" => site).increment(1);
}
impl PersonhogStore {
pub fn new(inner: EtcdStore) -> Self {
- Self { inner }
+ Self {
+ inner,
+ freeze_quorums: Arc::new(StdMutex::new(HashMap::new())),
+ }
}
pub fn inner(&self) -> &EtcdStore {
@@ -95,6 +125,7 @@ impl PersonhogStore {
// ── Pod operations ──────────────────────────────────────────
pub async fn register_pod(&self, pod: &RegisteredPod, lease_id: i64) -> Result<()> {
+ count_call("register_pod");
let key = self.key(StoreKey::Pod(&pod.pod_name));
Ok(self.inner.put(&key, pod, Some(lease_id)).await?)
}
@@ -107,6 +138,7 @@ impl PersonhogStore {
}
pub async fn get_pod(&self, pod_name: &str) -> Result<Option<RegisteredPod>> {
+ count_call("get_pod");
let key = self.key(StoreKey::Pod(pod_name));
Ok(self.inner.get(&key).await?)
}
@@ -119,6 +151,7 @@ impl PersonhogStore {
}
pub async fn list_pods(&self) -> Result<Vec<RegisteredPod>> {
+ count_call("list_pods");
let key = self.key(StoreKey::PodsPrefix);
Ok(self.inner.list(&key).await?)
}
@@ -126,6 +159,7 @@ impl PersonhogStore {
/// List pods along with the etcd revision of the snapshot, so a watch
/// can be anchored strictly after it.
pub async fn list_pods_with_revision(&self) -> Result<(Vec<RegisteredPod>, i64)> {
+ count_call("list_pods_with_revision");
let key = self.key(StoreKey::PodsPrefix);
Ok(self.inner.list_with_revision(&key).await?)
}
@@ -136,6 +170,7 @@ impl PersonhogStore {
status: PodStatus,
lease_id: i64,
) -> Result<()> {
+ count_call("update_pod_status");
let key = self.key(StoreKey::Pod(pod_name));
let mut pod: RegisteredPod = self
.inner
@@ -155,23 +190,27 @@ impl PersonhogStore {
/// replaying events since that revision even if they predate the
/// watch's creation.
pub async fn watch_pods_from(&self, start_revision: i64) -> Result<WatchStream> {
+ count_call("watch_pods_from");
let key = self.key(StoreKey::PodsPrefix);
Ok(self.inner.watch_from(&key, start_revision).await?)
}
/// The current etcd store revision, for anchoring watches.
pub async fn current_revision(&self) -> Result<i64> {
+ count_call("current_revision");
Ok(self.inner.current_revision().await?)
}
// ── Router operations ────────────────────────────────────────
pub async fn register_router(&self, router: &RegisteredRouter, lease_id: i64) -> Result<()> {
+ count_call("register_router");
let key = self.key(StoreKey::Router(&router.router_name));
Ok(self.inner.put(&key, router, Some(lease_id)).await?)
}
pub async fn list_routers(&self) -> Result<Vec<RegisteredRouter>> {
+ count_call("list_routers");
let key = self.key(StoreKey::RoutersPrefix);
Ok(self.inner.list(&key).await?)
}
@@ -182,6 +221,7 @@ impl PersonhogStore {
}
pub async fn watch_routers_from(&self, start_revision: i64) -> Result<WatchStream> {
+ count_call("watch_routers_from");
let key = self.key(StoreKey::RoutersPrefix);
Ok(self.inner.watch_from(&key, start_revision).await?)
}
@@ -189,11 +229,13 @@ impl PersonhogStore {
// ── Assignment operations ───────────────────────────────────
pub async fn get_assignment(&self, partition: u32) -> Result<Option<PartitionAssignment>> {
+ count_call("get_assignment");
let key = self.key(StoreKey::Assignment(partition));
Ok(self.inner.get(&key).await?)
}
pub async fn list_assignments(&self) -> Result<Vec<PartitionAssignment>> {
+ count_call("list_assignments");
let key = self.key(StoreKey::AssignmentsPrefix);
Ok(self.inner.list(&key).await?)
}
@@ -201,6 +243,7 @@ impl PersonhogStore {
/// Like `list_assignments`, but also returns the etcd revision of the
/// snapshot, for gap-free snapshot-then-watch handshakes.
pub async fn list_assignments_with_revision(&self) -> Result<(Vec<PartitionAssignment>, i64)> {
+ count_call("list_assignments_with_revision");
let key = self.key(StoreKey::AssignmentsPrefix);
Ok(self.inner.list_with_revision(&key).await?)
}
@@ -211,6 +254,7 @@ impl PersonhogStore {
pub async fn list_assignments_with_mod_revisions(
&self,
) -> Result<Vec<(PartitionAssignment, i64)>> {
+ count_call("list_assignments_with_mod_revisions");
let key = self.key(StoreKey::AssignmentsPrefix);
Ok(self.inner.list_with_mod_revisions(&key).await?)
}
@@ -237,11 +281,13 @@ impl PersonhogStore {
// ── Handoff operations ──────────────────────────────────────
pub async fn get_handoff(&self, partition: u32) -> Result<Option<HandoffState>> {
+ count_call("get_handoff");
let key = self.key(StoreKey::Handoff(partition));
Ok(self.inner.get(&key).await?)
}
pub async fn list_handoffs(&self) -> Result<Vec<HandoffState>> {
+ count_call("list_handoffs");
let key = self.key(StoreKey::HandoffsPrefix);
Ok(self.inner.list(&key).await?)
}
@@ -250,6 +296,7 @@ impl PersonhogStore {
/// snapshot. Pair with `watch_handoffs_from(revision + 1)` for a
/// gap-free snapshot-then-watch handshake.
pub async fn list_handoffs_with_revision(&self) -> Result<(Vec<HandoffState>, i64)> {
+ count_call("list_handoffs_with_revision");
let key = self.key(StoreKey::HandoffsPrefix);
Ok(self.inner.list_with_revision(&key).await?)
}
@@ -258,6 +305,7 @@ impl PersonhogStore {
/// `mod_revision`, so a later replacement can be guarded on the
/// record being exactly the one this snapshot read.
pub async fn list_handoffs_with_mod_revisions(&self) -> Result<Vec<(HandoffState, i64)>> {
+ count_call("list_handoffs_with_mod_revisions");
let key = self.key(StoreKey::HandoffsPrefix);
Ok(self.inner.list_with_mod_revisions(&key).await?)
}
@@ -265,6 +313,7 @@ impl PersonhogStore {
/// Bypasses the protocol: see the crate's `test-support` feature.
#[cfg(any(test, feature = "test-support"))]
pub async fn put_handoff(&self, handoff: &HandoffState) -> Result<()> {
+ count_call("put_handoff");
let key = self.key(StoreKey::Handoff(handoff.partition));
Ok(self.inner.put(&key, handoff, None).await?)
}
@@ -293,6 +342,7 @@ impl PersonhogStore {
expected: crate::types::HandoffPhase,
new_phase: crate::types::HandoffPhase,
) -> Result<bool> {
+ count_call("cas_handoff_phase");
let handoff_key = self.key(StoreKey::Handoff(partition));
let Some((mut handoff, mod_revision)) = self
.inner
@@ -329,6 +379,7 @@ impl PersonhogStore {
&self,
partition: u32,
) -> Result<Option<(HandoffState, i64)>> {
+ count_call("get_handoff_with_mod_revision");
let key = self.key(StoreKey::Handoff(partition));
Ok(self.inner.get_with_mod_revision(&key).await?)
}
@@ -345,6 +396,7 @@ impl PersonhogStore {
partition: u32,
expected_mod_revision: i64,
) -> Result<bool> {
+ count_call("delete_handoff_and_acks_if_unchanged");
let handoff_key = self.key(StoreKey::Handoff(partition));
let prefix_delete = || Some(DeleteOptions::new().with_prefix());
let txn = Txn::new()
@@ -388,6 +440,7 @@ impl PersonhogStore {
/// events since that revision even if they predate the watch's
/// creation.
pub async fn watch_handoffs_from(&self, start_revision: i64) -> Result<WatchStream> {
+ count_call("watch_handoffs_from");
let key = self.key(StoreKey::HandoffsPrefix);
Ok(self.inner.watch_from(&key, start_revision).await?)
}
@@ -395,6 +448,7 @@ impl PersonhogStore {
// ── Freeze ack operations (router -> coordinator) ────────────
pub async fn put_freeze_ack(&self, ack: &RouterFreezeAck) -> Result<()> {
+ count_call("put_freeze_ack");
let key = self.key(StoreKey::FreezeAck {
partition: ack.partition,
router: &ack.router_name,
@@ -406,7 +460,40 @@ impl PersonhogStore {
Ok(self.inner.put(&key, &stamped, None).await?)
}
+ /// One transaction per chunk of acks in place of one round trip per
+ /// ack: a plan freezing hundreds of partitions has every router
+ /// acking each of them, and serial puts hold the freeze quorum on
+ /// the slowest router's whole sequence. `max_txn_ops` must not
+ /// exceed the server's own limit, which refuses a larger batch
+ /// outright. An empty batch costs nothing.
+ pub async fn put_freeze_acks(
+ &self,
+ acks: &[RouterFreezeAck],
+ max_txn_ops: usize,
+ ) -> Result<()> {
+ for chunk in acks.chunks(max_txn_ops.max(1)) {
+ count_call("put_freeze_acks");
+ let mut ops = Vec::with_capacity(chunk.len());
+ for ack in chunk {
+ let key = self.key(StoreKey::FreezeAck {
+ partition: ack.partition,
+ router: &ack.router_name,
+ });
+ // The store stamps the millisecond clock so span metrics
+ // never depend on each writer remembering to.
+ let mut stamped = ack.clone();
+ stamped.acked_at_ms = assignment_coordination::util::now_millis();
+ ops.push(TxnOp::put(key, serde_json::to_vec(&stamped)?, None));
+ }
+ metrics::counter!("personhog_coordination_freeze_acks_written_total")
+ .increment(chunk.len() as u64);
+ self.inner.txn(Txn::new().and_then(ops)).await?;
+ }
+ Ok(())
+ }
+
pub async fn list_freeze_acks(&self, partition: u32) -> Result<Vec<RouterFreezeAck>> {
+ count_call("list_freeze_acks");
let key = self.key(StoreKey::FreezeAcksForPartition(partition));
Ok(self.inner.list(&key).await?)
}
@@ -422,6 +509,7 @@ impl PersonhogStore {
}
pub async fn watch_freeze_acks_from(&self, start_revision: i64) -> Result<WatchStream> {
+ count_call("watch_freeze_acks_from");
let key = self.key(StoreKey::FreezeAcksPrefix);
Ok(self.inner.watch_from(&key, start_revision).await?)
}
@@ -429,6 +517,7 @@ impl PersonhogStore {
// ── Drained ack operations (old owner -> coordinator) ────────
pub async fn put_drained_ack(&self, ack: &PodDrainedAck) -> Result<()> {
+ count_call("put_drained_ack");
let key = self.key(StoreKey::DrainedAck {
partition: ack.partition,
pod: &ack.pod_name,
@@ -441,6 +530,7 @@ impl PersonhogStore {
}
pub async fn list_drained_acks(&self, partition: u32) -> Result<Vec<PodDrainedAck>> {
+ count_call("list_drained_acks");
let key = self.key(StoreKey::DrainedAcksForPartition(partition));
Ok(self.inner.list(&key).await?)
}
@@ -456,6 +546,7 @@ impl PersonhogStore {
}
pub async fn watch_drained_acks_from(&self, start_revision: i64) -> Result<WatchStream> {
+ count_call("watch_drained_acks_from");
let key = self.key(StoreKey::DrainedAcksPrefix);
Ok(self.inner.watch_from(&key, start_revision).await?)
}
@@ -463,6 +554,7 @@ impl PersonhogStore {
// ── Warmed ack operations (new owner -> coordinator) ─────────
pub async fn put_warmed_ack(&self, ack: &PodWarmedAck) -> Result<()> {
+ count_call("put_warmed_ack");
let key = self.key(StoreKey::WarmedAck {
partition: ack.partition,
pod: &ack.pod_name,
@@ -475,6 +567,7 @@ impl PersonhogStore {
}
pub async fn list_warmed_acks(&self, partition: u32) -> Result<Vec<PodWarmedAck>> {
+ count_call("list_warmed_acks");
let key = self.key(StoreKey::WarmedAcksForPartition(partition));
Ok(self.inner.list(&key).await?)
}
@@ -490,6 +583,7 @@ impl PersonhogStore {
}
pub async fn watch_warmed_acks_from(&self, start_revision: i64) -> Result<WatchStream> {
+ count_call("watch_warmed_acks_from");
let key = self.key(StoreKey::WarmedAcksPrefix);
Ok(self.inner.watch_from(&key, start_revision).await?)
}
@@ -527,7 +621,9 @@ impl PersonhogStore {
handoffs: &[HandoffState],
preconditions: &[AssignmentPrecondition],
) -> Result<bool> {
- self.apply_plan(assignments, handoffs, &[], preconditions)
+ // The handoffs come ready-made, so there is no shared
+ // membership to write alongside them.
+ self.apply_plan(assignments, handoffs, &[], preconditions, None)
.await
}
@@ -540,22 +636,44 @@ impl PersonhogStore {
handoffs: &[HandoffState],
replacements: &[HandoffReplacement],
preconditions: &[AssignmentPrecondition],
+ // The membership every handoff in this plan refers to, written
+ // in the same transaction so no handoff is ever durable with a
+ // reference to a record that does not exist.
+ freeze_quorum: Option<(&str, &[String])>,
) -> Result<bool> {
+ count_call("apply_plan");
let mut guards: Vec<Compare> =
Vec::with_capacity(handoffs.len() + replacements.len() + preconditions.len());
let mut ops: Vec<TxnOp> =
Vec::with_capacity(assignments.len() + handoffs.len() + replacements.len() * 4);
-
+ // A plan is one gRPC request and one raft entry, so its size is
+ // bounded by etcd's `--max-request-bytes` however small the
+ // individual records are. Both terms scale with the fleet, so
+ // they are measured rather than assumed — and the measurement
+ // counts every key the request carries, guards and deletes
+ // included, since a total that omits them reads low against the
+ // exact limit it exists to warn about.
+ let mut plan_bytes = 0usize;
+
+ if let Some((id, members)) = freeze_quorum {
+ let key = self.key(StoreKey::FreezeQuorum(id));
+ let value = serde_json::to_vec(members)?;
+ plan_bytes += key.len() + value.len();
+ ops.push(TxnOp::put(key, value, None));
+ }
for a in assignments {
let key = self.key(StoreKey::Assignment(a.partition));
let value = serde_json::to_vec(a)?;
+ plan_bytes += key.len() + value.len();
ops.push(TxnOp::put(key, value, None));
}
for h in handoffs {
let key = self.key(StoreKey::Handoff(h.partition));
let value = serde_json::to_vec(h)?;
+ plan_bytes += key.len() + value.len();
// A key that was never created has create_revision 0 — the
// canonical etcd existence guard.
+ plan_bytes += key.len();
guards.push(Compare::create_revision(key.clone(), CompareOp::Equal, 0));
ops.push(TxnOp::put(key, value, None));
}
@@ -564,23 +682,23 @@ impl PersonhogStore {
let partition = r.handoff.partition;
let key = self.key(StoreKey::Handoff(partition));
let value = serde_json::to_vec(&r.handoff)?;
+ plan_bytes += key.len() + value.len();
+ plan_bytes += key.len();
guards.push(Compare::mod_revision(
key.clone(),
CompareOp::Equal,
r.expected_mod_revision,
));
- ops.push(TxnOp::delete(
+ for acks in [
self.key(StoreKey::FreezeAcksForPartition(partition)),
- prefix_delete(),
- ));
- ops.push(TxnOp::delete(
self.key(StoreKey::DrainedAcksForPartition(partition)),
- prefix_delete(),
- ));
- ops.push(TxnOp::delete(
self.key(StoreKey::WarmedAcksForPartition(partition)),
- prefix_delete(),
- ));
+ ] {
+ // A prefix delete carries `range_end` as well as the
+ // key, and they are the same length.
+ plan_bytes += acks.len() * 2;
+ ops.push(TxnOp::delete(acks, prefix_delete()));
+ }
ops.push(TxnOp::put(key, value, None));
}
for precondition in preconditions {
@@ -590,15 +708,27 @@ impl PersonhogStore {
mod_revision,
} => {
let key = self.key(StoreKey::Assignment(*partition));
+ plan_bytes += key.len();
guards.push(Compare::mod_revision(key, CompareOp::Equal, *mod_revision));
}
AssignmentPrecondition::Absent { partition } => {
let key = self.key(StoreKey::Assignment(*partition));
+ plan_bytes += key.len();
guards.push(Compare::create_revision(key, CompareOp::Equal, 0));
}
}
}
+ // Both lists count toward the request etcd sizes against
+ // `--max-request-bytes`, and each is checked separately against
+ // `--max-txn-ops`, so a sum could not be compared to either
+ // limit or say which list was close to it.
+ metrics::histogram!("personhog_coordination_plan_bytes").record(plan_bytes as f64);
+ metrics::histogram!("personhog_coordination_plan_ops", "list" => "guards")
+ .record(guards.len() as f64);
+ metrics::histogram!("personhog_coordination_plan_ops", "list" => "ops")
+ .record(ops.len() as f64);
+
let txn = Txn::new().when(guards).and_then(ops);
let resp = self.inner.txn(txn).await?;
Ok(resp.succeeded())
@@ -636,6 +766,7 @@ impl PersonhogStore {
expected_id: &str,
expected_phase: crate::types::HandoffPhase,
) -> Result<bool> {
+ count_call("complete_handoff");
let handoff_key = self.key(StoreKey::Handoff(partition));
let (mut handoff, mod_revision) = self
@@ -674,12 +805,108 @@ impl PersonhogStore {
Ok(resp.succeeded())
}
+ // ── Freeze quorum membership ────────────────────────────────
+
+ /// The membership record `id` names, or `None` if no record exists.
+ ///
+ /// Callers treat a missing record as "no membership recorded" and
+ /// fall back to requiring every live router, which is the stricter
+ /// rule — so a record lost to garbage collection or an incomplete
+ /// write delays a handoff rather than advancing it early.
+ pub async fn get_freeze_quorum(&self, id: &str) -> Result<Option<Vec<String>>> {
+ count_call("get_freeze_quorum");
+ let key = self.key(StoreKey::FreezeQuorum(id));
+ Ok(self.inner.get(&key).await?)
+ }
+
+ /// The membership a handoff requires, from wherever it is recorded.
+ ///
+ /// Records written before the membership moved into its own key
+ /// carry it inline. `None` — no reference and nothing inline, or a
+ /// reference whose record has gone — means the caller falls back to
+ /// requiring every live router.
+ pub async fn resolve_freeze_quorum(
+ &self,
+ handoff: &HandoffState,
+ ) -> Result<Option<Vec<String>>> {
+ match &handoff.freeze_quorum_ref {
+ Some(id) => {
+ // A hit answers from memory: confirming against etcd
+ // would cost the read this cache removes, to observe a
+ // case it already neutralizes. A hit that resolved to
+ // nothing still counts, so the signal persists while
+ // the condition does.
+ let cached = self
+ .freeze_quorums
+ .lock()
+ .expect("freeze quorum cache lock poisoned")
+ .get(id)
+ .cloned();
+ if let Some(members) = cached {
+ if members.is_none() {
+ crate::util::record_unresolved_freeze_quorum();
+ }
+ return Ok(members);
+ }
+ let members = self.get_freeze_quorum(id).await?;
+ // A miss is cached too: an id that resolves to nothing
+ // resolves to nothing forever, and a lost record would
+ // otherwise cost a read per frozen partition per pass.
+ {
+ let mut cache = self
+ .freeze_quorums
+ .lock()
+ .expect("freeze quorum cache lock poisoned");
+ // Sized for a rolling deploy (plans in flight, not
+ // one). Evicting the oldest — ids lead with
+ // milliseconds, so smallest is oldest — keeps the
+ // working set.
+ if cache.len() >= 32 {
+ if let Some(oldest) = cache.keys().min().cloned() {
+ cache.remove(&oldest);
+ }
+ }
+ cache.insert(id.clone(), members.clone());
+ }
+ if members.is_none() {
+ crate::util::record_unresolved_freeze_quorum();
+ tracing::warn!(
+ partition = handoff.partition,
+ quorum_id = %id,
+ "freeze quorum record is missing; requiring every live router"
+ );
+ }
+ Ok(members)
+ }
+ None => Ok(handoff.freeze_quorum.clone()),
+ }
+ }
+
+ /// The ids of every membership record currently stored.
+ pub async fn list_freeze_quorum_ids(&self) -> Result<Vec<String>> {
+ count_call("list_freeze_quorum_ids");
+ let prefix = self.key(StoreKey::FreezeQuorumsPrefix);
+ let keys = self.inner.list_keys(&prefix).await?;
+ Ok(keys
+ .iter()
+ .filter_map(|key| key.strip_prefix(prefix.as_str()))
+ .map(str::to_string)
+ .collect())
+ }
+
+ pub async fn delete_freeze_quorum(&self, id: &str) -> Result<()> {
+ count_call("delete_freeze_quorum");
+ let key = self.key(StoreKey::FreezeQuorum(id));
+ Ok(self.inner.delete(&key).await?)
+ }
+
// ── Leader election ─────────────────────────────────────────
/// Try to acquire coordinator leadership using compare-and-swap.
///
/// Returns `true` if this instance became the leader.
pub async fn try_acquire_leadership(&self, holder: &str, lease_id: i64) -> Result<bool> {
+ count_call("try_acquire_leadership");
let key = self.key(StoreKey::Leader);
let leader = LeaderInfo {
holder: holder.to_string(),
@@ -702,13 +929,31 @@ impl PersonhogStore {
}
pub async fn get_leader(&self) -> Result<Option<LeaderInfo>> {
+ count_call("get_leader");
let key = self.key(StoreKey::Leader);
Ok(self.inner.get(&key).await?)
}
+ /// The current leader and the revision that answer was read at. A
+ /// standby anchors its watch on that revision so the leader cannot
+ /// disappear unobserved in the gap before the watch attaches.
+ pub async fn get_leader_with_revision(&self) -> Result<(Option<LeaderInfo>, i64)> {
+ count_call("get_leader_with_revision");
+ let key = self.key(StoreKey::Leader);
+ Ok(self.inner.get_with_revision(&key).await?)
+ }
+
+ /// Watch the leader key alone, from `start_revision` inclusive.
+ pub async fn watch_leader_from(&self, start_revision: i64) -> Result<WatchStream> {
+ count_call("watch_leader_from");
+ let key = self.key(StoreKey::Leader);
+ Ok(self.inner.watch_key_from(&key, start_revision).await?)
+ }
+
// ── Lease operations ────────────────────────────────────────
pub async fn grant_lease(&self, ttl: i64) -> Result<i64> {
+ count_call("grant_lease");
Ok(self.inner.grant_lease(ttl).await?)
}
@@ -716,16 +961,19 @@ impl PersonhogStore {
&self,
lease_id: i64,
) -> Result<(etcd_client::LeaseKeeper, etcd_client::LeaseKeepAliveStream)> {
+ count_call("keep_alive");
Ok(self.inner.keep_alive(lease_id).await?)
}
pub async fn revoke_lease(&self, lease_id: i64) -> Result<()> {
+ count_call("revoke_lease");
Ok(self.inner.revoke_lease(lease_id).await?)
}
// ── Config operations ───────────────────────────────────────
pub async fn get_total_partitions(&self) -> Result<u32> {
+ count_call("get_total_partitions");
let key = self.key(StoreKey::TotalPartitions);
let bytes = self
.inner
diff --git a/rust/personhog-coordination/src/types.rs b/rust/personhog-coordination/src/types.rs
index de33c738b5ec..011c43a17e89 100644
--- a/rust/personhog-coordination/src/types.rs
+++ b/rust/personhog-coordination/src/types.rs
@@ -153,8 +153,24 @@ pub struct HandoffState {
/// falls back to requiring every live router. `Some([])` is a real
/// snapshot — zero routers were registered at creation — and
/// requires nobody.
+ /// Carried by records written before the membership moved into its
+ /// own key, and read for those. One current path still writes it: a
+ /// reaffirm, which states an empty membership directly rather than
+ /// minting a record no handoff would ever resolve. Nothing reads that
+ /// value — a reaffirm is created at `Complete`, past every quorum
+ /// check — but the field is written, so treat "absent" rather than
+ /// "never written" as the thing this can be relied on for.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub freeze_quorum: Option<Vec<String>>,
+ /// The id of the record holding this handoff's quorum membership,
+ /// under `{prefix}freeze_quorums/{id}`. A plan's handoffs share one
+ /// membership; inlined, it wrote the router fleet once per
+ /// partition and exceeded etcd's request limit at fleet scale. An
+ /// id that no longer resolves falls back to requiring every live
+ /// router — the stricter answer, so a lost record can only delay a
+ /// handoff, never advance one early.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub freeze_quorum_ref: Option<String>,
/// Millisecond creation time. `started_at` (seconds) predates it and
/// stays authoritative for the cancellation deadline — changing that
/// field's units mid-roll would make old records' ages read as
@@ -380,6 +396,7 @@ mod tests {
started_at: 1700000000,
handoff_id: "1700000000000-0".to_string(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
@@ -399,6 +416,7 @@ mod tests {
started_at: 1700000000,
handoff_id: "1700000000000-0".to_string(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
diff --git a/rust/personhog-coordination/src/util.rs b/rust/personhog-coordination/src/util.rs
index f48ee2df5b4f..1d8f69377edd 100644
--- a/rust/personhog-coordination/src/util.rs
+++ b/rust/personhog-coordination/src/util.rs
@@ -24,21 +24,14 @@ 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.
+/// Record one supervisor-level failure against the consecutive budget;
+/// returns `false` when it is exhausted. Progress resets the count
+/// first, and INVARIANT: progress means *applied* work (a completed
+/// convergence, an applied snapshot or event) — never a read that
+/// changed nothing, which stays available in exactly the wedges the
+/// budget exists for. Measured rather than time-based, because a
+/// "healthy after N seconds" threshold exempts every failure detector
+/// slower than N.
pub(crate) fn note_run_failure(
consecutive: &mut u32,
progress: &AtomicBool,
@@ -68,6 +61,31 @@ pub(crate) fn note_run_failure(
*consecutive < budget
}
+/// Log and count a coordination-run failure for a component with no
+/// budget to spend. The coordinator is the one such component: it fails
+/// over to a peer for free, a restart cannot mend an unwell etcd, and
+/// its process also serves person writes and strong reads — so it
+/// retries indefinitely and surfaces every failure.
+pub(crate) fn record_run_failure(
+ component: &'static str,
+ name: &str,
+ consecutive: u32,
+ err: &Error,
+) {
+ counter!(
+ "personhog_coordination_run_restarts_total",
+ "component" => component
+ )
+ .increment(1);
+ tracing::warn!(
+ component,
+ name,
+ error = %err,
+ consecutive,
+ "coordination run failed; retrying while the data plane keeps serving"
+ );
+}
+
/// 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
@@ -174,6 +192,11 @@ pub async fn run_lease_keepalive(
// never overstates how much lease is left. Anchoring at the
// response would credit the round-trip delay to the lease.
let sent = Instant::now();
+ // Renewals never pass through the store, so without this the
+ // fleet's highest-rate etcd call is absent from both the call
+ // attribution and the op-duration histogram — and after this
+ // crate stopped candidates polling the election, renewals are
+ // what is left at the top.
let round = async {
keeper.keep_alive().await?;
match stream.message().await? {
@@ -185,12 +208,24 @@ pub async fn run_lease_keepalive(
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)
- ))),
+ let outcome = {
+ // Scoped to the round alone. A timer living to the end of
+ // the iteration would drop after the pacing sleep below
+ // and record that instead — the interval, every time,
+ // whatever etcd actually did. The round is abandoned at
+ // `left.min(interval)` either way, so this measures
+ // renewal latency up to that bound and cannot show one
+ // beyond it; the margin, not this histogram, is what
+ // catches those.
+ crate::store::count_call("keep_alive_renewal");
+ let _renewal = assignment_coordination::store::OpTimer::new("keep_alive_renewal");
+ 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) => {
@@ -243,6 +278,45 @@ pub async fn run_lease_keepalive(
}
}
+/// The watch responses a live watcher can still deliver on. etcd
+/// cancels a watcher with an ordinary response and delivers nothing to
+/// it afterwards, so a loop that keeps awaiting is parked forever at
+/// reconcile-tick latency with no error; surfacing the cancel as an
+/// error routes it into the same retry that heals a broken stream.
+pub(crate) fn live_watch_response(
+ resp: Option<etcd_client::WatchResponse>,
+ what: &str,
+) -> Result<etcd_client::WatchResponse> {
+ let resp = resp.ok_or_else(|| Error::invalid_state(format!("{what} watch stream ended")))?;
+ if resp.canceled() {
+ return Err(Error::invalid_state(format!(
+ "{what} watcher cancelled by etcd (reason: {:?}, compact_revision: {})",
+ resp.cancel_reason(),
+ resp.compact_revision(),
+ )));
+ }
+ Ok(resp)
+}
+
+/// Count one resolution that found no record — not one record lost: a
+/// single missing record resolves once per frozen partition per pass,
+/// so read it as a rate (how much work is degraded to the fallback),
+/// never as a population.
+pub fn record_unresolved_freeze_quorum() {
+ metrics::counter!("personhog_coordination_unresolved_freeze_quorums_total").increment(1);
+}
+
+/// Count a handoff watch event by what this pod did with it. An event
+/// the pod could not read must not land in `skipped`, or a fleet whose
+/// records this binary cannot parse reads as scoping working perfectly.
+pub fn record_handoff_event_disposition(disposition: &'static str) {
+ metrics::counter!(
+ "personhog_coordination_handoff_events_total",
+ "disposition" => disposition
+ )
+ .increment(1);
+}
+
/// Records how long a handoff phase write took to reach this observer's
/// watch stream. Only the non-terminal phases are recorded — those are
/// the writes whose propagation gates protocol progress, while Complete
@@ -292,14 +366,138 @@ pub fn preregister_coordinator_metrics() {
.increment(0);
}
metrics::counter!("personhog_coordination_elections_won_total").increment(0);
- metrics::counter!("personhog_coordination_partition_releases_total").increment(0);
+ metrics::counter!("personhog_coordination_election_campaigns_total").increment(0);
+ metrics::counter!("personhog_coordination_abdications_total").increment(0);
+ metrics::counter!("personhog_coordination_election_observation_failures_total").increment(0);
+ metrics::counter!("personhog_coordination_election_watch_interruptions_total").increment(0);
+ for stage in ["list", "delete"] {
+ metrics::counter!(
+ "personhog_coordination_freeze_quorum_sweep_failures_total",
+ "stage" => stage
+ )
+ .increment(0);
+ }
+ metrics::counter!("personhog_coordination_freeze_quorums_collected_total").increment(0);
+ // The plan histograms are deliberately absent here. A counter
+ // preregisters for free, but a histogram has no zero-observation
+ // form: recording one would put a zero-byte plan into the very
+ // series that exists to say how large plans get. They appear with
+ // the first plan instead, and the first plan is not the one anybody
+ // is watching for.
+ metrics::counter!("personhog_coordination_store_calls_total", "site" => "apply_plan")
+ .increment(0);
+ // The coordinator's escalation story spans four series — this one
+ // for terms that failed outright, `abdications_total` for terms
+ // that lost leadership (a lease that cannot renew lands there, not
+ // here, and it is the common bad ending under etcd degradation),
+ // `election_observation_failures_total` for a candidate that
+ // cannot read the election at all (a dark etcd), and
+ // `election_watch_interruptions_total` for watches etcd cancels or
+ // drops (a flapping etcd lands only there, with reads still
+ // passing). Failures arrive in correlated bursts with quiet days
+ // between — exactly the delta a lazily-registered counter loses.
+ metrics::counter!(
+ "personhog_coordination_run_restarts_total",
+ "component" => "coordinator"
+ )
+ .increment(0);
+ metrics::counter!("personhog_coordination_unresolved_freeze_quorums_total").increment(0);
+ // Phase transitions fire only while handoffs are moving — the
+ // flagship deploy-burst series, and the one most exposed to losing
+ // its first delta. Freezing advances to Draining, or straight to
+ // Warming when there is no old owner to drain.
+ for (from, to) in [
+ ("freezing", "draining"),
+ ("freezing", "warming"),
+ ("draining", "warming"),
+ ("warming", "complete"),
+ ] {
+ metrics::counter!(
+ "personhog_coordination_handoff_transitions_total",
+ "from" => from,
+ "to" => to,
+ )
+ .increment(0);
+ }
+ // Burst-shaped: these fire only during a mass cancellation, which is
+ // exactly the delta a lazily-registered series loses.
+ for reason in ["phase_deadline", "dead_new_owner"] {
+ metrics::counter!("personhog_coordination_handoffs_cancelled_total", "reason" => reason)
+ .increment(0);
+ }
+ for disposition in ["successor", "reaffirm", "delete"] {
+ metrics::counter!(
+ "personhog_coordination_handoffs_replaced_total",
+ "disposition" => disposition
+ )
+ .increment(0);
+ }
metrics::gauge!("personhog_coordination_generation_hold_pods").set(0.0);
metrics::gauge!("personhog_coordination_generation_capped_pods").set(0.0);
}
+/// Same as [`preregister_coordinator_metrics`], for the counters a
+/// writer pod's coordination layer emits.
+pub fn preregister_pod_metrics() {
+ // Emitted by the pod, so it belongs here rather than beside the
+ // coordinator's counters — they run in different binaries, and a
+ // series registered where nothing emits it is a permanent zero.
+ metrics::counter!("personhog_coordination_partition_releases_total").increment(0);
+ metrics::counter!(
+ "personhog_coordination_run_restarts_total",
+ "component" => "pod"
+ )
+ .increment(0);
+ metrics::counter!(
+ "personhog_coordination_keepalive_retries_total",
+ "component" => "pod"
+ )
+ .increment(0);
+ for disposition in ["converged", "skipped", "unreadable"] {
+ metrics::counter!(
+ "personhog_coordination_handoff_events_total",
+ "disposition" => disposition
+ )
+ .increment(0);
+ }
+ // All burst-shaped: they fire during etcd blips and deploy churn
+ // with quiet days between, which is when a lazily-registered series
+ // loses its first delta.
+ metrics::counter!(
+ "personhog_coordination_reconcile_failures_total",
+ "component" => "pod"
+ )
+ .increment(0);
+ for outcome in ["run", "suppressed"] {
+ metrics::counter!(
+ "personhog_coordination_repair_passes_total",
+ "outcome" => outcome
+ )
+ .increment(0);
+ }
+ metrics::counter!("personhog_coordination_registration_deleted_total").increment(0);
+}
+
/// Same as [`preregister_coordinator_metrics`], for the counters the
/// router's coordination layer emits.
pub fn preregister_router_coordination_metrics() {
+ for component in ["router", "coordinator"] {
+ metrics::counter!(
+ "personhog_coordination_keepalive_retries_total",
+ "component" => component
+ )
+ .increment(0);
+ }
+ metrics::counter!(
+ "personhog_coordination_run_restarts_total",
+ "component" => "router"
+ )
+ .increment(0);
+ metrics::counter!(
+ "personhog_coordination_reconcile_failures_total",
+ "component" => "router"
+ )
+ .increment(0);
for outcome in ["revoked", "revoke_failed"] {
metrics::counter!(
"personhog_coordination_router_deregistered_total",
@@ -307,13 +505,77 @@ pub fn preregister_router_coordination_metrics() {
)
.increment(0);
}
+ metrics::counter!("personhog_coordination_freeze_acks_written_total").increment(0);
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
+ use std::sync::atomic::{AtomicBool, Ordering};
+
+ use super::{new_handoff_id, note_run_failure};
+ use crate::error::Error;
+
+ /// Losing the election lease ends a leadership term but says nothing
+ /// about this process's health — a successor takes over and
+ /// reconciles. The coordinator's run loop tells the two apart on
+ /// this predicate: an abdication is paced and counted, an error is
+ /// paced and reported, and neither ends the process.
+ #[test]
+ fn an_abdication_is_not_a_process_failure() {
+ assert!(Error::leadership_lost().is_leadership_lost());
+ assert!(!Error::invalid_state("etcd unreachable").is_leadership_lost());
+ assert!(!Error::NotFound("handoffs/7".to_string()).is_leadership_lost());
+ }
- use super::new_handoff_id;
+ /// Applied work has to clear the count, or sporadic errors spread
+ /// over hours add up to a restart of a healthy component. This is
+ /// the pod's and router's supervisor — both serve continuously, so a
+ /// stretch with no applied work is itself a symptom. The coordinator
+ /// does not use it: it idles legitimately, and it never gives up.
+ #[test]
+ fn applied_work_clears_the_failure_count() {
+ let progress = AtomicBool::new(false);
+ let err = Error::invalid_state("etcd unreachable");
+ let mut consecutive = 0u32;
+
+ for attempt in 1..3 {
+ assert!(
+ note_run_failure(&mut consecutive, &progress, 3, "pod", "p", &err),
+ "attempt {attempt} is within budget"
+ );
+ }
+
+ progress.store(true, Ordering::SeqCst);
+ assert!(
+ note_run_failure(&mut consecutive, &progress, 3, "pod", "p", &err),
+ "applied work resets the count"
+ );
+ assert_eq!(consecutive, 1);
+ }
+
+ /// And it must escalate when nothing succeeds in between — this is
+ /// the wedge it exists for: winning the election and then failing the
+ /// coordination loop returns an error every single time.
+ #[test]
+ fn an_unbroken_run_of_failures_exhausts_the_budget() {
+ let progress = AtomicBool::new(false);
+ let err = Error::invalid_state("list_handoffs failed");
+ let mut consecutive = 0u32;
+
+ assert!(note_run_failure(
+ &mut consecutive,
+ &progress,
+ 2,
+ "pod",
+ "p",
+ &err
+ ));
+ assert!(
+ !note_run_failure(&mut consecutive, &progress, 2, "pod", "p", &err),
+ "the budget is spent, so the caller must stop retrying"
+ );
+ }
/// Quorum correlation and cancellation detection hang off id
/// uniqueness; ids minted in the same instant (a handoff cancelled
diff --git a/rust/personhog-coordination/tests/common/mod.rs b/rust/personhog-coordination/tests/common/mod.rs
index b9498bbe9ab3..67f5b84ce420 100644
--- a/rust/personhog-coordination/tests/common/mod.rs
+++ b/rust/personhog-coordination/tests/common/mod.rs
@@ -145,7 +145,11 @@ pub fn start_coordinator_with_deadline(
name: name.to_string(),
leader_lease_ttl,
keepalive_interval: Duration::from_secs(keepalive_secs),
- election_retry_interval: Duration::from_secs(1),
+ // Short enough that a failover never waits on the leader-key
+ // watch alone.
+ standby_poll_interval: Duration::from_millis(500),
+ run_retry_backoff: Duration::from_millis(10),
+ backoff_decay_window: Duration::from_secs(300),
rebalance_debounce_interval: Duration::from_millis(100),
reconcile_interval: Duration::from_millis(500),
// Callers default this to a day: these tests deliberately
@@ -160,7 +164,10 @@ pub fn start_coordinator_with_deadline(
None,
);
let token = cancel.child_token();
- tokio::spawn(async move { coordinator.run(token).await })
+ tokio::spawn(async move {
+ coordinator.run(token).await;
+ Ok(())
+ })
}
pub struct PodHandles {
@@ -686,7 +693,10 @@ pub fn start_coordinator_reconcile_parked(
None,
);
let token = cancel.child_token();
- tokio::spawn(async move { coordinator.run(token).await })
+ tokio::spawn(async move {
+ coordinator.run(token).await;
+ Ok(())
+ })
}
pub fn start_coordinator_with_debounce(
@@ -705,7 +715,10 @@ pub fn start_coordinator_with_debounce(
None,
);
let token = cancel.child_token();
- tokio::spawn(async move { coordinator.run(token).await })
+ tokio::spawn(async move {
+ coordinator.run(token).await;
+ Ok(())
+ })
}
pub fn start_pod_slow(
@@ -801,14 +814,27 @@ pub async fn store_at(endpoint: &str, prefix: &str) -> Arc<PersonhogStore> {
/// 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.
+/// error; reconnects still succeed), `set_blackholed(true)` also kills
+/// new connections on accept, so recovery is impossible until it is
+/// lifted, and `set_hanging(true)` accepts them and then does nothing.
+///
+/// The three are different failures, and the difference matters. Severed
+/// and blackholed both fail *fast* — the client gets a reset and an error
+/// it can act on. Hanging is the silent partition: the connection is
+/// established, the request goes out, and no answer ever comes, so a
+/// caller with no timeout of its own waits for the transport rather than
+/// for anything it chose.
pub struct FlakyProxy {
/// Endpoint URL to hand to `store_at`.
pub endpoint: String,
conns: Arc<StdMutex<Vec<tokio::task::JoinHandle<()>>>>,
+ /// Accepted-and-parked sockets, held open so the peer sees a live
+ /// connection that never answers. Dropping them would turn the hang
+ /// into a reset, which is the failure this mode exists to not be.
+ parked: Arc<StdMutex<Vec<TcpStream>>>,
blackholed: Arc<AtomicBool>,
+ hanging: Arc<AtomicBool>,
+ accepted: Arc<AtomicUsize>,
listener: tokio::task::JoinHandle<()>,
}
@@ -818,18 +844,32 @@ impl FlakyProxy {
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 parked: Arc<StdMutex<Vec<TcpStream>>> = Arc::new(StdMutex::new(Vec::new()));
let blackholed = Arc::new(AtomicBool::new(false));
+ let hanging = Arc::new(AtomicBool::new(false));
+ let accepted = Arc::new(AtomicUsize::new(0));
+ let accepted_bg = Arc::clone(&accepted);
let conns_bg = Arc::clone(&conns);
+ let parked_bg = Arc::clone(&parked);
let blackholed_bg = Arc::clone(&blackholed);
+ let hanging_bg = Arc::clone(&hanging);
let listener = tokio::spawn(async move {
loop {
let Ok((mut client, _)) = socket.accept().await else {
return;
};
+ accepted_bg.fetch_add(1, Ordering::SeqCst);
if blackholed_bg.load(Ordering::SeqCst) {
drop(client);
continue;
}
+ if hanging_bg.load(Ordering::SeqCst) {
+ // Held rather than dropped: the peer must see a
+ // connection that is open and silent, not one that
+ // was refused.
+ parked_bg.lock().unwrap().push(client);
+ continue;
+ }
let pump = tokio::spawn(async move {
let Ok(mut upstream_conn) = TcpStream::connect(upstream).await else {
return;
@@ -842,11 +882,24 @@ impl FlakyProxy {
Self {
endpoint,
conns,
+ parked,
blackholed,
+ hanging,
+ accepted,
listener,
}
}
+ /// How many connections the proxy has accepted since it started.
+ ///
+ /// A blackholed proxy drops each one immediately, so a client that
+ /// keeps retrying keeps climbing this — which is what makes "it is
+ /// still trying" a fact a test can wait on rather than a duration it
+ /// hopes is long enough.
+ pub fn accepted(&self) -> usize {
+ self.accepted.load(Ordering::SeqCst)
+ }
+
/// Break every live connection; the streams running over them error
/// out. New connections still succeed unless blackholed.
pub fn sever(&self) {
@@ -858,12 +911,23 @@ impl FlakyProxy {
pub fn set_blackholed(&self, blackholed: bool) {
self.blackholed.store(blackholed, Ordering::SeqCst);
}
+
+ /// Accept new connections and then answer nothing on them.
+ ///
+ /// The silent partition: a caller that sets no timeout of its own
+ /// waits for the transport to give up rather than for a deadline it
+ /// chose, which is what makes an unraced etcd call outlast the budget
+ /// its component was given.
+ pub fn set_hanging(&self, hanging: bool) {
+ self.hanging.store(hanging, Ordering::SeqCst);
+ }
}
impl Drop for FlakyProxy {
fn drop(&mut self) {
self.listener.abort();
self.sever();
+ self.parked.lock().unwrap().clear();
}
}
diff --git a/rust/personhog-coordination/tests/integration.rs b/rust/personhog-coordination/tests/integration.rs
index e9aa6e40928e..9786fefae333 100644
--- a/rust/personhog-coordination/tests/integration.rs
+++ b/rust/personhog-coordination/tests/integration.rs
@@ -1420,6 +1420,7 @@ async fn a_dead_new_owner_handoff_is_reaffirmed_to_the_current_owner() {
started_at: 0,
handoff_id: String::new(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
@@ -1550,6 +1551,7 @@ async fn stale_handoff_address_never_overwrites_a_fresher_registration() {
started_at: 0,
handoff_id: "h-stale-addr".to_string(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
})
@@ -1774,6 +1776,7 @@ async fn late_joining_router_during_warming_begins_stash() {
started_at: 0,
handoff_id: String::new(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
@@ -1841,6 +1844,7 @@ async fn dead_old_owner_in_freezing_advances_to_completion() {
started_at: 0,
handoff_id: String::new(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
@@ -1896,6 +1900,7 @@ async fn late_joining_router_during_freezing_acks_and_stashes() {
started_at: 0,
handoff_id: String::new(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
@@ -1978,6 +1983,7 @@ async fn a_dead_new_owner_handoff_in_warming_is_reaffirmed() {
started_at: 0,
handoff_id: String::new(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
@@ -2079,6 +2085,7 @@ async fn reconcile_advances_warming_with_pre_staged_warmed_ack() {
started_at: 0,
handoff_id: String::new(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
@@ -2162,6 +2169,7 @@ async fn draining_old_owner_blocks_phase_advance() {
started_at: 0,
handoff_id: String::new(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
@@ -2267,6 +2275,7 @@ async fn draining_old_owner_does_not_trigger_cleanup() {
started_at: 0,
handoff_id: String::new(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
@@ -2377,6 +2386,7 @@ async fn a_handoff_that_can_never_reach_quorum_is_cancelled() {
.as_secs() as i64,
handoff_id: "wedged-handoff".to_string(),
freeze_quorum: Some(vec!["silent-router".to_string()]),
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
})
@@ -2462,6 +2472,7 @@ async fn freezing_blocks_until_routers_ack_before_draining() {
started_at: 0,
handoff_id: String::new(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
@@ -2562,6 +2573,7 @@ async fn initial_assignment_skips_draining_phase() {
started_at: 0,
handoff_id: String::new(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
@@ -2624,6 +2636,7 @@ async fn dead_old_owner_in_draining_recovers() {
started_at: 0,
handoff_id: String::new(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
@@ -2726,6 +2739,7 @@ async fn reconcile_advances_draining_with_pre_staged_drained_ack() {
started_at: 0,
handoff_id: String::new(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
@@ -2789,6 +2803,7 @@ async fn late_joining_router_during_draining_begins_stash_no_ack() {
started_at: 0,
handoff_id: String::new(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
@@ -2876,6 +2891,7 @@ async fn a_dead_new_owner_handoff_in_draining_is_reaffirmed() {
started_at: 0,
handoff_id: String::new(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
@@ -3125,6 +3141,7 @@ async fn conflicting_plan_cannot_replace_an_in_flight_handoff() {
started_at: 0,
handoff_id: "first".to_string(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
@@ -3144,6 +3161,7 @@ async fn conflicting_plan_cannot_replace_an_in_flight_handoff() {
started_at: 0,
handoff_id: "second".to_string(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
@@ -3195,6 +3213,7 @@ async fn stale_plan_is_rejected_when_the_assignment_moved() {
started_at: 0,
handoff_id: id.to_string(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
@@ -3275,6 +3294,7 @@ async fn fresh_plan_is_rejected_when_an_assignment_appeared() {
started_at: 0,
handoff_id: id.to_string(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
diff --git a/rust/personhog-coordination/tests/k3s_integration.rs b/rust/personhog-coordination/tests/k3s_integration.rs
index 9687cc22fe74..cc41250ef4fb 100644
--- a/rust/personhog-coordination/tests/k3s_integration.rs
+++ b/rust/personhog-coordination/tests/k3s_integration.rs
@@ -489,7 +489,10 @@ fn start_coordinator_k8s(
k8s_awareness,
);
let token = cancel.child_token();
- tokio::spawn(async move { coordinator.run(token).await })
+ tokio::spawn(async move {
+ coordinator.run(token).await;
+ Ok(())
+ })
}
// ── Tests ────────────────────────────────────────────────
diff --git a/rust/personhog-coordination/tests/protocol_hardening.rs b/rust/personhog-coordination/tests/protocol_hardening.rs
index d64d41324df4..9b329ce87ddc 100644
--- a/rust/personhog-coordination/tests/protocol_hardening.rs
+++ b/rust/personhog-coordination/tests/protocol_hardening.rs
@@ -7,10 +7,11 @@
//! All tests run against a real etcd at localhost:2379 with per-test key
//! prefixes, matching the conventions in `integration.rs`.
+use etcd_client::EventType;
use personhog_coordination::authority::AuthorityClock;
mod common;
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use std::future::pending;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
@@ -30,7 +31,9 @@ use common::{
FlakyProxy, HandoffEvent, MockCutoverHandler, MockHandoffHandler, ETCD_ENDPOINT, POLL_INTERVAL,
WAIT_TIMEOUT,
};
+use personhog_coordination::coordinator::{Coordinator, CoordinatorConfig};
use personhog_coordination::error::Result;
+use personhog_coordination::protocol::freeze_quorum_met;
use personhog_coordination::routing_table::{RoutingTable, RoutingTableConfig, StashHandler};
use personhog_coordination::store::PersonhogStore;
use personhog_coordination::strategy::StickyBalancedStrategy;
@@ -56,6 +59,7 @@ async fn put_handoff(
started_at: 0,
handoff_id: format!("test-handoff-{partition}"),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
@@ -2594,6 +2598,7 @@ async fn put_handoff_with_id(
started_at: 0,
handoff_id: handoff_id.to_string(),
freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
new_owner_address: None,
@@ -4338,3 +4343,1287 @@ async fn a_pending_new_owner_is_hinted_but_not_warmed() {
cancel.cancel();
}
+
+/// A standby waits on the leader key rather than campaigning at its
+/// retry interval — a campaign costs etcd writes per candidate per
+/// retry, so standing by must cost nothing until the key goes away.
+///
+/// The fallback re-read is set beyond the test's timeouts and a
+/// successor reclaims the key instantly, so only the delete event can
+/// end the wait. The read-to-attach gap is pinned separately by
+/// `a_leader_that_goes_between_the_read_and_the_watch_is_still_delivered`.
+#[tokio::test]
+async fn a_standby_waits_on_the_leader_key_rather_than_campaigning() {
+ let prefix = format!("/test-standby-watch-{}/", uuid::Uuid::new_v4());
+ let store = store_at(ETCD_ENDPOINT, &prefix).await;
+
+ let standby = Arc::new(Coordinator::new(
+ Arc::clone(&store),
+ CoordinatorConfig {
+ name: "standby".to_string(),
+ standby_poll_interval: Duration::from_secs(600),
+ ..Default::default()
+ },
+ Arc::new(StickyBalancedStrategy),
+ None,
+ ));
+ let cancel = CancellationToken::new();
+
+ // With no leader recorded, the election is open and the wait is over
+ // before it starts.
+ tokio::time::timeout(WAIT_TIMEOUT, standby.await_election_opening(&cancel))
+ .await
+ .expect("an unheld election must not make a candidate wait")
+ .expect("reading the leader key must succeed");
+
+ // The lease only serves to take the key. The test drives the key
+ // directly from there, because revoking the lease can only produce a
+ // delete, and the first thing to prove is that a write which is not
+ // a delete leaves the candidate parked. Nothing renews it, so its
+ // TTL sits far above the assertion window: an expiry mid-test would
+ // deliver the delete this test exists to prove is the only waker.
+ let lease_id = store.grant_lease(60).await.unwrap();
+ assert!(
+ store
+ .try_acquire_leadership("incumbent", lease_id)
+ .await
+ .unwrap(),
+ "the test's own leader must take the key"
+ );
+
+ // An incumbent holds it, so the candidate parks. The wait runs as a
+ // task from here on, with the fallback re-read set past every
+ // timeout in this test, so nothing but the delete can end it.
+ let waiting = {
+ let standby = Arc::clone(&standby);
+ let cancel = cancel.clone();
+ tokio::spawn(async move { standby.await_election_opening(&cancel).await })
+ };
+ // Generous, because the point of the window is to let the wait
+ // reach its read and park: a runner slow enough to still be reading
+ // when the revoke lands would see the read return no leader and
+ // finish for the wrong reason.
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ assert!(
+ !waiting.is_finished(),
+ "a candidate must not enter an election another coordinator holds"
+ );
+
+ // A write to the key that is not a deletion must not end the wait.
+ // Overwriting it in place produces a Put and no Delete, which is
+ // exactly what a predicate matching the wrong event type would
+ // accept. No coordinator writes the key that way — campaigning is a
+ // create, guarded on the key being absent — so the event is built
+ // here rather than provoked, to hold the discriminator itself.
+ let leader_key = format!("{prefix}coordinator/leader");
+ let mut raw = etcd_client::Client::connect([ETCD_ENDPOINT], None)
+ .await
+ .expect("connect raw etcd client");
+ raw.put(
+ leader_key.clone(),
+ r#"{"holder":"incumbent","lease_id":0}"#,
+ None,
+ )
+ .await
+ .expect("overwrite the leader key");
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ assert!(
+ !waiting.is_finished(),
+ "a write that is not a deletion must not open the election"
+ );
+
+ // Now the deletion, with a successor taking the key back at once so
+ // a re-read can never be what ends the wait — only the delete event
+ // can. etcd rejects a delete and a put of one key in a single
+ // transaction, so a one-round-trip window remains; a defect large
+ // enough to matter here needs seconds, not that.
+ raw.delete(leader_key, None)
+ .await
+ .expect("delete the leader key");
+ let successor_lease = store.grant_lease(60).await.expect("grant lease");
+ assert!(
+ store
+ .try_acquire_leadership("successor", successor_lease)
+ .await
+ .expect("successor campaign"),
+ "the successor must take the key back"
+ );
+ tokio::time::timeout(WAIT_TIMEOUT, waiting)
+ .await
+ .expect("the watch must wake the candidate when the leader goes")
+ .expect("the waiting task must not panic")
+ .expect("watching the leader key must succeed");
+}
+
+/// A handoff replaced in place — cancelled and re-issued in one
+/// transaction — must still reach a pod the successor no longer names.
+/// The old owner sees a single put naming two other pods; only what it
+/// still holds locally says the fence should come off, and a pod that
+/// skipped the event would reject writes until the reconcile tick.
+///
+/// Pins the local-state disjunct as a whole (warm and fence held
+/// together); the individual terms are held by
+/// `restarted_old_owner_serves_again_after_handoff_cancelled` and
+/// `pod_releases_partition_when_cancelled_handoff_leaves_it_unassigned`.
+#[tokio::test]
+async fn a_replaced_handoff_reaches_the_old_owner_it_no_longer_names() {
+ let store = test_store("handoff-replaced-old-owner").await;
+ let cancel = CancellationToken::new();
+
+ let pod = start_pod(Arc::clone(&store), "replaced-pod-a", cancel.clone());
+
+ let check_store = Arc::clone(&store);
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let store = Arc::clone(&check_store);
+ async move {
+ store
+ .list_pods()
+ .await
+ .map(|pods| pods.iter().any(|p| p.pod_name == "replaced-pod-a"))
+ .unwrap_or(false)
+ }
+ })
+ .await;
+
+ // Take ownership of partition 0 through the real acquisition path, so
+ // the assignment names this pod.
+ put_handoff(&store, 0, None, "replaced-pod-a", HandoffPhase::Warming).await;
+ wait_for_event(&pod.events, HandoffEvent::Warmed(0)).await;
+ let warming = store
+ .get_handoff(0)
+ .await
+ .expect("get handoff")
+ .expect("handoff exists");
+ assert!(
+ store
+ .complete_handoff(0, &warming.handoff_id, HandoffPhase::Warming)
+ .await
+ .expect("complete"),
+ "complete_handoff must succeed"
+ );
+ store.delete_handoff(0).await.expect("cleanup");
+
+ // Move the partition away, leaving this pod drained and fenced.
+ put_handoff(
+ &store,
+ 0,
+ Some("replaced-pod-a"),
+ "replaced-pod-b",
+ HandoffPhase::Draining,
+ )
+ .await;
+ wait_for_event(&pod.events, HandoffEvent::Drained(0)).await;
+
+ // The successor is written over the same key and names neither this
+ // pod nor anything it holds. The assignment still names it, so it
+ // must resume rather than stay fenced.
+ put_handoff(
+ &store,
+ 0,
+ Some("replaced-pod-b"),
+ "replaced-pod-c",
+ HandoffPhase::Freezing,
+ )
+ .await;
+ wait_for_event(&pod.events, HandoffEvent::Resumed(0)).await;
+
+ cancel.cancel();
+}
+
+/// A plan records its freeze-quorum membership once and points its
+/// handoffs at it, rather than writing the router fleet into each one.
+///
+/// Inlining made a handoff record grow with the fleet and a plan
+/// transaction grow with the fleet times the partition count. At a few
+/// hundred of each that exceeded etcd's maximum request size, so the
+/// transaction was rejected and no partition moved at all. The same
+/// bytes were paid again by every list of handoffs.
+///
+/// The sweep is the other half: membership records outlive nothing, so
+/// without collection they accumulate one per plan forever.
+#[tokio::test]
+async fn a_plan_records_its_freeze_quorum_once_and_collects_it_after() {
+ let store = test_store("freeze-quorum-by-reference").await;
+ store.set_total_partitions(2).await.expect("set partitions");
+ let cancel = CancellationToken::new();
+
+ // A registered router that never acks parks every handoff in
+ // Freezing, so the records under test stay put while the test reads
+ // them.
+ let lease_id = store.grant_lease(60).await.expect("grant lease");
+ store
+ .register_router(
+ &RegisteredRouter {
+ router_name: "fqr-router".to_string(),
+ registered_at: 0,
+ last_heartbeat: 0,
+ },
+ lease_id,
+ )
+ .await
+ .expect("register router");
+
+ let _pod = start_pod(Arc::clone(&store), "fqr-pod", cancel.clone());
+ let _coordinator = start_coordinator(
+ Arc::clone(&store),
+ Arc::new(StickyBalancedStrategy),
+ cancel.clone(),
+ );
+
+ let check = Arc::clone(&store);
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let store = Arc::clone(&check);
+ async move {
+ store
+ .list_handoffs()
+ .await
+ .map(|handoffs| {
+ !handoffs.is_empty()
+ && handoffs.iter().all(|h| h.phase == HandoffPhase::Freezing)
+ })
+ .unwrap_or(false)
+ }
+ })
+ .await;
+
+ let handoffs = store.list_handoffs().await.expect("list handoffs");
+ let referenced: HashSet<String> = handoffs
+ .iter()
+ .filter_map(|h| h.freeze_quorum_ref.clone())
+ .collect();
+ assert_eq!(
+ referenced.len(),
+ 1,
+ "every handoff of one plan must point at the same membership record"
+ );
+ for handoff in &handoffs {
+ assert!(
+ handoff.freeze_quorum.is_none(),
+ "the membership must not also be written into the handoff"
+ );
+ }
+
+ let id = referenced.into_iter().next().expect("a referenced id");
+ let members = store
+ .get_freeze_quorum(&id)
+ .await
+ .expect("read membership")
+ .expect("the plan must write the record it points at");
+ assert_eq!(
+ members,
+ vec!["fqr-router".to_string()],
+ "the record must hold the routers registered when the plan ran"
+ );
+
+ // Nothing refers to it once the handoffs are gone, so the sweep on
+ // the coordinator's reconcile tick must take it.
+ for handoff in &handoffs {
+ store
+ .delete_handoff(handoff.partition)
+ .await
+ .expect("delete handoff");
+ }
+ let check = Arc::clone(&store);
+ let swept_id = id.clone();
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let store = Arc::clone(&check);
+ let id = swept_id.clone();
+ async move {
+ store
+ .get_freeze_quorum(&id)
+ .await
+ .map(|members| members.is_none())
+ .unwrap_or(false)
+ }
+ })
+ .await;
+
+ cancel.cancel();
+}
+
+/// A freeze-quorum reference that no longer resolves must read as
+/// "membership unknown", never as "membership empty".
+///
+/// The two are one `Option` apart and sit on opposite sides of the
+/// safety argument. Unknown falls back to requiring every live router,
+/// which can only delay a handoff. Empty requires nobody, which would
+/// advance a handoff out of Freezing before any router had stopped
+/// routing to the old owner — the state the freeze exists to prevent.
+#[tokio::test]
+async fn a_freeze_quorum_reference_that_is_gone_requires_every_live_router() {
+ let store = test_store("freeze-quorum-dangling-ref").await;
+
+ let mut handoff = HandoffState {
+ partition: 0,
+ old_owner: Some("pod-old".to_string()),
+ new_owner: "pod-new".to_string(),
+ new_owner_address: None,
+ phase: HandoffPhase::Freezing,
+ started_at: 0,
+ handoff_id: "handoff-dangling".to_string(),
+ freeze_quorum: None,
+ freeze_quorum_ref: Some("never-written".to_string()),
+ created_at_ms: 0,
+ phase_entered_at_ms: 0,
+ };
+
+ let quorum = store
+ .resolve_freeze_quorum(&handoff)
+ .await
+ .expect("resolving must not error");
+ assert!(
+ quorum.is_none(),
+ "a reference with no record must resolve to unknown, not to an empty membership"
+ );
+
+ let routers = [
+ RegisteredRouter {
+ router_name: "router-0".to_string(),
+ registered_at: 0,
+ last_heartbeat: 0,
+ },
+ RegisteredRouter {
+ router_name: "router-1".to_string(),
+ registered_at: 0,
+ last_heartbeat: 0,
+ },
+ ];
+ let acks = [RouterFreezeAck {
+ router_name: "router-0".to_string(),
+ partition: 0,
+ acked_at: 0,
+ acked_at_ms: 0,
+ handoff_id: handoff.handoff_id.clone(),
+ }];
+ assert!(
+ !freeze_quorum_met(&routers, &acks, &handoff, quorum.as_deref()),
+ "one ack of two live routers must not satisfy an unresolvable membership"
+ );
+
+ // An inline membership on an older record still resolves to itself.
+ handoff.freeze_quorum_ref = None;
+ handoff.freeze_quorum = Some(vec!["router-0".to_string()]);
+ let quorum = store
+ .resolve_freeze_quorum(&handoff)
+ .await
+ .expect("resolving must not error");
+ assert!(
+ freeze_quorum_met(&routers, &acks, &handoff, quorum.as_deref()),
+ "a record carrying its membership inline must still be judged by it"
+ );
+}
+
+/// A handoff cancelled while its new owner is still warming must reach
+/// that pod.
+///
+/// A new owner records its warm only once `warm_partition` returns, and
+/// it holds no fence, so for the whole replay it holds no local state
+/// for the partition — and a long warm is exactly what a deadline
+/// cancels. Deciding involvement from local state alone drops the
+/// deletion there, leaving the pod to finish a warm for a handoff that
+/// no longer exists and hold the cache until a reconcile tick notices.
+/// This pod's reconcile tick is parked, so only the event path can
+/// produce the release.
+#[tokio::test]
+async fn a_handoff_cancelled_mid_warm_reaches_the_pod_still_warming() {
+ let store = test_store("cancel-mid-warm").await;
+ let cancel = CancellationToken::new();
+
+ let pod = start_pod_gated(Arc::clone(&store), "mid-warm-pod", 4, cancel.clone());
+
+ let check = Arc::clone(&store);
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let store = Arc::clone(&check);
+ async move {
+ store
+ .list_pods()
+ .await
+ .map(|pods| pods.iter().any(|p| p.pod_name == "mid-warm-pod"))
+ .unwrap_or(false)
+ }
+ })
+ .await;
+
+ // Acquire partition 0 as the new owner of a fresh assignment. The
+ // gate is shut, so the warm parks and the pod holds nothing for the
+ // partition yet.
+ put_handoff(&store, 0, None, "mid-warm-pod", HandoffPhase::Warming).await;
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let in_flight = Arc::clone(&pod.warms_in_flight);
+ async move {
+ in_flight
+ .lock()
+ .expect("warms in flight lock poisoned")
+ .get(&0)
+ .is_some_and(|count| *count > 0)
+ }
+ })
+ .await;
+ assert!(
+ !pod.events.lock().await.contains(&HandoffEvent::Warmed(0)),
+ "the warm must still be parked at the gate"
+ );
+
+ // Cancel it out from under the warm, then let the warm finish.
+ store.delete_handoff(0).await.expect("delete handoff");
+ pod.gates.open(0);
+
+ // Nothing assigns the partition to this pod, so converging on the
+ // deletion must release what the warm installed.
+ wait_for_event(&pod.events, HandoffEvent::Released(0)).await;
+
+ cancel.cancel();
+}
+
+/// A leader that disappears between a standby's read and its watch is
+/// still delivered to that watch. Anchoring the watch at the revision
+/// the read returned replays that deletion; anchoring at "now" drops
+/// it, which looks identical in any test that lets the watch attach
+/// first.
+///
+/// Driven through the two store calls in order rather than the loop —
+/// no amount of racing the loop lands the deletion between them on
+/// demand. What this pins is the store contract the loop depends on.
+#[tokio::test]
+async fn a_leader_that_goes_between_the_read_and_the_watch_is_still_delivered() {
+ let store = test_store("standby-watch-anchor").await;
+
+ let lease_id = store.grant_lease(60).await.unwrap();
+ assert!(
+ store
+ .try_acquire_leadership("incumbent", lease_id)
+ .await
+ .unwrap(),
+ "the test's own leader must take the key"
+ );
+
+ // The read a standby makes, then the deletion, then the watch.
+ let (leader, revision) = store
+ .get_leader_with_revision()
+ .await
+ .expect("reading the leader key must succeed");
+ assert!(
+ leader.is_some(),
+ "the incumbent must be visible to the read"
+ );
+
+ store.revoke_lease(lease_id).await.unwrap();
+
+ let mut stream = store
+ .watch_leader_from(revision + 1)
+ .await
+ .expect("watching the leader key must succeed");
+
+ let delivered = tokio::time::timeout(WAIT_TIMEOUT, async {
+ loop {
+ let Ok(Some(response)) = stream.message().await else {
+ return false;
+ };
+ if response
+ .events()
+ .iter()
+ .any(|event| event.event_type() == EventType::Delete)
+ {
+ return true;
+ }
+ }
+ })
+ .await
+ .expect("the watch must deliver the deletion it missed, not wait for a new one");
+
+ assert!(
+ delivered,
+ "a watch anchored on the read's revision must replay the deletion"
+ );
+}
+
+/// The sweep must spare a membership record a live handoff refers to.
+///
+/// Its safety rests on the filter, and on reading the record ids before
+/// the handoffs so anything written in between is not a candidate. Drop
+/// the filter and the sweep deletes memberships out from under handoffs
+/// still in Freezing; each then falls back to requiring every live
+/// router, so a rebalance slows to whichever router is slowest to ack.
+///
+/// This pins the filter. The read ordering it does not pin — the window
+/// is a single round trip and the ordering lives at the call site, not
+/// in the swept function — so reversing those two reads passes here.
+#[tokio::test]
+async fn the_sweep_spares_a_membership_a_live_handoff_refers_to() {
+ let store = test_store("freeze-quorum-sweep-spares").await;
+ store.set_total_partitions(2).await.expect("set partitions");
+ let cancel = CancellationToken::new();
+
+ // A registered router that never acks parks the handoffs in
+ // Freezing, so their membership stays referenced while the sweep
+ // runs against it repeatedly.
+ let lease_id = store.grant_lease(60).await.expect("grant lease");
+ store
+ .register_router(
+ &RegisteredRouter {
+ router_name: "sweep-router".to_string(),
+ registered_at: 0,
+ last_heartbeat: 0,
+ },
+ lease_id,
+ )
+ .await
+ .expect("register router");
+
+ let _pod = start_pod(Arc::clone(&store), "sweep-pod", cancel.clone());
+ let _coordinator = start_coordinator(
+ Arc::clone(&store),
+ Arc::new(StickyBalancedStrategy),
+ cancel.clone(),
+ );
+
+ let check = Arc::clone(&store);
+ wait_for_condition_named(
+ WAIT_TIMEOUT,
+ POLL_INTERVAL,
+ "a referenced membership",
+ || {
+ let store = Arc::clone(&check);
+ async move {
+ store
+ .list_handoffs()
+ .await
+ .map(|handoffs| {
+ !handoffs.is_empty()
+ && handoffs.iter().all(|h| {
+ h.phase == HandoffPhase::Freezing && h.freeze_quorum_ref.is_some()
+ })
+ })
+ .unwrap_or(false)
+ }
+ },
+ )
+ .await;
+
+ let id = store
+ .list_handoffs()
+ .await
+ .expect("list handoffs")
+ .first()
+ .and_then(|h| h.freeze_quorum_ref.clone())
+ .expect("a referenced membership id");
+
+ // The coordinator's reconcile tick sweeps every 500ms in these
+ // tests, so this spans several passes over a record that is still
+ // referenced throughout.
+ for _ in 0..6 {
+ tokio::time::sleep(Duration::from_millis(250)).await;
+ assert!(
+ store
+ .get_freeze_quorum(&id)
+ .await
+ .expect("reading the membership must succeed")
+ .is_some(),
+ "the sweep must not collect a membership a Freezing handoff still refers to"
+ );
+ }
+
+ cancel.cancel();
+}
+
+/// A coordinator that cannot reach etcd keeps trying, and still stops
+/// promptly when asked to.
+///
+/// It has no budget: coordination fails over to a peer for free on every
+/// term ending, a restart cannot mend an unwell etcd, and the process it
+/// would take down also serves person writes and strong reads. So the
+/// contract is retry-and-report, and both halves matter — a coordinator
+/// that gave up would shed routing capacity during an etcd event, and
+/// one that ignored cancellation would hold shutdown past its grace
+/// period.
+#[tokio::test]
+async fn a_coordinator_that_cannot_reach_etcd_keeps_trying_and_still_stops_on_request() {
+ let proxy = FlakyProxy::start("127.0.0.1:2379").await;
+ let prefix = format!("/test-coordinator-retries-{}/", uuid::Uuid::new_v4());
+ // Connect while the proxy is healthy: the failure under test is a
+ // connection that dies later, not one that never opened.
+ let store = store_at(&proxy.endpoint, &prefix).await;
+
+ let coordinator = Coordinator::new(
+ Arc::clone(&store),
+ CoordinatorConfig {
+ name: "retrying-coordinator".to_string(),
+ // A candidate that cannot read the election climbs the
+ // observation ladder rather than the ending pace — it never
+ // held a term. Both bases are small so the attempt count
+ // this test needs fits inside its timeout even at the
+ // ladder's cap.
+ standby_poll_interval: Duration::from_millis(20),
+ run_retry_backoff: Duration::from_millis(1),
+ ..Default::default()
+ },
+ Arc::new(StickyBalancedStrategy),
+ None,
+ );
+ // Blackholed before the coordinator starts, so its very first
+ // campaign fails: otherwise a campaign that slips through ends its
+ // term by abdication, which is a different arm from the one under
+ // test.
+ proxy.set_blackholed(true);
+ let cancel = CancellationToken::new();
+ let token = cancel.clone();
+ let running = tokio::spawn(async move { coordinator.run(token).await });
+
+ // Counting attempts rather than waiting a fixed span, because a span
+ // cannot tell "still trying" from "gave up quietly". Each failed
+ // attempt opens one connection through the blackholed proxy, so the
+ // threshold below is twelve of them.
+ //
+ // What this pins is narrower than it looks. A blackholed etcd fails
+ // in `await_election_opening`, so these are observation failures:
+ // they never reach the ending arm and never touch its counter. A
+ // budget re-added there would leave this test green. What the twelve
+ // rules out is a coordinator that stops retrying at all — which is
+ // the half of the contract this path can speak to. The ending arm's
+ // own pacing is pinned by the unit tests over `pace_after_ending`.
+ let before = proxy.accepted();
+ wait_for_condition_named(
+ WAIT_TIMEOUT,
+ POLL_INTERVAL,
+ "more attempts than the budget that once passed this test",
+ || {
+ let seen = proxy.accepted().saturating_sub(before);
+ async move { seen >= 12 }
+ },
+ )
+ .await;
+ assert!(
+ !running.is_finished(),
+ "an unreachable etcd must not make the coordinator give up"
+ );
+
+ cancel.cancel();
+ tokio::time::timeout(WAIT_TIMEOUT, running)
+ .await
+ .expect("cancellation must stop the coordinator promptly")
+ .expect("the coordinator task must not panic");
+}
+
+/// A standby drained while etcd is unreachable stops when asked, rather
+/// than waiting out the transport.
+///
+/// Standing by means sitting inside one of two etcd calls almost all the
+/// time, and the store sets no request timeout of its own — so unraced,
+/// each runs to the transport's own bound, several times the graceful
+/// shutdown budget this component is given. The lifecycle manager then
+/// abandons it, and the work that would have followed a clean exit does
+/// not happen.
+#[tokio::test]
+async fn a_standby_stops_promptly_when_etcd_is_dark() {
+ let proxy = FlakyProxy::start("127.0.0.1:2379").await;
+ let prefix = format!("/test-standby-cancel-{}/", uuid::Uuid::new_v4());
+ // Connected and used while healthy: the failure under test is a call
+ // that cannot complete, not a store that never opened.
+ let store = store_at(&proxy.endpoint, &prefix).await;
+ let lease_id = store.grant_lease(30).await.expect("grant");
+ assert!(
+ store
+ .try_acquire_leadership("incumbent", lease_id)
+ .await
+ .expect("acquire"),
+ "the test's own leader must take the key, so the candidate stands by"
+ );
+
+ let standby = Arc::new(Coordinator::new(
+ Arc::clone(&store),
+ CoordinatorConfig {
+ name: "cancelled-standby".to_string(),
+ // Far beyond the assertion window, so a fallback re-read can
+ // never be what ends the wait.
+ standby_poll_interval: Duration::from_secs(600),
+ ..Default::default()
+ },
+ Arc::new(StickyBalancedStrategy),
+ None,
+ ));
+
+ // Live connections cut, and new ones accepted but never answered, so
+ // a caller must reconnect and then wait. A refused connection would
+ // not do: that errors promptly, and an error is not the failure under
+ // test.
+ proxy.set_hanging(true);
+ proxy.sever();
+ // The severed connection reports a broken pipe promptly the first
+ // time or two. Drain that here, so the call under test is one that
+ // opens a fresh connection and gets no answer — confirmed by a probe
+ // that fails to complete rather than by assuming a fixed number.
+ let mut hanging = false;
+ for _ in 0..5 {
+ if tokio::time::timeout(Duration::from_millis(200), store.get_leader_with_revision())
+ .await
+ .is_err()
+ {
+ hanging = true;
+ break;
+ }
+ }
+ assert!(
+ hanging,
+ "the proxy must reach a state where an etcd call gets no answer"
+ );
+
+ let cancel = CancellationToken::new();
+ let token = cancel.clone();
+ let waiting = tokio::spawn(async move { standby.await_election_opening(&token).await });
+
+ // Long enough to be inside the call, short enough that the assertion
+ // window below is still well under the transport's own bound.
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ cancel.cancel();
+ tokio::time::timeout(Duration::from_secs(2), waiting)
+ .await
+ .expect("a cancelled standby must not wait out the transport")
+ .expect("the standby task must not panic")
+ .expect("cancellation is not an error");
+}
+
+/// A standby whose watch is severed still takes an open election at
+/// the next fallback deadline.
+///
+/// A lost watch waits out its window and then re-reads rather than
+/// trusting the stream further. The proxy severs the live connection
+/// so the stream errors while etcd itself stays healthy for the
+/// re-read; a loss path that wedged on the dead stream, or surfaced it
+/// as a run failure, fails the bound here.
+#[tokio::test]
+async fn a_standby_with_a_severed_watch_still_takes_an_open_election() {
+ let proxy = FlakyProxy::start("127.0.0.1:2379").await;
+ let prefix = format!("/test-severed-watch-{}/", uuid::Uuid::new_v4());
+ let direct = store_at(ETCD_ENDPOINT, &prefix).await;
+ let watched = store_at(&proxy.endpoint, &prefix).await;
+
+ let lease_id = direct.grant_lease(60).await.expect("lease");
+ assert!(
+ direct
+ .try_acquire_leadership("incumbent", lease_id)
+ .await
+ .expect("acquire"),
+ "the test's own leader must take the key"
+ );
+
+ let standby = Coordinator::new(
+ Arc::clone(&watched),
+ CoordinatorConfig {
+ name: "severed-standby".to_string(),
+ standby_poll_interval: Duration::from_secs(2),
+ ..Default::default()
+ },
+ Arc::new(StickyBalancedStrategy),
+ None,
+ );
+ let cancel = CancellationToken::new();
+ let waiting = {
+ let cancel = cancel.clone();
+ tokio::spawn(async move { standby.await_election_opening(&cancel).await })
+ };
+
+ // Let the standby read and establish its watch, then cut it and
+ // open the election. Only a re-read can observe the opening: the
+ // severed watch is gone, and its successor is created only after
+ // the re-read below runs.
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ proxy.sever();
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ direct
+ .revoke_lease(lease_id)
+ .await
+ .expect("depose incumbent");
+
+ // The lost watch waits out its ~2s window, re-reads, and finds the
+ // election open — well inside this bound.
+ tokio::time::timeout(Duration::from_secs(5), waiting)
+ .await
+ .expect("a standby with a severed watch must re-read at its deadline")
+ .expect("the standby task must not panic")
+ .expect("an open election is not an error");
+}
+
+/// A pod asked to shut down while etcd hangs exits inside its bounds
+/// instead of waiting out the transport.
+///
+/// The graceful path's etcd calls — the drain's bookkeeping and the
+/// final revoke — are each bounded, and this is what the bounds buy: a
+/// store that accepts connections and answers nothing (the silent
+/// partition, not the fast error) cannot hold the teardown past the
+/// budget the lifecycle manager gives it. The lease TTL is 30s here so
+/// the keepalive margin (20s) cannot preempt the path under test: with
+/// the bounds the teardown finishes well before it; without them the
+/// setup call alone would hang to the margin, which is what the
+/// assertion window excludes.
+#[tokio::test]
+async fn a_pod_asked_to_stop_while_etcd_hangs_exits_inside_its_bounds() {
+ let proxy = FlakyProxy::start("127.0.0.1:2379").await;
+ let prefix = format!("/test-pod-teardown-{}/", uuid::Uuid::new_v4());
+ let store = store_at(&proxy.endpoint, &prefix).await;
+ let cancel = CancellationToken::new();
+
+ let mut pod = start_pod_with_lease_ttl(Arc::clone(&store), "teardown-pod", 30, cancel.clone());
+ let check = Arc::clone(&store);
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let store = Arc::clone(&check);
+ async move {
+ store
+ .list_pods()
+ .await
+ .map(|pods| pods.iter().any(|p| p.pod_name == "teardown-pod"))
+ .unwrap_or(false)
+ }
+ })
+ .await;
+
+ proxy.set_hanging(true);
+ proxy.sever();
+ // The severed connection errors fast once or twice before the
+ // channel re-establishes onto a parked socket; a call that fails
+ // fast never exercises the bounds under test. The pod shares this
+ // store's channel, so probing until a call hangs puts its calls in
+ // the same state.
+ let mut hanging = false;
+ for _ in 0..5 {
+ if tokio::time::timeout(Duration::from_millis(200), store.list_pods())
+ .await
+ .is_err()
+ {
+ hanging = true;
+ break;
+ }
+ }
+ assert!(hanging, "the store must reach a state where calls hang");
+ cancel.cancel();
+
+ // Setup bound (5s) + fence (prompt: nothing held) + heartbeat join
+ // (one round, ≤10s) + revoke bound (5s), with slack — far under the
+ // ~20s the unbounded setup alone would take to reach the margin.
+ let join = pod.join_handle.take().expect("join handle");
+ tokio::time::timeout(Duration::from_secs(17), join)
+ .await
+ .expect("a hung etcd must not hold the pod's shutdown past its bounds")
+ .expect("the pod task must not panic")
+ .expect("a cancelled run is not an error");
+}
+
+/// A router asked to shut down while etcd hangs exits inside its bounds.
+///
+/// The teardown's one etcd call — the deregistration revoke — is
+/// bounded, and the drain-lane joins race cancellation, so the whole
+/// exit is prompt against a store that answers nothing.
+#[tokio::test]
+async fn a_router_asked_to_stop_while_etcd_hangs_exits_inside_its_bounds() {
+ let proxy = FlakyProxy::start("127.0.0.1:2379").await;
+ let prefix = format!("/test-router-teardown-{}/", uuid::Uuid::new_v4());
+ let store = store_at(&proxy.endpoint, &prefix).await;
+ let cancel = CancellationToken::new();
+
+ let mut router =
+ start_router_with_lease_ttl(Arc::clone(&store), "teardown-router", 30, cancel.clone());
+ let check = Arc::clone(&store);
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let store = Arc::clone(&check);
+ async move {
+ store
+ .list_routers()
+ .await
+ .map(|routers| routers.iter().any(|r| r.router_name == "teardown-router"))
+ .unwrap_or(false)
+ }
+ })
+ .await;
+
+ proxy.set_hanging(true);
+ proxy.sever();
+ // As in the pod test above: fast failures on the severed connection
+ // are drained until a call genuinely hangs, so the teardown's revoke
+ // meets the failure under test rather than a prompt error.
+ let mut hanging = false;
+ for _ in 0..5 {
+ if tokio::time::timeout(Duration::from_millis(200), store.list_routers())
+ .await
+ .is_err()
+ {
+ hanging = true;
+ break;
+ }
+ }
+ assert!(hanging, "the store must reach a state where calls hang");
+ cancel.cancel();
+
+ // Lane joins race cancellation; the heartbeat join is bounded by
+ // one keepalive round (≤10s at this test's 30s TTL); the revoke is
+ // bounded at 2s. An unbounded revoke, by contrast, waits out the
+ // hang indefinitely — which is what the window refutes.
+ let join = router.join_handle.take().expect("join handle");
+ let outcome = tokio::time::timeout(Duration::from_secs(15), join)
+ .await
+ .expect("a hung etcd must not hold the router's shutdown past its bounds")
+ .expect("the router task must not panic");
+ // Ok or Err are both legitimate endings here: cancellation racing an
+ // attempt that the severed stream already failed may surface the
+ // store error. The bound is what this test holds, not the exit code.
+ drop(outcome);
+}
+
+/// A recorded membership narrows the freeze requirement to its members —
+/// a registered router outside it must not hold the freeze.
+///
+/// This is the direction nothing else pins. Every other quorum test
+/// either injects the membership straight into the predicate or parks
+/// its handoff where the fallback and the membership are
+/// indistinguishable, so a resolution that silently degraded to
+/// "require every live router" — the safe-but-wasteful direction — would
+/// leave the whole suite green while every freeze in production waited
+/// on routers its plan deliberately excluded.
+#[tokio::test]
+async fn a_recorded_membership_advances_past_a_router_outside_it() {
+ let store = test_store("membership-narrows").await;
+ let cancel = CancellationToken::new();
+
+ // Two live routers, but the membership names only one of them: the
+ // other joined after the plan, so its ack must be neither obtainable
+ // nor required.
+ for router in ["r-member", "r-outsider"] {
+ let lease = store.grant_lease(60).await.expect("lease");
+ store
+ .register_router(
+ &RegisteredRouter {
+ router_name: router.to_string(),
+ registered_at: 0,
+ last_heartbeat: 0,
+ },
+ lease,
+ )
+ .await
+ .expect("register router");
+ }
+ store
+ .inner()
+ .put(
+ &format!("{}freeze_quorums/narrow-membership", store.inner().prefix()),
+ &vec!["r-member".to_string()],
+ None,
+ )
+ .await
+ .expect("write membership");
+
+ let _coord = start_coordinator_reconcile_parked(
+ Arc::clone(&store),
+ Arc::new(StickyBalancedStrategy),
+ cancel.clone(),
+ );
+
+ let handoff = HandoffState {
+ partition: 0,
+ old_owner: Some("pod-old".to_string()),
+ new_owner: "pod-new".to_string(),
+ new_owner_address: None,
+ phase: HandoffPhase::Freezing,
+ started_at: 0,
+ handoff_id: "narrowed-handoff".to_string(),
+ freeze_quorum: None,
+ freeze_quorum_ref: Some("narrow-membership".to_string()),
+ created_at_ms: 0,
+ phase_entered_at_ms: 0,
+ };
+ store.put_handoff(&handoff).await.expect("write handoff");
+ store
+ .put_freeze_ack(&RouterFreezeAck {
+ router_name: "r-member".to_string(),
+ partition: 0,
+ acked_at: 0,
+ acked_at_ms: 0,
+ handoff_id: "narrowed-handoff".to_string(),
+ })
+ .await
+ .expect("write ack");
+
+ // The member's ack alone must advance the freeze while the outsider
+ // stays registered and silent. A resolution degraded to the
+ // require-everybody fallback parks here forever.
+ let check_store = Arc::clone(&store);
+ wait_for_condition_named(
+ WAIT_TIMEOUT,
+ POLL_INTERVAL,
+ "the membership's one ack to advance the freeze",
+ || {
+ let store = Arc::clone(&check_store);
+ async move {
+ store
+ .get_handoff(0)
+ .await
+ .ok()
+ .flatten()
+ .is_some_and(|h| h.phase != HandoffPhase::Freezing)
+ }
+ },
+ )
+ .await;
+
+ cancel.cancel();
+}
+
+/// A coordinator whose terms keep ending badly keeps campaigning — there
+/// is no budget on endings.
+///
+/// The blackholed-proxy test cannot pin this: a candidate that cannot
+/// reach etcd fails to observe the election, which retries on the
+/// standby interval and never touches the ending arm. Here every ending
+/// is real — the term's lease is revoked out from under it — and the
+/// candidate must take the election back each time. Three consecutive
+/// endings inside one decay window rule out a budget of three or fewer
+/// on the arm the removed escalation used to live in; the honest limit
+/// of this shape is that a larger budget would still pass.
+#[tokio::test]
+async fn a_coordinator_keeps_campaigning_through_repeated_term_endings() {
+ let store = test_store("endings-no-budget").await;
+ let cancel = CancellationToken::new();
+
+ let _coord = start_coordinator_reconcile_parked(
+ Arc::clone(&store),
+ Arc::new(StickyBalancedStrategy),
+ cancel.clone(),
+ );
+
+ let mut deposed = Vec::new();
+ for round in 1..=3 {
+ let check_store = Arc::clone(&store);
+ let already = deposed.clone();
+ wait_for_condition_named(
+ WAIT_TIMEOUT,
+ POLL_INTERVAL,
+ "a fresh term to hold the election",
+ || {
+ let store = Arc::clone(&check_store);
+ let already = already.clone();
+ async move {
+ store
+ .get_leader()
+ .await
+ .ok()
+ .flatten()
+ .is_some_and(|leader| !already.contains(&leader.lease_id))
+ }
+ },
+ )
+ .await;
+ let leader = store
+ .get_leader()
+ .await
+ .expect("read leader")
+ .expect("a leader holds the election");
+ deposed.push(leader.lease_id);
+ // End the term from outside: the keepalive sees TTL 0 on its
+ // next round and the coordinator abdicates — the ending arm,
+ // not the observation arm.
+ store
+ .revoke_lease(leader.lease_id)
+ .await
+ .unwrap_or_else(|_| panic!("revoke the round-{round} lease"));
+ }
+
+ // After the third deposition it must still come back.
+ let check_store = Arc::clone(&store);
+ wait_for_condition_named(
+ WAIT_TIMEOUT,
+ POLL_INTERVAL,
+ "a fourth term after three consecutive endings",
+ || {
+ let store = Arc::clone(&check_store);
+ let deposed = deposed.clone();
+ async move {
+ store
+ .get_leader()
+ .await
+ .ok()
+ .flatten()
+ .is_some_and(|leader| !deposed.contains(&leader.lease_id))
+ }
+ },
+ )
+ .await;
+
+ cancel.cancel();
+}
+
+/// A membership the cache has learned is absent still requires every
+/// live router, and does not read as "requires nobody".
+///
+/// Those are one `Option` apart and sit on opposite sides of the safety
+/// rule: absent means unknown, which widens the requirement, while an
+/// empty membership is a real snapshot that narrows it to nobody.
+/// Caching the second in place of the first would advance a handoff out
+/// of Freezing before any router had stopped routing to the old owner —
+/// and it would do so on the second resolution, not the first, so a test
+/// that resolves once would not see it.
+#[tokio::test]
+async fn a_cached_absent_membership_still_requires_every_live_router() {
+ let store = test_store("freeze-quorum-cached-absence").await;
+
+ let handoff = HandoffState {
+ partition: 0,
+ old_owner: Some("pod-old".to_string()),
+ new_owner: "pod-new".to_string(),
+ new_owner_address: None,
+ phase: HandoffPhase::Freezing,
+ started_at: 0,
+ handoff_id: "handoff-cached-absence".to_string(),
+ freeze_quorum: None,
+ freeze_quorum_ref: Some("never-written".to_string()),
+ created_at_ms: 0,
+ phase_entered_at_ms: 0,
+ };
+
+ let routers = [
+ RegisteredRouter {
+ router_name: "router-0".to_string(),
+ registered_at: 0,
+ last_heartbeat: 0,
+ },
+ RegisteredRouter {
+ router_name: "router-1".to_string(),
+ registered_at: 0,
+ last_heartbeat: 0,
+ },
+ ];
+ let acks = [RouterFreezeAck {
+ router_name: "router-0".to_string(),
+ partition: 0,
+ acked_at: 0,
+ acked_at_ms: 0,
+ handoff_id: handoff.handoff_id.clone(),
+ }];
+
+ // Resolve twice: the first read populates the cache, the second is
+ // answered from it. Both must say the same thing.
+ for pass in 1..=2 {
+ let quorum = store
+ .resolve_freeze_quorum(&handoff)
+ .await
+ .expect("resolving must not error");
+ assert!(
+ quorum.is_none(),
+ "pass {pass}: an absent record must stay unknown, not become an empty membership"
+ );
+ assert!(
+ !freeze_quorum_met(&routers, &acks, &handoff, quorum.as_deref()),
+ "pass {pass}: one ack of two live routers must not satisfy an absent membership"
+ );
+ }
+}
+
+/// A batch of freeze acks lands every key, across the transaction
+/// chunk boundary.
+///
+/// Acks are written in chunks of at most 128 ops — etcd's default
+/// transaction ceiling — so the regression worth pinning is the tail:
+/// a batch one chunk past the boundary that quietly drops its last
+/// chunk leaves quorum members unacked and every affected freeze
+/// parked at its deadline.
+#[tokio::test]
+async fn a_freeze_ack_batch_lands_every_key_across_the_chunk_boundary() {
+ let prefix = format!("/test-ack-batch-{}/", uuid::Uuid::new_v4());
+ let store = store_at(ETCD_ENDPOINT, &prefix).await;
+
+ let acks: Vec<RouterFreezeAck> = (0u32..130)
+ .map(|partition| RouterFreezeAck {
+ router_name: "batch-router".to_string(),
+ partition,
+ acked_at: 0,
+ acked_at_ms: 0,
+ handoff_id: format!("h-{partition}"),
+ })
+ .collect();
+ store
+ .put_freeze_acks(&acks, 128)
+ .await
+ .expect("batch write");
+
+ for partition in [0u32, 127, 128, 129] {
+ let listed = store.list_freeze_acks(partition).await.expect("list acks");
+ assert_eq!(listed.len(), 1, "partition {partition} must carry its ack");
+ assert_eq!(listed[0].handoff_id, format!("h-{partition}"));
+ assert!(
+ listed[0].acked_at_ms > 0,
+ "the store stamps the batch's clock"
+ );
+ }
+
+ // An empty batch is a no-op, not an error.
+ store.put_freeze_acks(&[], 128).await.expect("empty batch");
+}
+
+/// A membership already read is answered from memory, not read again.
+///
+/// This is the whole point of holding it: every frozen partition of one
+/// plan shares an id, so resolving per handoff per reconcile pass is the
+/// read the cache exists to remove. Nothing else pins that it caches at
+/// all — the absence test passes just as well against a store that
+/// re-reads every time.
+///
+/// Deleting the record behind the cache is what makes the difference
+/// observable: a re-read would find nothing and widen the requirement,
+/// so still getting the membership proves it came from memory.
+#[tokio::test]
+async fn a_membership_already_read_is_answered_without_reading_again() {
+ let store = test_store("freeze-quorum-cache-hit").await;
+
+ let id = "cached-membership";
+ let members = vec!["router-0".to_string(), "router-1".to_string()];
+ store
+ .inner()
+ .put(
+ &format!("{}freeze_quorums/{id}", store.inner().prefix()),
+ &members,
+ None,
+ )
+ .await
+ .expect("write the membership");
+
+ let handoff = HandoffState {
+ partition: 0,
+ old_owner: Some("pod-old".to_string()),
+ new_owner: "pod-new".to_string(),
+ new_owner_address: None,
+ phase: HandoffPhase::Freezing,
+ started_at: 0,
+ handoff_id: "handoff-cache-hit".to_string(),
+ freeze_quorum: None,
+ freeze_quorum_ref: Some(id.to_string()),
+ created_at_ms: 0,
+ phase_entered_at_ms: 0,
+ };
+
+ assert_eq!(
+ store
+ .resolve_freeze_quorum(&handoff)
+ .await
+ .expect("first resolution"),
+ Some(members.clone()),
+ "the first resolution reads the record"
+ );
+
+ store
+ .delete_freeze_quorum(id)
+ .await
+ .expect("delete the membership");
+ assert!(
+ store
+ .get_freeze_quorum(id)
+ .await
+ .expect("read after delete")
+ .is_none(),
+ "the record must really be gone from etcd"
+ );
+
+ assert_eq!(
+ store
+ .resolve_freeze_quorum(&handoff)
+ .await
+ .expect("second resolution"),
+ Some(members),
+ "the second resolution must come from memory, not from etcd"
+ );
+}
diff --git a/rust/personhog-leader/src/config.rs b/rust/personhog-leader/src/config.rs
index e4143cce28e7..152bc5fe230d 100644
--- a/rust/personhog-leader/src/config.rs
+++ b/rust/personhog-leader/src/config.rs
@@ -5,6 +5,9 @@ use std::time::Duration;
use common_kafka::config::KafkaConfig;
use envconfig::Envconfig;
use personhog_coordination::authority::AuthorityClock;
+use personhog_coordination::pod::{
+ PodConfig, DRAIN_SETUP_BOUND, REVOKE_TIMEOUT, SHUTDOWN_FENCE_BOUND,
+};
#[derive(Envconfig, Clone)]
pub struct Config {
@@ -327,6 +330,30 @@ pub struct Config {
#[envconfig(default = "10")]
pub heartbeat_interval_secs: u64,
+
+ // ── Shutdown budgets ─────────────────────────────────────────
+ // The lifecycle manager's per-phase windows. Configurable because
+ // the terms validated against them — the drain timeout, the
+ // heartbeat interval — are, and a fixed ceiling under adjustable
+ // terms is a configuration an operator cannot resolve. Their
+ // relations are checked by `validate_shutdown_budgets` at startup.
+ /// How long the lifecycle manager lets the coordination component
+ /// exit gracefully. The pod's whole teardown — drain setup, drain,
+ /// fence, keepalive join, revoke — must fit inside it, which
+ /// `validate_lease_timescales` enforces.
+ #[envconfig(default = "55")]
+ pub coordination_graceful_shutdown_secs: u64,
+
+ /// The phase-1 components' shared budget: the gRPC server and the
+ /// producer stop in parallel after coordination finishes.
+ #[envconfig(default = "15")]
+ pub phase1_graceful_shutdown_secs: u64,
+
+ /// Phase 0 (coordination) plus phase 1, with slack. Must stay under
+ /// the chart's termination grace period so shutdown concludes
+ /// process-side.
+ #[envconfig(default = "75")]
+ pub global_shutdown_timeout_secs: u64,
}
/// A fenced write must resolve inside the runway the lease keepalive
@@ -580,9 +607,78 @@ impl Config {
self.lease_ttl,
));
}
+ // The pod's graceful exit — drain setup, drain, shutdown-path
+ // fence, one keepalive round's join, bounded revoke — has to
+ // fit the coordination budget, or the lifecycle manager
+ // abandons it mid-teardown while this pod is still the
+ // registered owner. The drain term reads the same
+ // `base_pod_config` the running pod is built from, so a future
+ // knob cannot decouple the validated sum from the deployed one.
+ let drain = self.base_pod_config().drain_timeout;
+ let teardown =
+ DRAIN_SETUP_BOUND + drain + SHUTDOWN_FENCE_BOUND + heartbeat + REVOKE_TIMEOUT;
+ let budget = self.coordination_graceful_shutdown();
+ if teardown >= budget {
+ return Err(format!(
+ "the pod's teardown ({teardown:?} = setup {DRAIN_SETUP_BOUND:?} + drain \
+ {drain:?} + fence {SHUTDOWN_FENCE_BOUND:?} + a {heartbeat:?} keepalive join \
+ + revoke {REVOKE_TIMEOUT:?}) must finish inside the coordination \
+ component's {budget:?} graceful shutdown budget; lower \
+ HEARTBEAT_INTERVAL_SECS or raise COORDINATION_GRACEFUL_SHUTDOWN_SECS"
+ ));
+ }
+ Ok(())
+ }
+
+ /// The lifecycle manager's phases must fit the window that
+ /// supervises them, or its own deadline fires before theirs.
+ ///
+ /// Checked at startup rather than compile time because the budgets
+ /// are configuration: a fixed ceiling under adjustable phase
+ /// timings is a configuration an operator cannot resolve.
+ pub fn validate_shutdown_budgets(&self) -> Result<(), String> {
+ let phases = self.coordination_graceful_shutdown() + self.phase1_graceful_shutdown();
+ let global = self.global_shutdown_timeout();
+ if phases >= global {
+ return Err(format!(
+ "the shutdown phases ({phases:?} = a {:?} coordination drain plus a {:?} \
+ server and producer stop) must finish inside the {global:?} global window \
+ with room to spare; raise GLOBAL_SHUTDOWN_TIMEOUT_SECS or lower the phases",
+ self.coordination_graceful_shutdown(),
+ self.phase1_graceful_shutdown(),
+ ));
+ }
Ok(())
}
+ pub fn coordination_graceful_shutdown(&self) -> Duration {
+ Duration::from_secs(self.coordination_graceful_shutdown_secs)
+ }
+
+ pub fn phase1_graceful_shutdown(&self) -> Duration {
+ Duration::from_secs(self.phase1_graceful_shutdown_secs)
+ }
+
+ pub fn global_shutdown_timeout(&self) -> Duration {
+ Duration::from_secs(self.global_shutdown_timeout_secs)
+ }
+
+ /// The coordination-relevant half of the pod's configuration, shared
+ /// by `main`'s construction and the teardown validation above so the
+ /// two cannot drift: a drain or heartbeat knob added here is summed
+ /// by the validation automatically, where one added at the
+ /// construction site would be invisible to it.
+ pub fn base_pod_config(&self) -> PodConfig {
+ PodConfig {
+ lease_ttl: self.lease_ttl,
+ heartbeat_interval: self.heartbeat_interval(),
+ // Zero would park every warm on an unobtainable permit and
+ // wedge handoffs; treat it as fully sequential instead.
+ warm_concurrency: self.warm_concurrency.max(1),
+ ..Default::default()
+ }
+ }
+
/// Every relation the fenced produce path depends on, checked at
/// startup: the derivation satisfies them wherever the lease TTL
/// leaves room, and an operator can override either knob.
@@ -778,12 +874,69 @@ mod tests {
}
}
+#[cfg(test)]
+mod lease_timescale_tests {
+ use super::*;
+
+ /// The phase budgets have to fit the window supervising them. This
+ /// held at compile time while they were constants; as configuration
+ /// it is a startup refusal, and the defaults must still satisfy it.
+ #[test]
+ fn shutdown_phases_that_overrun_the_global_window_are_refused() {
+ let config =
+ Config::init_from_hashmap(&std::collections::HashMap::new()).expect("defaults");
+ assert!(
+ config.validate_shutdown_budgets().is_ok(),
+ "the defaults must satisfy their own relations"
+ );
+
+ let mut overrun =
+ Config::init_from_hashmap(&std::collections::HashMap::new()).expect("defaults");
+ overrun.global_shutdown_timeout_secs =
+ overrun.coordination_graceful_shutdown_secs + overrun.phase1_graceful_shutdown_secs;
+ assert!(
+ overrun.validate_shutdown_budgets().is_err(),
+ "phases summing to the whole global window leave the manager no slack"
+ );
+ }
+
+ /// The pod's teardown must fit the coordination component's budget,
+ /// and the keepalive join is the one term an operator can move. A
+ /// heartbeat the renewal margin accepts can still blow the budget —
+ /// that band is exactly what a check on the margin alone missed.
+ #[test]
+ fn a_teardown_the_shutdown_budget_cannot_fit_is_refused() {
+ let mut config =
+ Config::init_from_hashmap(&std::collections::HashMap::new()).expect("defaults");
+ config.lease_ttl = 30;
+ // Inside the 20s renewal margin, so the pair check passes — but
+ // setup (5s) + drain (30s) + fence (3s) + a 16s join + revoke
+ // (5s) = 59s overruns the 55s budget. Sixteen, not a rounder
+ // number, because it discriminates on every term: without the
+ // setup bound the sum is 54s, which a broken validation would
+ // accept — a 17s join sums to exactly 55s either way and pins
+ // nothing about the setup term.
+ config.heartbeat_interval_secs = 16;
+ assert!(config.validate_lease_timescales().is_err());
+
+ config.heartbeat_interval_secs = 10;
+ assert!(
+ config.validate_lease_timescales().is_ok(),
+ "the default heartbeat must fit the budget"
+ );
+ }
+}
+
#[cfg(test)]
mod fencing_timescale_tests {
use super::*;
+ /// The envconfig defaults with no environment behind them, so an
+ /// ambient variable in a developer's shell cannot change what these
+ /// tests assert.
fn fenced(lease_ttl: i64) -> Config {
- let mut config = Config::init_from_env().expect("defaults");
+ let mut config =
+ Config::init_from_hashmap(&std::collections::HashMap::new()).expect("defaults");
config.kafka_transactional_fencing = true;
config.lease_gated_authority = true;
config.lease_ttl = lease_ttl;
diff --git a/rust/personhog-leader/src/coordination/mod.rs b/rust/personhog-leader/src/coordination/mod.rs
index e95784d2251d..048898643962 100644
--- a/rust/personhog-leader/src/coordination/mod.rs
+++ b/rust/personhog-leader/src/coordination/mod.rs
@@ -353,6 +353,10 @@ impl HandoffHandler for LeaderHandoffHandler {
}
}
+ // CONSTRAINT: synchronous local work only. The shutdown fence's
+ // certified teardown sum (`validate_lease_timescales`) counts these
+ // releases as free; making this await an external system requires
+ // growing SHUTDOWN_FENCE_BOUND.
async fn release_partition(&self, partition: u32) -> Result<()> {
info!(partition, "releasing partition");
if let Some(fenced) = &self.fenced {
diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rs
index bfaebc6b555f..8b8321036837 100644
--- a/rust/personhog-leader/src/main.rs
+++ b/rust/personhog-leader/src/main.rs
@@ -63,6 +63,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
config
.validate_fencing_timescales()
.expect("Invalid fencing configuration");
+ config
+ .validate_shutdown_budgets()
+ .expect("Invalid shutdown configuration");
validate_table_name(&config.fallback_table).expect("Invalid FALLBACK_TABLE");
// Initialize tracing
@@ -99,16 +102,18 @@ 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) plus the pre-revoke fence's short bound (3s), and the
- // global timeout must fit both phases.
+ // window must fit the pod's whole teardown — drain, fence, keepalive
+ // join, revoke — and the global timeout both phases;
+ // `validate_lease_timescales` refuses a configuration that breaks
+ // the first relation at startup.
let mut manager = Manager::builder("personhog-leader")
- .with_global_shutdown_timeout(Duration::from_secs(60))
+ .with_global_shutdown_timeout(config.global_shutdown_timeout())
.build();
let grpc_handle = manager.register(
"grpc-server",
ComponentOptions::new()
- .with_graceful_shutdown(Duration::from_secs(15))
+ .with_graceful_shutdown(config.phase1_graceful_shutdown())
.with_shutdown_phase(1),
);
let metrics_handle = manager.register(
@@ -117,7 +122,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
);
let coordination_handle = manager.register(
"coordination",
- ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(35)),
+ ComponentOptions::new().with_graceful_shutdown(config.coordination_graceful_shutdown()),
);
let kafka_handle = manager.register(
"kafka-producer",
@@ -125,7 +130,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// spawned after the producer is built normally completes well
// inside it.
ComponentOptions::new()
- .with_graceful_shutdown(Duration::from_secs(15))
+ .with_graceful_shutdown(config.phase1_graceful_shutdown())
.with_shutdown_phase(1),
);
@@ -551,17 +556,15 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
(None, String::new(), None)
};
+ // Timescale and concurrency knobs come from `base_pod_config`, the
+ // same values `validate_lease_timescales` summed at startup; only
+ // the identity fields, which no validation reads, are filled here.
let pod_config = PodConfig {
pod_name: config.pod_name.clone(),
generation,
controller,
- lease_ttl: config.lease_ttl,
- heartbeat_interval: config.heartbeat_interval(),
advertise_address: Some(advertise_address),
- // Zero would park every warm on an unobtainable permit and wedge
- // handoffs; treat it as fully sequential instead.
- warm_concurrency: config.warm_concurrency.max(1),
- ..Default::default()
+ ..config.base_pod_config()
};
// Open connections up front: warms cluster in deploy bursts, and a
diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rs
index ca5da9bbddf1..b11db3e258ac 100644
--- a/rust/personhog-leader/tests/common/mod.rs
+++ b/rust/personhog-leader/tests/common/mod.rs
@@ -100,7 +100,11 @@ pub fn start_coordinator(
name: "coordinator-0".to_string(),
leader_lease_ttl: 10,
keepalive_interval: Duration::from_secs(3),
- election_retry_interval: Duration::from_secs(1),
+ // Short enough that a failover never waits on the leader-key
+ // watch alone.
+ standby_poll_interval: Duration::from_millis(500),
+ run_retry_backoff: Duration::from_millis(10),
+ backoff_decay_window: Duration::from_secs(300),
rebalance_debounce_interval: Duration::from_millis(100),
reconcile_interval: Duration::from_millis(500),
// Effectively disabled: these tests park handoffs to assert
@@ -113,7 +117,10 @@ pub fn start_coordinator(
None,
);
let token = cancel.child_token();
- tokio::spawn(async move { coordinator.run(token).await })
+ tokio::spawn(async move {
+ coordinator.run(token).await;
+ Ok(())
+ })
}
// ── Router (for ack quorum) ─────────────────────────────────
diff --git a/rust/personhog-router/Cargo.toml b/rust/personhog-router/Cargo.toml
index 27321465542b..e34fa205f36b 100644
--- a/rust/personhog-router/Cargo.toml
+++ b/rust/personhog-router/Cargo.toml
@@ -38,6 +38,11 @@ tracing = { workspace = true }
tracing-subscriber = { workspace = true }
[dev-dependencies]
+# Test-only: the store layer emits the etcd payload histogram from both
+# this binary and every binary on the shared recorder, so the two bucket
+# ladders have to match or the series cannot be aggregated across jobs.
+# A dev-dependency binds them without pulling the crate into the build.
+common-metrics = { path = "../common/metrics" }
dashmap = { workspace = true }
flate2 = { workspace = true }
prost = { workspace = true }
diff --git a/rust/personhog-router/src/config.rs b/rust/personhog-router/src/config.rs
index 43bc5b28002a..34a8a0d527df 100644
--- a/rust/personhog-router/src/config.rs
+++ b/rust/personhog-router/src/config.rs
@@ -3,6 +3,7 @@ use std::str::FromStr;
use envconfig::Envconfig;
use personhog_coordination::authority::AuthorityClock;
+use personhog_coordination::coordinator::REVOKE_TIMEOUT as COORDINATOR_REVOKE_TIMEOUT;
use std::net::SocketAddr;
use std::time::Duration;
@@ -261,10 +262,13 @@ pub struct Config {
pub coordinator_enabled: bool,
/// Lease TTL for the coordinator leader election. A crashed leader
- /// blocks every handoff until this expires and a survivor's campaign
- /// fires, so the worst-case coordinator outage is roughly this plus
- /// the election retry interval. Graceful exits revoke the lease and
- /// fail over immediately.
+ /// blocks every handoff until this expires and a survivor takes
+ /// over. Survivors watch the leader key, so a succession follows the
+ /// key's deletion rather than a retry tick, and this TTL is what
+ /// bounds an ordinary outage. It also caps the wait a survivor paced
+ /// by repeated bad endings can add on top, so the worst case is
+ /// roughly twice this rather than unbounded in the pace. Graceful
+ /// exits revoke the lease and fail over immediately.
#[envconfig(default = "5")]
pub coordinator_lease_ttl: i64,
@@ -274,9 +278,25 @@ pub struct Config {
#[envconfig(default = "1")]
pub coordinator_keepalive_secs: u64,
- /// Retry interval between a standby candidate's election campaigns.
- #[envconfig(default = "1")]
- pub coordinator_election_retry_secs: u64,
+ /// How long a standby candidate waits on its leader-key watch before
+ /// re-reading the key, and the base of the growing retry a candidate
+ /// backs off on when it cannot read the election at all. Bounds how
+ /// long a watch that stalls without erroring can hide an opening.
+ #[envconfig(default = "5")]
+ pub coordinator_standby_poll_secs: u64,
+
+ /// Base wait before campaigning again after a leadership term ended
+ /// badly. Doubles per consecutive bad ending, capped at the
+ /// coordinator lease TTL so a paced candidate is never slower to take
+ /// an open election than to wait out a crashed leader's lease.
+ #[envconfig(default = "500")]
+ pub coordinator_run_retry_backoff_ms: u64,
+
+ /// How long without a bad ending before that pace starts over.
+ /// Without it a bad spell leaves every candidate at the cap long
+ /// after etcd recovered.
+ #[envconfig(default = "300")]
+ pub coordinator_backoff_decay_secs: u64,
/// Debounce interval (ms) for batching pod events before rebalancing
#[envconfig(default = "1000")]
@@ -294,7 +314,8 @@ pub struct Config {
/// satisfy its quorum: nothing else removes one whose new owner is
/// alive, and an in-flight handoff pins its partition, so without
/// this it waits for a human. Sized well above healthy handoffs,
- /// which complete in seconds.
+ /// which complete in seconds. Zero disables the backstop entirely —
+ /// a wedged handoff then really does wait for a human.
#[envconfig(default = "120")]
pub coordinator_handoff_deadline_secs: u64,
@@ -308,38 +329,89 @@ pub struct Config {
/// service account mount at /var/run/secrets/kubernetes.io/serviceaccount/namespace.
#[envconfig(default = "")]
pub k8s_namespace: String,
+
+ /// How many freeze acks the routing table may put in one etcd
+ /// transaction. Mirrors the server's `--max-txn-ops`: a batch above
+ /// it is refused outright, a smaller one only costs a round trip.
+ /// Defaults to etcd's own default.
+ #[envconfig(default = "128")]
+ pub etcd_max_txn_ops: usize,
+
+ // ── Shutdown budgets ─────────────────────────────────────────
+ // The lifecycle manager's per-phase windows. Configurable because
+ // the timings validated against them — the keepalive interval, the
+ // lease TTL — are, and a fixed ceiling under adjustable terms is a
+ // configuration an operator cannot resolve. Their relations are
+ // checked by `validate_shutdown_budgets` at startup.
+ /// The gRPC server's phase-0 budget: it drains first while the
+ /// coordination components keep serving its in-flight requests.
+ #[envconfig(default = "15")]
+ pub grpc_graceful_shutdown_secs: u64,
+
+ /// The phase-1 coordination components' shared budget (routing
+ /// table, coordinator, discovery, in parallel).
+ #[envconfig(default = "5")]
+ pub phase1_graceful_shutdown_secs: u64,
+
+ /// How long the lifecycle manager lets the coordinator component
+ /// exit gracefully, within phase 1.
+ #[envconfig(default = "5")]
+ pub coordinator_graceful_shutdown_secs: u64,
+
+ /// Both phases plus slack. Must stay under the chart's termination
+ /// grace period so shutdown concludes process-side.
+ #[envconfig(default = "25")]
+ pub global_shutdown_timeout_secs: u64,
}
#[cfg(test)]
mod tests {
use super::*;
+ /// The envconfig defaults with no environment behind them, so an
+ /// ambient `COORDINATOR_*` or `LEASE_TTL` in a developer's shell
+ /// cannot change what these tests assert.
+ fn default_config() -> Config {
+ Config::init_from_hashmap(&std::collections::HashMap::new()).expect("defaults")
+ }
+
fn leased(lease_ttl: i64, heartbeat_interval_secs: u64) -> Config {
- let mut config = Config::init_from_env().expect("defaults");
+ let mut config = default_config();
config.lease_ttl = lease_ttl;
config.heartbeat_interval_secs = heartbeat_interval_secs;
config
}
+ /// `leased`, in leader mode — where the coordinator can exist and
+ /// its knobs are therefore live.
+ fn leader_leased(lease_ttl: i64, heartbeat_interval_secs: u64) -> Config {
+ let mut config = leased(lease_ttl, heartbeat_interval_secs);
+ config.router_mode = RouterMode::Leader;
+ config
+ }
+
/// The keepalive uses the heartbeat as the timeout for each renewal
/// round, so a zero one times out instantly and the router fences
/// itself against healthy etcd for as long as it runs — taking every
/// handoff that needs its freeze ack with it.
#[test]
fn a_zero_heartbeat_is_refused() {
- assert!(leased(10, 0).validate_lease_timescales().is_err());
+ assert!(leader_leased(10, 0).validate_lease_timescales().is_err());
+ // A replica router registers no lease, so the same pair is dead
+ // config there and must not refuse startup.
+ assert!(leased(10, 0).validate_lease_timescales().is_ok());
}
/// A heartbeat past the renewal margin exhausts the lease by sleeping,
/// with the same result.
#[test]
fn a_heartbeat_the_lease_cannot_fit_is_refused() {
- assert!(leased(10, 30).validate_lease_timescales().is_err());
+ assert!(leader_leased(10, 30).validate_lease_timescales().is_err());
}
#[test]
fn a_heartbeat_well_inside_the_margin_is_accepted() {
- assert!(leased(10, 2).validate_lease_timescales().is_ok());
+ assert!(leader_leased(10, 2).validate_lease_timescales().is_ok());
}
/// The coordinator election lease runs the same keepalive on its own
@@ -347,7 +419,7 @@ mod tests {
/// self-fencing loop, stalling every handoff behind the coordinator.
#[test]
fn a_coordinator_keepalive_the_lease_cannot_fit_is_refused() {
- let mut config = leased(10, 2);
+ let mut config = leader_leased(10, 2);
config.coordinator_lease_ttl = 10;
config.coordinator_keepalive_secs = 30;
assert!(config.validate_lease_timescales().is_err());
@@ -356,11 +428,158 @@ mod tests {
config.coordinator_keepalive_secs = 2;
assert!(config.validate_lease_timescales().is_ok());
- // A disabled coordinator never reads these knobs, so they must
- // not be able to refuse startup.
+ // A coordinator that cannot exist never reads these knobs, so
+ // they must not be able to refuse startup — whether it is
+ // disabled by flag or by the router running in replica mode.
config.coordinator_keepalive_secs = 0;
config.coordinator_enabled = false;
assert!(config.validate_lease_timescales().is_ok());
+ config.coordinator_enabled = true;
+ config.router_mode = RouterMode::Replica;
+ assert!(config.validate_lease_timescales().is_ok());
+ }
+
+ /// The router now sets every coordinator knob explicitly, so its
+ /// envconfig defaults — not `CoordinatorConfig::default()` — are what
+ /// production runs on. The reasoning for each number still lives on
+ /// the protocol's `Default` impl, which nothing else would notice
+ /// drifting from these. Every shared knob is pinned; a partial list
+ /// would leave the drift it exists to catch silent for the rest.
+ #[test]
+ fn the_router_defaults_match_the_protocols_own() {
+ let config = default_config();
+ let protocol = personhog_coordination::coordinator::CoordinatorConfig::default();
+
+ assert_eq!(config.coordinator_lease_ttl, protocol.leader_lease_ttl);
+ assert_eq!(
+ config.coordinator_keepalive_interval(),
+ protocol.keepalive_interval
+ );
+ assert_eq!(
+ config.coordinator_standby_poll_interval(),
+ protocol.standby_poll_interval
+ );
+ assert_eq!(
+ config.coordinator_run_retry_backoff(),
+ protocol.run_retry_backoff
+ );
+ assert_eq!(
+ config.coordinator_backoff_decay_window(),
+ protocol.backoff_decay_window
+ );
+ assert_eq!(
+ config.coordinator_rebalance_debounce_interval(),
+ protocol.rebalance_debounce_interval
+ );
+ assert_eq!(
+ config.coordinator_reconcile_interval(),
+ protocol.reconcile_interval
+ );
+ assert_eq!(
+ config.coordinator_handoff_deadline(),
+ protocol.handoff_deadline
+ );
+ assert_eq!(
+ config.coordinator_warming_deadline(),
+ protocol.warming_deadline
+ );
+ }
+
+ /// A zero reconcile interval panics the interval it drives, and the
+ /// panic retries through the whole run budget and then the process —
+ /// forever. Leader-mode only: a replica router never reads these.
+ #[test]
+ fn a_zero_router_pace_is_refused_in_leader_mode() {
+ let mut config = leased(10, 2);
+ config.router_mode = RouterMode::Leader;
+ config.router_reconcile_secs = 0;
+ assert!(config.validate_lease_timescales().is_err());
+
+ config.router_reconcile_secs = 5;
+ config.router_run_retry_backoff_ms = 0;
+ assert!(config.validate_lease_timescales().is_err());
+
+ config.router_run_retry_backoff_ms = 500;
+ assert!(config.validate_lease_timescales().is_ok());
+
+ // Dead config on a replica router must not refuse startup.
+ config.router_reconcile_secs = 0;
+ config.router_mode = RouterMode::Replica;
+ assert!(config.validate_lease_timescales().is_ok());
+ }
+
+ /// Each of the coordinator's three paced knobs is either a wait or
+ /// the window a wait decays over, so a zero turns the loop it paces
+ /// into one that runs as fast as etcd will answer — a standby reading
+ /// the leader key and creating a watch back to back, or a candidate
+ /// campaigning with a lease grant, a transaction and a revoke every
+ /// turn. None of them has a floor at the point of use.
+ #[test]
+ fn a_zero_coordinator_pace_is_refused() {
+ for zero in [
+ |c: &mut Config| c.coordinator_standby_poll_secs = 0,
+ |c: &mut Config| c.coordinator_run_retry_backoff_ms = 0,
+ |c: &mut Config| c.coordinator_backoff_decay_secs = 0,
+ ] {
+ let mut config = leader_leased(10, 2);
+ zero(&mut config);
+ assert!(
+ config.validate_lease_timescales().is_err(),
+ "a zero pace must refuse startup"
+ );
+ }
+ }
+
+ /// The phase budgets have to fit the window supervising them. This
+ /// held at compile time while they were constants; as configuration
+ /// it is a startup refusal, and the defaults must still satisfy it.
+ #[test]
+ fn shutdown_phases_that_overrun_the_global_window_are_refused() {
+ let config = default_config();
+ assert!(
+ config.validate_shutdown_budgets().is_ok(),
+ "the defaults must satisfy their own relations"
+ );
+
+ let mut overrun = default_config();
+ overrun.global_shutdown_timeout_secs =
+ overrun.grpc_graceful_shutdown_secs + overrun.phase1_graceful_shutdown_secs;
+ assert!(
+ overrun.validate_shutdown_budgets().is_err(),
+ "phases summing to the whole global window leave the manager no slack"
+ );
+
+ let mut oversized_coordinator = default_config();
+ oversized_coordinator.coordinator_graceful_shutdown_secs =
+ oversized_coordinator.phase1_graceful_shutdown_secs + 1;
+ assert!(
+ oversized_coordinator.validate_shutdown_budgets().is_err(),
+ "the coordinator cannot outlast the phase it runs in"
+ );
+ }
+
+ /// The coordinator's graceful exit joins its keepalive and then
+ /// revokes the election lease, and the lifecycle manager abandons the
+ /// component when its budget runs out. The keepalive join is not
+ /// raced against cancellation, so a keepalive interval close to the
+ /// renewal margin can spend the budget before the revoke is even
+ /// reached — leaving the successor to wait out the lease TTL that the
+ /// revoke exists to spare it.
+ #[test]
+ fn a_coordinator_teardown_that_cannot_fit_its_shutdown_budget_is_refused() {
+ let mut config = leader_leased(10, 2);
+ config.coordinator_lease_ttl = 5;
+ // Inside the renewal margin (3.33s), so the keepalive pair is
+ // valid — but a 3s join plus the 2s revoke reaches the whole 5s
+ // budget, which is the case a check on the revoke alone misses.
+ config.coordinator_keepalive_secs = 3;
+ assert!(config.validate_lease_timescales().is_err());
+
+ config.coordinator_keepalive_secs = 1;
+ assert!(
+ config.validate_lease_timescales().is_ok(),
+ "a teardown that fits must be accepted"
+ );
}
// ── ReplicaDiscoveryMode ──────────────────────────────────────────────────
@@ -526,31 +745,53 @@ impl Config {
Duration::from_secs(self.heartbeat_interval_secs)
}
- /// Refuse a heartbeat the lease cannot survive.
- ///
- /// The router holds an etcd lease and votes in the freeze quorum,
- /// on the same keepalive the leader runs — which uses this interval
- /// as the timeout for each renewal round. A zero one times out
- /// instantly and a slow one sleeps through the margin, and either
- /// exhausts the lease against healthy etcd. The router then
- /// deregisters and starts over for as long as it runs, and every
- /// handoff that needs its freeze ack waits on a participant that
- /// keeps leaving.
- ///
- /// The coordinator election lease runs the same keepalive with its
- /// own pair of knobs, so it gets the same refusal: a coordinator
- /// that keeps fencing itself stalls every handoff behind it.
+ /// Refuse a heartbeat the lease cannot survive: a zero interval
+ /// times out every renewal instantly and a slow one sleeps through
+ /// the margin, so either exhausts the lease against healthy etcd
+ /// and the participant keeps leaving mid-handoff. The coordinator
+ /// election lease runs the same keepalive with its own knobs, so it
+ /// gets the same refusal.
pub fn validate_lease_timescales(&self) -> Result<(), String> {
- Self::validate_keepalive_pair(
- "HEARTBEAT_INTERVAL_SECS",
- self.heartbeat_interval(),
- "LEASE_TTL",
- self.lease_ttl,
- )?;
- // Only where a coordinator can actually run: refusing startup
- // over knobs a disabled coordinator never reads would turn dead
- // config into an outage.
- if !self.coordinator_enabled {
+ // Everything here is the routing table's, and the routing table
+ // only exists in leader mode — a replica router registers no
+ // lease and reads none of these, and refusing startup over dead
+ // config would turn it into an outage.
+ if self.router_mode == RouterMode::Leader {
+ Self::validate_keepalive_pair(
+ "HEARTBEAT_INTERVAL_SECS",
+ self.heartbeat_interval(),
+ "LEASE_TTL",
+ self.lease_ttl,
+ )?;
+ // The reconcile interval's zero panics
+ // `tokio::time::interval_at`, which ends the run, which
+ // retries the panic through the whole budget and then
+ // restarts the process — forever.
+ for (name, value) in [
+ ("ROUTER_RECONCILE_SECS", self.router_reconcile_interval()),
+ (
+ "ROUTER_RUN_RETRY_BACKOFF_MS",
+ Duration::from_millis(self.router_run_retry_backoff_ms),
+ ),
+ (
+ "STASH_MAX_WAIT_MS",
+ Duration::from_millis(self.stash_max_wait_ms),
+ ),
+ ] {
+ if value.is_zero() {
+ return Err(format!(
+ "{name} must be greater than zero: a zero either panics the \
+ interval it drives, turns its retries into a hot loop, or \
+ expires every stashed request the moment it arrives"
+ ));
+ }
+ }
+ }
+ // Only where a coordinator can actually run — which takes both
+ // the flag and leader mode, since replica routers never register
+ // one: refusing startup over knobs a coordinator that cannot
+ // exist never reads would turn dead config into an outage.
+ if !self.coordinator_enabled || self.router_mode != RouterMode::Leader {
return Ok(());
}
Self::validate_keepalive_pair(
@@ -558,7 +799,99 @@ impl Config {
self.coordinator_keepalive_interval(),
"COORDINATOR_LEASE_TTL",
self.coordinator_lease_ttl,
- )
+ )?;
+ for (name, value) in [
+ (
+ "COORDINATOR_STANDBY_POLL_SECS",
+ self.coordinator_standby_poll_interval(),
+ ),
+ (
+ "COORDINATOR_RUN_RETRY_BACKOFF_MS",
+ self.coordinator_run_retry_backoff(),
+ ),
+ (
+ "COORDINATOR_BACKOFF_DECAY_SECS",
+ self.coordinator_backoff_decay_window(),
+ ),
+ // Not a pace, but the same refusal for a worse failure: a
+ // zero period panics `tokio::time::interval`, and the panic
+ // ends the term, which retries the panic — a coordinator
+ // that never coordinates and never stops campaigning.
+ (
+ "COORDINATOR_RECONCILE_SECS",
+ self.coordinator_reconcile_interval(),
+ ),
+ ] {
+ if value.is_zero() {
+ return Err(format!(
+ "{name} must be greater than zero: every one of these paces a loop or \
+ is the window a pace decays over, and a zero either hot-loops against \
+ etcd or panics the interval it drives"
+ ));
+ }
+ }
+ // The teardown's only unraced await is the keepalive join —
+ // bounded by one renewal round, which the pair check above
+ // keeps under the margin — followed by the bounded revoke.
+ // Checked here because both halves of the relation are known.
+ let keepalive_bound = self.coordinator_keepalive_interval();
+ let teardown = keepalive_bound + COORDINATOR_REVOKE_TIMEOUT;
+ let budget = self.coordinator_graceful_shutdown();
+ if teardown >= budget {
+ return Err(format!(
+ "the coordinator's teardown ({teardown:?} = a {keepalive_bound:?} keepalive \
+ join plus a {COORDINATOR_REVOKE_TIMEOUT:?} lease revoke) must finish inside \
+ its {budget:?} graceful shutdown budget; lower COORDINATOR_KEEPALIVE_SECS \
+ or raise COORDINATOR_GRACEFUL_SHUTDOWN_SECS"
+ ));
+ }
+ Ok(())
+ }
+
+ /// The lifecycle manager's phases must fit the window that
+ /// supervises them, or its own deadline fires before theirs.
+ ///
+ /// Checked at startup rather than compile time because the budgets
+ /// are configuration: a fixed ceiling under adjustable phase
+ /// timings is a configuration an operator cannot resolve.
+ pub fn validate_shutdown_budgets(&self) -> Result<(), String> {
+ let phases = self.grpc_graceful_shutdown() + self.phase1_graceful_shutdown();
+ let global = self.global_shutdown_timeout();
+ if phases >= global {
+ return Err(format!(
+ "the shutdown phases ({phases:?} = a {:?} gRPC drain plus a {:?} coordination \
+ phase) must finish inside the {global:?} global window with room to spare; \
+ raise GLOBAL_SHUTDOWN_TIMEOUT_SECS or lower the phases",
+ self.grpc_graceful_shutdown(),
+ self.phase1_graceful_shutdown(),
+ ));
+ }
+ let coordinator = self.coordinator_graceful_shutdown();
+ let phase1 = self.phase1_graceful_shutdown();
+ if coordinator > phase1 {
+ return Err(format!(
+ "the coordinator's {coordinator:?} budget must fit the {phase1:?} phase it \
+ runs in; lower COORDINATOR_GRACEFUL_SHUTDOWN_SECS or raise \
+ PHASE1_GRACEFUL_SHUTDOWN_SECS"
+ ));
+ }
+ Ok(())
+ }
+
+ pub fn grpc_graceful_shutdown(&self) -> Duration {
+ Duration::from_secs(self.grpc_graceful_shutdown_secs)
+ }
+
+ pub fn phase1_graceful_shutdown(&self) -> Duration {
+ Duration::from_secs(self.phase1_graceful_shutdown_secs)
+ }
+
+ pub fn coordinator_graceful_shutdown(&self) -> Duration {
+ Duration::from_secs(self.coordinator_graceful_shutdown_secs)
+ }
+
+ pub fn global_shutdown_timeout(&self) -> Duration {
+ Duration::from_secs(self.global_shutdown_timeout_secs)
}
fn validate_keepalive_pair(
@@ -590,8 +923,16 @@ impl Config {
Duration::from_secs(self.coordinator_keepalive_secs)
}
- pub fn coordinator_election_retry_interval(&self) -> Duration {
- Duration::from_secs(self.coordinator_election_retry_secs)
+ pub fn coordinator_standby_poll_interval(&self) -> Duration {
+ Duration::from_secs(self.coordinator_standby_poll_secs)
+ }
+
+ pub fn coordinator_run_retry_backoff(&self) -> Duration {
+ Duration::from_millis(self.coordinator_run_retry_backoff_ms)
+ }
+
+ pub fn coordinator_backoff_decay_window(&self) -> Duration {
+ Duration::from_secs(self.coordinator_backoff_decay_secs)
}
pub fn coordinator_rebalance_debounce_interval(&self) -> Duration {
diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rs
index 994bd1eceb20..28bb83d22835 100644
--- a/rust/personhog-router/src/main.rs
+++ b/rust/personhog-router/src/main.rs
@@ -40,6 +40,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
if let Err(e) = config.validate_lease_timescales() {
panic!("invalid lease configuration: {e}");
}
+ if let Err(e) = config.validate_shutdown_budgets() {
+ panic!("invalid shutdown configuration: {e}");
+ }
// Install the process-wide recorder before anything records: metrics
// emitted ahead of it land in a no-op recorder and are dropped, and
// preregistered series never materialize.
@@ -76,10 +79,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
);
let mut manager = Manager::builder("personhog-router")
- // Below the pod's 30s termination grace so shutdown always
+ // Below the pod's 40s termination grace so shutdown always
// concludes process-side — reaching the routing table's lease
// revoke — rather than racing the kubelet's SIGKILL.
- .with_global_shutdown_timeout(Duration::from_secs(25))
+ .with_global_shutdown_timeout(config.global_shutdown_timeout())
.build();
// Shutdown order is the inverse of the leader's: the gRPC server
@@ -90,7 +93,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// router takes over coordination immediately.
let grpc_handle = manager.register(
"grpc-server",
- ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(15)),
+ ComponentOptions::new().with_graceful_shutdown(config.grpc_graceful_shutdown()),
);
let metrics_handle = manager.register(
"metrics-server",
@@ -102,14 +105,17 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let rt = manager.register(
"routing-table",
ComponentOptions::new()
- .with_graceful_shutdown(Duration::from_secs(5))
+ .with_graceful_shutdown(config.phase1_graceful_shutdown())
.with_shutdown_phase(1),
);
let coord = config.coordinator_enabled.then(|| {
+ // The whole teardown — the keepalive join and then the lease
+ // revoke — is checked against this budget by
+ // `validate_lease_timescales`, which runs before any of this.
manager.register(
"coordinator",
ComponentOptions::new()
- .with_graceful_shutdown(Duration::from_secs(5))
+ .with_graceful_shutdown(config.coordinator_graceful_shutdown())
.with_shutdown_phase(1),
)
});
@@ -124,7 +130,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
manager.register(
"replica-discovery",
ComponentOptions::new()
- .with_graceful_shutdown(Duration::from_secs(5))
+ .with_graceful_shutdown(config.phase1_graceful_shutdown())
.with_shutdown_phase(1),
),
)
@@ -261,6 +267,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
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(),
+ max_txn_ops: config.etcd_max_txn_ops,
};
let coordination_routing_table =
@@ -342,7 +349,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
name: config.pod_name.clone(),
leader_lease_ttl: config.coordinator_lease_ttl,
keepalive_interval: config.coordinator_keepalive_interval(),
- election_retry_interval: config.coordinator_election_retry_interval(),
+ standby_poll_interval: config.coordinator_standby_poll_interval(),
+ run_retry_backoff: config.coordinator_run_retry_backoff(),
+ backoff_decay_window: config.coordinator_backoff_decay_window(),
rebalance_debounce_interval: config.coordinator_rebalance_debounce_interval(),
reconcile_interval: config.coordinator_reconcile_interval(),
handoff_deadline: config.coordinator_handoff_deadline(),
@@ -354,9 +363,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
tokio::spawn(async move {
let _guard = coordinator_handle.process_scope();
- if let Err(e) = coordinator.run(coordinator_handle.shutdown_token()).await {
- coordinator_handle.signal_failure(format!("Coordinator error: {e}"));
- }
+ // No failure path back into the lifecycle manager on
+ // purpose: a peer takes over for free, a restart cannot
+ // mend an unwell etcd, and this process also serves
+ // person writes and strong reads. It retries and
+ // reports.
+ coordinator.run(coordinator_handle.shutdown_token()).await;
k8s_cancel.cancel();
});
} else {
@@ -412,6 +424,16 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
+/// Must stay equal to `common_metrics::ETCD_PAYLOAD_SIZE_BUCKETS_BYTES`,
+/// which every binary on the shared recorder gets. This binary builds its
+/// own recorder and does not depend on that crate, but the store layer
+/// emits the metric from both, and one name carrying two ladders across
+/// jobs cannot be aggregated. `etcd_payload_ladder_matches_the_shared_one`
+/// enforces the equality rather than leaving it to this comment.
+const ETCD_PAYLOAD_SIZE_BUCKETS_BYTES: &[f64] = &[
+ 1024.0, 8192.0, 65536.0, 262144.0, 524288.0, 1048576.0, 1572864.0, 2097152.0, 4194304.0,
+];
+
/// Build and install the process-wide Prometheus recorder. Runs in
/// `main` before anything records — including `preregister_metrics` —
/// because everything emitted ahead of the install lands in the default
@@ -454,6 +476,16 @@ fn install_metrics_recorder() -> PrometheusHandle {
Matcher::Prefix("personhog_router_response_size".into()),
RESPONSE_SIZE_BUCKETS,
)
+ .expect("valid buckets")
+ .set_buckets_for_metric(
+ Matcher::Full("personhog_coordination_plan_bytes".into()),
+ ETCD_PAYLOAD_SIZE_BUCKETS_BYTES,
+ )
+ .expect("valid buckets")
+ .set_buckets_for_metric(
+ Matcher::Full("assignment_coordination_etcd_payload_bytes".into()),
+ ETCD_PAYLOAD_SIZE_BUCKETS_BYTES,
+ )
.unwrap()
.set_buckets_for_metric(
Matcher::Full("personhog_coordination_handoff_phase_reached_ms".into()),
@@ -540,3 +572,17 @@ fn preregister_metrics() {
}
personhog_coordination::preregister_router_coordination_metrics();
}
+
+#[cfg(test)]
+mod tests {
+ /// The two ladders are separate literals that must agree; this
+ /// test is what enforces it.
+ #[test]
+ fn etcd_payload_ladder_matches_the_shared_one() {
+ assert_eq!(
+ super::ETCD_PAYLOAD_SIZE_BUCKETS_BYTES,
+ common_metrics::ETCD_PAYLOAD_SIZE_BUCKETS_BYTES,
+ "one metric name carrying two bucket ladders cannot be aggregated across jobs"
+ );
+ }
+}
diff --git a/rust/personhog-stateright/src/model.rs b/rust/personhog-stateright/src/model.rs
index 3f5c38173c83..d9cee87dd5fe 100644
--- a/rust/personhog-stateright/src/model.rs
+++ b/rust/personhog-stateright/src/model.rs
@@ -48,19 +48,26 @@ fn production_handoff(p: Partition, h: &Handoff) -> HandoffState {
phase: h.phase,
started_at: 0,
handoff_id: h.id.to_string(),
- // The model always captures a snapshot (its Rebalance mirrors
- // the production coordinator, which always writes one). The
- // production `None` legacy fallback is a serialization concern
- // pinned by unit tests, not a reachable state here. With
- // `RouterJoin` in the action space the snapshot diverges from
- // the live registry, and the production quorum predicate below
- // is exercised on exactly that divergence.
- freeze_quorum: Some(h.quorum.iter().map(|r| router_name(*r)).collect()),
+ // Membership lives beside the record in production, so the
+ // record carries neither form. `production_quorum` supplies it
+ // to the predicates that need it.
+ freeze_quorum: None,
+ freeze_quorum_ref: None,
created_at_ms: 0,
phase_entered_at_ms: 0,
}
}
+/// The membership a model handoff was created with, in the form the
+/// production quorum predicates take. The model always captures a
+/// snapshot; the production `None` fallback is a serialization concern
+/// pinned by unit tests, not a reachable state here. `RouterJoin` makes
+/// the snapshot diverge from the live registry, which is what exercises
+/// the predicate.
+fn production_quorum(h: &Handoff) -> Vec<String> {
+ h.quorum.iter().map(|r| router_name(*r)).collect()
+}
+
/// Which produce-path protection the model runs with.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Variant {
@@ -793,7 +800,12 @@ impl HandoffModel {
})
})
.collect();
- if !freeze_quorum_met(&routers, &acks, &production_handoff(p, h)) {
+ if !freeze_quorum_met(
+ &routers,
+ &acks,
+ &production_handoff(p, h),
+ Some(&production_quorum(h)),
+ ) {
return None;
}
// Initial assignments (no old owner) skip the drain