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): coordination hardening (#69029)

Zach Brown3174a30ec1a1
diff --git a/rust/common/assignment-coordination/src/store.rs b/rust/common/assignment-coordination/src/store.rs
index d93994386b1f..507c3788a832 100644
--- a/rust/common/assignment-coordination/src/store.rs
+++ b/rust/common/assignment-coordination/src/store.rs
@@ -78,13 +78,60 @@ impl EtcdStore {
}
}
+ /// Like `get_versioned`, but returns the key's `mod_revision` instead
+ /// of its per-key `version` counter. Compare-and-swap guards that must
+ /// not match across a delete-and-recreate of the same key MUST use
+ /// this: `version` resets to 1 when a key is recreated, so a guard on
+ /// `version` can accept a different incarnation of the key, while
+ /// `mod_revision` is globally monotonic and never repeats.
+ pub async fn get_with_mod_revision<T: DeserializeOwned>(
+ &self,
+ key: &str,
+ ) -> Result<Option<(T, i64)>> {
+ let resp = self.client.clone().get(key, None).await?;
+ match resp.kvs().first() {
+ Some(kv) => {
+ let value = serde_json::from_slice(kv.value())?;
+ Ok(Some((value, kv.mod_revision())))
+ }
+ None => Ok(None),
+ }
+ }
+
pub async fn list<T: DeserializeOwned>(&self, prefix: &str) -> Result<Vec<T>> {
+ Ok(self.list_with_revision(prefix).await?.0)
+ }
+
+ /// 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
+ /// the revision is in the snapshot, every later one is delivered by
+ /// the watch, no matter when the watch actually attaches.
+ pub async fn list_with_revision<T: DeserializeOwned>(
+ &self,
+ prefix: &str,
+ ) -> Result<(Vec<T>, i64)> {
let options = GetOptions::new().with_prefix();
let resp = self.client.clone().get(prefix, Some(options)).await?;
- resp.kvs()
+ let revision = resp.header().map(|h| h.revision()).unwrap_or(0);
+ let items = resp
+ .kvs()
.iter()
.map(|kv| serde_json::from_slice(kv.value()).map_err(Error::from))
- .collect()
+ .collect::<Result<Vec<T>>>()?;
+ Ok((items, revision))
+ }
+
+ /// The current etcd store revision, for anchoring watches when no
+ /// snapshot read is involved.
+ pub async fn current_revision(&self) -> Result<i64> {
+ let options = GetOptions::new().with_prefix().with_count_only();
+ let resp = self
+ .client
+ .clone()
+ .get(self.config.prefix.clone(), Some(options))
+ .await?;
+ Ok(resp.header().map(|h| h.revision()).unwrap_or(0))
}
pub async fn put<T: Serialize>(
@@ -116,6 +163,21 @@ impl EtcdStore {
Ok(stream)
}
+ /// Watch the prefix starting from an explicit revision (inclusive).
+ /// Events since that revision are replayed even if they predate the
+ /// watch's creation, which removes the missed-event window between a
+ /// snapshot read and the watch attaching. If etcd has compacted past
+ /// the requested revision the stream is cancelled with an error; the
+ /// caller's watch loop treats that as fatal and the component restarts
+ /// with a fresh snapshot.
+ pub async fn watch_from(&self, prefix: &str, start_revision: i64) -> Result<WatchStream> {
+ let options = WatchOptions::new()
+ .with_prefix()
+ .with_start_revision(start_revision);
+ let stream = self.client.clone().watch(prefix, Some(options)).await?;
+ Ok(stream)
+ }
+
// ── Transactions ─────────────────────────────────────────────
pub async fn txn(&self, txn: Txn) -> Result<TxnResponse> {
diff --git a/rust/personhog-coordination/Cargo.toml b/rust/personhog-coordination/Cargo.toml
index 0058f5aae4a5..1e06faa65057 100644
--- a/rust/personhog-coordination/Cargo.toml
+++ b/rust/personhog-coordination/Cargo.toml
@@ -15,6 +15,7 @@ thiserror = { workspace = true }
tokio = { workspace = true }
tokio-util = { version = "0.7", features = ["rt"] }
tracing = { workspace = true }
+uuid = { workspace = true }
[dev-dependencies]
k8s-openapi = { version = "0.24", features = ["latest"] }
@@ -26,7 +27,6 @@ testcontainers = { workspace = true }
testcontainers-modules = { version = "0.15", features = ["k3s"] }
tokio = { workspace = true, features = ["test-util"] }
tracing-subscriber = { workspace = true }
-uuid = { workspace = true }
[lints]
workspace = true
diff --git a/rust/personhog-coordination/README.md b/rust/personhog-coordination/README.md
index f91394f8b219..30a289ad1f66 100644
--- a/rust/personhog-coordination/README.md
+++ b/rust/personhog-coordination/README.md
@@ -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. Routers begin buffering ("stashing") incoming writes for the partition and write a `RouterFreezeAck`. The old owner does *not* yet drain — it continues serving until every router has acked, because while a single router still forwards traffic to the old owner the inflight count cannot meaningfully be observed as zero. Once every registered router has acked, the coordinator advances to `Draining` via a versioned compare-and-swap.
+1. **Freezing**: Coordinator creates the handoff. Routers begin buffering ("stashing") incoming writes for the partition and write a `RouterFreezeAck`. The old owner does *not* yet drain — it continues serving until every router has acked, because while a single router still forwards traffic to the old owner the inflight count cannot meaningfully be observed as zero. Once every registered 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`.
@@ -54,6 +54,8 @@ Freezing --> Draining --> Warming --> Complete --> (deleted)
The handoff record carries `old_owner: Option<String>`. `None` denotes an initial assignment with no prior owner — there's nothing to drain, so the protocol short-circuits and skips `Draining` entirely, advancing `Freezing → Warming` once router quorum is met.
+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.
+
#### 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."
@@ -62,14 +64,17 @@ If a single phase served both purposes (router stash *and* old-owner drain in pa
Several failure modes are handled explicitly:
-- **Dead `new_owner`**: If the new owner's etcd registration disappears (lease expired, deregistered) before it can ack warming, `cleanup_stale_handoffs` deletes the handoff. A subsequent rebalance picks a fresh new owner.
-- **Dead `old_owner` before drain**: A Freezing handoff whose `old_owner` is no longer registered is also cleaned up. A dead pod can no longer produce writes, so the drain requirement is moot — but only if its etcd key is genuinely absent. A `Draining` pod is still alive and is required to write its `DrainedAck` before the handoff advances.
-- **Handoff deleted mid-flight**: When routers see a handoff key disappear (cleanup, ops intervention), they drain their stash back to whoever the routing table currently points at. The protocol never reached `Complete`, so the unchanged owner is the right target.
+- **Dead `new_owner`**: If the new owner's etcd registration disappears (lease expired, deregistered) before it can ack warming, `cleanup_stale_handoffs` deletes the handoff — this is the *only* condition that triggers cleanup. The delete re-reads the handoff under its `mod_revision` and removes the handoff plus all of its acks in a single guarded transaction, so a concurrent cleanup (pod watch, handoff watch, reconcile tick, or a coordinator failing over) can never destroy a successor handoff recreated at the same key. A subsequent rebalance picks a fresh new owner.
+- **Dead `old_owner`**: A dead old owner is deliberately *not* grounds for cleanup. A pod that is no longer registered can't produce writes, so the drain requirement is vacuously satisfied — `check_phase_advance` treats a handoff whose `old_owner` is absent from the registered set as drained and advances it in place toward `Complete`. An `old_owner` that is still registered must write its `DrainedAck` before the handoff advances.
+- **Handoff deleted mid-flight (cancellation)**: When routers see a handoff key disappear before `Complete` (cleanup, ops intervention), they drain their stash back to whoever the routing table currently points at. The protocol never reached `Complete`, so the unchanged owner is the right target. On the pod side the same deletion is a cancellation: a pod that still owns the partition gets `resume_partition`, lifting its write fence so the partition serves writes again. A deletion observed *after* `Complete` is normal cleanup and triggers no resume.
- **Coordinator restart**: On startup, the coordinator runs `reconcile_pending_handoffs`. For every existing handoff it applies cleanup if `Complete`, otherwise calls `check_phase_advance` to nudge the state machine. This handles the case where acks were written before the coordinator was up — the ack-watch only fires on Put events, so without reconcile those acks would be invisible.
+- **Reconcile tick**: Beyond the startup reconcile, the coordinator re-evaluates every in-flight handoff on a fixed interval (`reconcile_interval`, default 5 s). This is the liveness backstop for state changes that fire no watched event — e.g. a router departing (nothing watches router registrations) newly satisfying a freeze quorum. Everything the tick drives is idempotent: phase transitions use CAS and cleanup tolerates already-deleted records.
+- **Lease loss (self-fencing)**: A pod or router whose lease keepalive fails — including etcd answering a keepalive with TTL ≤ 0 for a revoked or expired lease — treats the lease as lost and exits its run loop immediately, skipping the graceful drain: the coordinator already considers it dead and is reassigning its partitions via the dead-owner path, so a graceful drain would only race that. This prevents a zombie owner from continuing to serve partitions the protocol has reassigned.
### Concurrency and atomicity
-- All phase advancement uses `cas_handoff_phase`, a version-CAS on the handoff key. Two watchers racing to advance the same handoff cannot both succeed; the loser observes `false` and leaves the work to the Put event from the winner.
+- All phase advancement uses `cas_handoff_phase`, a CAS on the handoff key's `mod_revision`. Two watchers racing to advance the same handoff cannot both succeed; the loser observes `false` and leaves the work to the Put event from the winner. (`mod_revision` rather than per-key `version`: `version` resets to 1 when a key is deleted and recreated, so a stale guard could match a different incarnation of the handoff.)
+- Every snapshot read that seeds a watch is revision-anchored: the read returns the etcd revision it was served at, and the watch starts at `revision + 1`. An event landing between the snapshot and the watch attaching is replayed rather than lost. When two snapshot reads feed one watch (e.g. a pod's startup reconcile reads assignments and handoffs), the watch anchors to the *lower* of the two revisions so nothing between them is skipped.
- Advancing to `Complete` uses an atomic etcd transaction that writes both `phase=Complete` and the new `PartitionAssignment` together. Routers can never observe a torn state where the phase has advanced but the assignment hasn't (or vice versa).
- Routing changes flow exclusively through handoff `Complete` events. There is no separate assignment watch — anything that mutates `assignments/{partition}` outside the handoff protocol is invisible to routers by design.
@@ -77,7 +82,7 @@ Several failure modes are handled explicitly:
**Assignment strategies are minimal**: The two bundled strategies (`JumpHashStrategy` and `StickyBalancedStrategy`) are basic implementations meant to exercise the coordination layer. `JumpHashStrategy` is stateless and deterministic but ignores current assignments entirely, causing unnecessary partition movement on every rebalance. `StickyBalancedStrategy` minimizes movement but uses a naive greedy approach without considering locality, rack awareness, or weighted pods. Both are placeholders to be replaced with a production-grade strategy as requirements become clearer.
-**Watch reconnects don't replay missed events**: If the routing table loses its etcd watch and the underlying client reconnects, any handoff Put/Delete events that fired during the disconnect are lost. The routing table relies on the etcd_client's reconnect logic and does not periodically reconcile, so a long disconnect could leave the routing map stale until something forces a re-read. This hasn't bitten us in practice but is worth knowing.
+**Mid-stream watch reconnects don't replay missed events**: The snapshot-to-watch-attach gap is closed (watches are revision-anchored to the snapshot that seeded them), but if an *established* etcd watch stream drops and the underlying client reconnects, events that fired during the disconnect are not replayed. The coordinator's reconcile tick backstops its own state machine; the routing table relies on the etcd client's reconnect logic and does not periodically reconcile, so a long disconnect could leave the routing map stale until something forces a re-read. This hasn't bitten us in practice but is worth knowing.
## Modules
@@ -85,9 +90,10 @@ Several failure modes are handled explicitly:
| --- | --- |
| `types` | Core data types: `RegisteredPod`, `PartitionAssignment`, `HandoffState`, `RouterFreezeAck`, `PodDrainedAck`, `PodWarmedAck`, etc. |
| `store` | `EtcdStore` abstraction: typed CRUD, watches, leases, and transactions over etcd. Hosts `cas_handoff_phase` and `complete_handoff` (the atomic phase + assignment txn). |
-| `coordinator` | Leader election, assignment computation, handoff orchestration, ack quorum checking, reconcile-on-startup, stale-handoff cleanup. |
-| `pod` | `PodHandle` + `HandoffHandler` trait: pod registration, heartbeat, and the drain/warm/release responses to handoff phases. |
+| `coordinator` | Leader election, assignment computation, handoff orchestration, ack quorum checking, reconcile-on-startup, periodic reconcile tick, stale-handoff cleanup. |
+| `pod` | `PodHandle` + `HandoffHandler` trait: pod registration, heartbeat, and the drain/warm/release/resume responses to handoff phases (state derived by `desired_state` from fresh reads and converged, not accumulated from event payloads). |
| `routing_table` | `RoutingTable` + `StashHandler` trait: routing map maintenance and the begin-stash / drain-stash phase responses. |
| `strategy` | `AssignmentStrategy` trait with `JumpHashStrategy` and `StickyBalancedStrategy` implementations. |
| `hash` | Jump consistent hash function. |
+| `util` | Shared helpers: lease keepalive with self-fencing on lease loss, handoff id generation. |
| `error` | Error types. |
diff --git a/rust/personhog-coordination/src/coordinator.rs b/rust/personhog-coordination/src/coordinator.rs
index 07bc7afd91fe..d885f97e70f6 100644
--- a/rust/personhog-coordination/src/coordinator.rs
+++ b/rust/personhog-coordination/src/coordinator.rs
@@ -1,8 +1,8 @@
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::Duration;
-use etcd_client::EventType;
+use etcd_client::{EventType, WatchStream};
use tokio_util::sync::CancellationToken;
use assignment_coordination::store::parse_watch_value;
@@ -28,6 +28,14 @@ pub struct CoordinatorConfig {
/// 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,
+ /// How often to re-evaluate in-flight handoffs regardless of watch
+ /// events. Phase advancement is normally event-driven, but some state
+ /// changes produce no watched event at all — a router departing
+ /// (nothing watches router registrations) can newly satisfy a freeze
+ /// quorum. The tick backstops those so handoffs cannot stall
+ /// indefinitely, and doubles as defense-in-depth for anything else
+ /// that slips through the event-driven paths.
+ pub reconcile_interval: Duration,
}
impl Default for CoordinatorConfig {
@@ -38,6 +46,7 @@ impl Default for CoordinatorConfig {
keepalive_interval: Duration::from_secs(5),
election_retry_interval: Duration::from_secs(5),
rebalance_debounce_interval: Duration::from_secs(1),
+ reconcile_interval: Duration::from_secs(5),
}
}
}
@@ -126,12 +135,22 @@ impl Coordinator {
}
async fn run_coordination_loop(&self, cancel: CancellationToken) -> Result<()> {
- // Spawn all watch loops BEFORE doing any work that produces etcd
- // events. The new protocol requires the coordinator itself to
- // observe ack writes (PodDrainedAck, PodWarmedAck, RouterFreezeAck)
- // to advance handoffs through their phases. If we did initial
- // bootstrap before attaching watches, events fired during bootstrap
- // would be missed and handoffs would stall in their initial phase.
+ // 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).
+ 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?;
+ let freeze_acks_stream = self.store.watch_freeze_acks_from(anchor).await?;
+ let drained_acks_stream = self.store.watch_drained_acks_from(anchor).await?;
+ let warmed_acks_stream = self.store.watch_warmed_acks_from(anchor).await?;
+
let mut tasks = tokio::task::JoinSet::new();
{
@@ -141,8 +160,15 @@ impl Coordinator {
let debounce_interval = self.config.rebalance_debounce_interval;
let token = cancel.child_token();
tasks.spawn(async move {
- Self::watch_pods_loop(store, strategy, k8s_awareness, debounce_interval, token)
- .await
+ Self::watch_pods_loop(
+ store,
+ strategy,
+ k8s_awareness,
+ debounce_interval,
+ token,
+ pods_stream,
+ )
+ .await
});
}
@@ -152,32 +178,42 @@ impl Coordinator {
let k8s_awareness = self.k8s_awareness.clone();
let token = cancel.child_token();
tasks.spawn(async move {
- Self::watch_handoffs_loop(store, strategy, k8s_awareness, token).await
+ Self::watch_handoffs_loop(store, strategy, k8s_awareness, token, handoffs_stream)
+ .await
});
}
{
let store = Arc::clone(&self.store);
let token = cancel.child_token();
- tasks.spawn(async move { Self::watch_freeze_acks_loop(store, token).await });
+ tasks.spawn(async move {
+ Self::run_ack_watch("freeze", freeze_acks_stream, &store, token).await
+ });
}
{
let store = Arc::clone(&self.store);
let token = cancel.child_token();
- tasks.spawn(async move { Self::watch_drained_acks_loop(store, token).await });
+ tasks.spawn(async move {
+ Self::run_ack_watch("drained", drained_acks_stream, &store, token).await
+ });
}
{
let store = Arc::clone(&self.store);
let token = cancel.child_token();
- tasks.spawn(async move { Self::watch_warmed_acks_loop(store, token).await });
+ tasks.spawn(async move {
+ Self::run_ack_watch("warmed", warmed_acks_stream, &store, token).await
+ });
+ }
+
+ {
+ let store = Arc::clone(&self.store);
+ let interval = self.config.reconcile_interval;
+ let token = cancel.child_token();
+ tasks.spawn(async move { Self::reconcile_tick_loop(store, interval, token).await });
}
- // Watches are now attached at the current etcd revision.
- // Any handoff/ack events produced from this point forward will be
- // observed by the relevant watch loops.
- //
// Reconcile any handoffs that already have full ack quorum.
// This handles acks that arrived before this coordinator took leadership.
self.reconcile_pending_handoffs().await?;
@@ -204,9 +240,8 @@ impl Coordinator {
k8s_awareness: Option<Arc<K8sAwareness>>,
debounce_interval: Duration,
cancel: CancellationToken,
+ mut stream: WatchStream,
) -> Result<()> {
- let mut stream = store.watch_pods().await?;
-
loop {
// Wait for the first pod event
tokio::select! {
@@ -249,9 +284,8 @@ impl Coordinator {
strategy: Arc<dyn AssignmentStrategy>,
k8s_awareness: Option<Arc<K8sAwareness>>,
cancel: CancellationToken,
+ mut stream: WatchStream,
) -> Result<()> {
- let mut stream = store.watch_handoffs().await?;
-
loop {
tokio::select! {
_ = cancel.cancelled() => return Ok(()),
@@ -294,36 +328,11 @@ impl Coordinator {
}
}
- /// Watch for router freeze acks (routers confirming they have begun stashing).
- async fn watch_freeze_acks_loop(
- store: Arc<PersonhogStore>,
- cancel: CancellationToken,
- ) -> Result<()> {
- let mut stream = store.watch_freeze_acks().await?;
- Self::run_ack_watch("freeze", &mut stream, &store, cancel).await
- }
-
- /// Watch for the old owner's drained acks.
- async fn watch_drained_acks_loop(
- store: Arc<PersonhogStore>,
- cancel: CancellationToken,
- ) -> Result<()> {
- let mut stream = store.watch_drained_acks().await?;
- Self::run_ack_watch("drained", &mut stream, &store, cancel).await
- }
-
- /// Watch for the new owner's warmed acks.
- async fn watch_warmed_acks_loop(
- store: Arc<PersonhogStore>,
- cancel: CancellationToken,
- ) -> Result<()> {
- let mut stream = store.watch_warmed_acks().await?;
- Self::run_ack_watch("warmed", &mut stream, &store, cancel).await
- }
-
+ /// Consume an ack watch stream (freeze, drained, or warmed), nudging
+ /// phase advancement for the acked partition on every event.
async fn run_ack_watch(
kind: &str,
- stream: &mut etcd_client::WatchStream,
+ mut stream: WatchStream,
store: &PersonhogStore,
cancel: CancellationToken,
) -> Result<()> {
@@ -349,6 +358,32 @@ impl Coordinator {
}
}
+ /// Periodically re-evaluate every in-flight handoff, mirroring what
+ /// the ack watches do on events. This is the liveness backstop for
+ /// state changes that fire no watched event — a router departing
+ /// (nothing watches router registrations) can newly satisfy a freeze
+ /// quorum. All the work it drives is idempotent: phase transitions
+ /// use CAS and completed-handoff cleanup tolerates already-deleted
+ /// records.
+ async fn reconcile_tick_loop(
+ store: Arc<PersonhogStore>,
+ interval: Duration,
+ cancel: CancellationToken,
+ ) -> Result<()> {
+ let mut tick = tokio::time::interval(interval);
+ loop {
+ tokio::select! {
+ _ = cancel.cancelled() => return Ok(()),
+ _ = tick.tick() => {
+ for handoff in store.list_handoffs().await? {
+ Self::handle_handoff_update_static(&store, &handoff).await?;
+ Self::check_phase_advance(&store, handoff.partition).await?;
+ }
+ }
+ }
+ }
+ }
+
/// Advance a handoff's phase when its current phase's preconditions are satisfied:
/// Freezing -> Draining: all registered routers have FreezeAck
/// Draining -> Warming: old owner has DrainedAck (or old owner is gone)
@@ -373,11 +408,28 @@ impl Coordinator {
let routers = store.list_routers().await?;
let freeze_acks = store.list_freeze_acks(partition).await?;
+ // Identity-based quorum: every currently registered router
+ // must have acked this partition's freeze. A count
+ // comparison would let a stale ack from a departed router
+ // (acks are not lease-bound) stand in for a live router
+ // that hasn't stashed yet — advancing to Draining while
+ // that router still forwards writes to the old owner.
+ // Only acks echoing this handoff's id count: an ack left
+ // over from a previous handoff of the same partition
+ // proves nothing about this one.
+ //
// With zero routers there is no traffic to stash, so the
// freeze quorum is vacuously met. This keeps bootstrap and
// router-less configurations (e.g. tests exercising only
// the coordinator+pod) unblocked.
- let all_routers_frozen = freeze_acks.len() >= routers.len();
+ let acked: HashSet<&str> = freeze_acks
+ .iter()
+ .filter(|a| a.handoff_id == handoff.handoff_id)
+ .map(|a| a.router_name.as_str())
+ .collect();
+ let all_routers_frozen = routers
+ .iter()
+ .all(|r| acked.contains(r.router_name.as_str()));
if all_routers_frozen {
// Initial assignments (no old owner) skip Draining
@@ -427,7 +479,9 @@ impl Coordinator {
true
} else {
let drained_acks = store.list_drained_acks(partition).await?;
- drained_acks.iter().any(|a| a.pod_name == *name)
+ drained_acks
+ .iter()
+ .any(|a| a.pod_name == *name && a.handoff_id == handoff.handoff_id)
}
}
};
@@ -447,7 +501,9 @@ impl Coordinator {
}
HandoffPhase::Warming => {
let warmed = store.list_warmed_acks(partition).await?;
- let new_owner_warmed = warmed.iter().any(|a| a.pod_name == handoff.new_owner);
+ let new_owner_warmed = warmed
+ .iter()
+ .any(|a| a.pod_name == handoff.new_owner && a.handoff_id == handoff.handoff_id);
if new_owner_warmed {
tracing::info!(
@@ -571,9 +627,8 @@ impl Coordinator {
// cache hasn't been warmed.
//
// Partitions that already have the correct owner are skipped.
- let assigned_partitions: std::collections::HashSet<u32> =
- new_assignments.keys().copied().collect();
- let reassignment_partitions: std::collections::HashSet<u32> =
+ let assigned_partitions: HashSet<u32> = new_assignments.keys().copied().collect();
+ let reassignment_partitions: HashSet<u32> =
reassignments.iter().map(|(p, _, _)| *p).collect();
// Fresh partitions = assigned but neither in current nor being reassigned.
@@ -599,6 +654,7 @@ impl Coordinator {
new_owner: new_owner.clone(),
phase: HandoffPhase::Freezing,
started_at: now,
+ handoff_id: util::new_handoff_id(),
});
}
@@ -611,6 +667,7 @@ impl Coordinator {
new_owner: new_owner.clone(),
phase: HandoffPhase::Freezing,
started_at: now,
+ handoff_id: util::new_handoff_id(),
});
}
@@ -624,7 +681,7 @@ impl Coordinator {
// already) still need to be written to etcd, but reassignments and
// fresh assignments defer their PartitionAssignment writes until the
// handoff reaches Complete.
- let handoff_partitions: std::collections::HashSet<u32> =
+ let handoff_partitions: HashSet<u32> =
handoff_objects.iter().map(|h| h.partition).collect();
let assignment_objects: Vec<PartitionAssignment> = new_assignments
.iter()
@@ -655,49 +712,60 @@ impl Coordinator {
Ok(())
}
- /// Delete handoffs that cannot progress because either the new_owner is
- /// gone, or the old_owner is gone before it wrote a DrainedAck.
+ /// Delete handoffs that cannot progress because the new_owner is gone —
+ /// no `WarmedAck` will ever arrive, so the handoff can never complete,
+ /// and deleting it lets the next rebalance pick a healthy owner.
+ ///
+ /// A dead *old* owner is deliberately not grounds for cleanup: Freezing
+ /// waits on routers rather than the old owner, and `check_phase_advance`
+ /// treats an absent old owner in Draining as vacuously drained, so such
+ /// handoffs advance on their own (the reconcile tick guarantees
+ /// re-evaluation). Deleting them here would race that advance path and
+ /// tear down a healthy in-flight warm on the new owner.
///
/// "Gone" here means the pod's etcd registration is absent — its lease
/// expired or it deregistered. A `Draining` pod is *not* gone: it is
/// still alive, still heartbeating, and still capable of running its
- /// handoff handler. We deliberately don't reuse the assignment-eligible
- /// pod set (which is `Ready`-only) for liveness here, because a Draining
- /// pod that's mid-drain still owes the protocol a `DrainedAck` and must
- /// be allowed to write it.
+ /// handoff handler.
async fn cleanup_stale_handoffs(store: &PersonhogStore) -> Result<()> {
let handoffs = store.list_handoffs().await?;
let pods = store.list_pods().await?;
- let registered_set: std::collections::HashSet<&str> =
- pods.iter().map(|p| p.pod_name.as_str()).collect();
+ let registered_set: HashSet<&str> = pods.iter().map(|p| p.pod_name.as_str()).collect();
for handoff in &handoffs {
- let new_owner_gone = !registered_set.contains(handoff.new_owner.as_str());
-
- // Check if old_owner is gone and hasn't acked its drain yet.
- // A dead old_owner with a DrainedAck already present is fine —
- // the protocol has all it needs to advance. Without the ack the
- // handoff is stuck in Freezing forever.
- let stuck_on_dead_old_owner = match &handoff.old_owner {
- Some(name) if !registered_set.contains(name.as_str()) => {
- let drained = store.list_drained_acks(handoff.partition).await?;
- !drained.iter().any(|a| a.pod_name == *name)
- }
- _ => false,
+ if registered_set.contains(handoff.new_owner.as_str()) {
+ continue;
+ }
+ // Re-read under mod_revision and re-verify before deleting.
+ // This function runs concurrently from the pod watch, the
+ // handoff watch, and the reconcile tick (and briefly from an
+ // outgoing coordinator during failover): an unguarded delete
+ // acting on this loop's snapshot could destroy a successor
+ // handoff recreated at the same key, along with its acks.
+ let Some((current, mod_revision)) = store
+ .get_handoff_with_mod_revision(handoff.partition)
+ .await?
+ else {
+ continue;
};
-
- if new_owner_gone || stuck_on_dead_old_owner {
- tracing::warn!(
- partition = handoff.partition,
- new_owner = %handoff.new_owner,
- old_owner = ?handoff.old_owner,
- phase = ?handoff.phase,
- new_owner_gone,
- stuck_on_dead_old_owner,
- "cleaning up stale handoff"
+ if registered_set.contains(current.new_owner.as_str()) {
+ continue;
+ }
+ tracing::warn!(
+ partition = current.partition,
+ new_owner = %current.new_owner,
+ old_owner = ?current.old_owner,
+ phase = ?current.phase,
+ "cleaning up handoff targeting a dead new owner"
+ );
+ if !store
+ .delete_handoff_and_acks_if_unchanged(current.partition, mod_revision)
+ .await?
+ {
+ tracing::info!(
+ partition = current.partition,
+ "handoff changed concurrently, skipping cleanup"
);
- store.delete_all_handoff_acks(handoff.partition).await?;
- store.delete_handoff(handoff.partition).await?;
}
}
@@ -709,12 +777,32 @@ impl Coordinator {
handoff: &HandoffState,
) -> Result<()> {
if handoff.phase == HandoffPhase::Complete {
+ // Same guarded-delete discipline as `cleanup_stale_handoffs`:
+ // the Complete observation may be stale by the time we act on
+ // it, and the record at this key may already be a successor
+ // handoff.
+ let Some((current, mod_revision)) = store
+ .get_handoff_with_mod_revision(handoff.partition)
+ .await?
+ else {
+ return Ok(());
+ };
+ if current.phase != HandoffPhase::Complete {
+ return Ok(());
+ }
tracing::info!(
- partition = handoff.partition,
+ partition = current.partition,
"handoff complete, cleaning up"
);
- store.delete_all_handoff_acks(handoff.partition).await?;
- store.delete_handoff(handoff.partition).await?;
+ if !store
+ .delete_handoff_and_acks_if_unchanged(current.partition, mod_revision)
+ .await?
+ {
+ tracing::info!(
+ partition = current.partition,
+ "handoff changed concurrently, skipping cleanup"
+ );
+ }
}
Ok(())
}
diff --git a/rust/personhog-coordination/src/pod.rs b/rust/personhog-coordination/src/pod.rs
index 29eb406498b4..f2daf30c46b0 100644
--- a/rust/personhog-coordination/src/pod.rs
+++ b/rust/personhog-coordination/src/pod.rs
@@ -3,7 +3,7 @@ use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
-use etcd_client::EventType;
+use etcd_client::{EventType, WatchStream};
use tokio::sync::{Mutex, Notify};
use tokio_util::sync::CancellationToken;
@@ -12,12 +12,82 @@ use k8s_awareness::types::{ControllerKind, ControllerRef};
use k8s_awareness::{DepartureReason, K8sAwareness};
use crate::error::{Error, Result};
-use crate::store::PersonhogStore;
+use crate::store::{self, PersonhogStore};
use crate::types::{
- HandoffPhase, HandoffState, PodDrainedAck, PodStatus, PodWarmedAck, RegisteredPod,
+ HandoffPhase, HandoffState, PartitionAssignment, PodDrainedAck, PodStatus, PodWarmedAck,
+ RegisteredPod,
};
use crate::util;
+/// The state this pod should hold for one partition, derived purely from
+/// the durable coordination state — the partition's assignment and any
+/// in-flight handoff. `PodHandle::converge` drives local state to match,
+/// so a pod whose memory has diverged from etcd (most notably after a
+/// crash-restart inside its lease TTL, which preserves its registration
+/// and assignments but wipes its cache and fences) is repaired by
+/// re-deriving rather than by replaying remembered events.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum DesiredState {
+ /// This pod owns the partition and no handoff constrains it: cache
+ /// warm, writes admitted. Also the old owner's state during Freezing
+ /// (routers are still collecting the freeze quorum; writes keep
+ /// flowing until every router has stashed).
+ Serving,
+ /// This pod is the old owner of a handoff past the freeze quorum:
+ /// writes fenced, inflight drained. `ack` is true while the protocol
+ /// is waiting on this pod's DrainedAck (phase Draining) and false once
+ /// the ack has been consumed (phase Warming) — re-acking after the
+ /// phase advanced would risk orphaning an ack past the coordinator's
+ /// cleanup. The cache is deliberately not warmed here: a cold restart
+ /// mid-handoff serves read errors until cutover (or until a
+ /// cancellation converges back to Serving, which warms).
+ Drained { ack: bool },
+ /// This pod is the new owner of a handoff in Warming: populate the
+ /// cache from Kafka and write a WarmedAck.
+ Acquiring,
+ /// This pod must not hold the partition: it isn't assigned to it, its
+ /// outbound handoff completed, or it is a new owner whose handoff
+ /// hasn't reached Warming (warming early would snapshot an HWM the old
+ /// owner is still advancing).
+ Released,
+}
+
+/// Pure derivation of a pod's desired state for a partition. The handoff,
+/// when it involves this pod, takes precedence over the assignment: the
+/// assignment names the *old* owner (or nobody) for the whole life of a
+/// handoff and only flips to the new owner atomically at Complete.
+fn desired_state(
+ pod: &str,
+ assignment: Option<&PartitionAssignment>,
+ handoff: Option<&HandoffState>,
+) -> DesiredState {
+ if let Some(h) = handoff {
+ if h.old_owner.as_deref() == Some(pod) {
+ return match h.phase {
+ HandoffPhase::Freezing => DesiredState::Serving,
+ HandoffPhase::Draining => DesiredState::Drained { ack: true },
+ HandoffPhase::Warming => DesiredState::Drained { ack: false },
+ HandoffPhase::Complete => DesiredState::Released,
+ };
+ }
+ if h.new_owner == pod {
+ return match h.phase {
+ HandoffPhase::Freezing | HandoffPhase::Draining => DesiredState::Released,
+ HandoffPhase::Warming => DesiredState::Acquiring,
+ // The assignment flips to this pod in the same txn that
+ // writes Complete.
+ HandoffPhase::Complete => DesiredState::Serving,
+ };
+ }
+ // A handoff between two other pods constrains nothing for this
+ // one; fall through to the assignment.
+ }
+ match assignment {
+ Some(a) if a.owner == pod => DesiredState::Serving,
+ _ => DesiredState::Released,
+ }
+}
+
/// Trait for the application-layer handoff handler on writer pods.
///
/// Implementations do the actual work of draining, warming, and releasing
@@ -44,6 +114,17 @@ pub trait HandoffHandler: Send + Sync {
///
/// Called when this pod is `old_owner` and handoff phase reaches `Complete`.
async fn release_partition(&self, partition: u32) -> Result<()>;
+
+ /// The handoff for a partition this pod still owns was cancelled before
+ /// completing (e.g. the new owner died mid-warm and the coordinator
+ /// deleted the record). The pod remains the owner and must resume
+ /// normal service — in particular, re-admit any writes it fenced when
+ /// it drained.
+ ///
+ /// Called when a handoff record is deleted while this pod still holds
+ /// the partition (a delete after `Complete` is normal cleanup and does
+ /// not trigger this).
+ async fn resume_partition(&self, partition: u32) -> Result<()>;
}
#[derive(Debug, Clone)]
@@ -80,8 +161,14 @@ pub struct PodHandle {
store: Arc<PersonhogStore>,
config: PodConfig,
handler: Arc<dyn HandoffHandler>,
- /// Partitions this pod has warmed. Used to avoid re-warming on assignment watches.
- owned_partitions: Mutex<HashSet<u32>>,
+ /// Partitions warmed by this process — local, dies with the process.
+ /// `converge` consults it to decide whether a Serving/Acquiring
+ /// partition still needs a warm, and `drain()` waits for it to empty.
+ warmed_partitions: Mutex<HashSet<u32>>,
+ /// 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>>,
/// Signalled when a partition is released, waking `drain()` without polling.
drain_notify: Notify,
/// Optional K8s awareness for departure classification during shutdown.
@@ -99,7 +186,8 @@ impl PodHandle {
store,
config,
handler,
- owned_partitions: Mutex::new(HashSet::new()),
+ warmed_partitions: Mutex::new(HashSet::new()),
+ fenced_partitions: Mutex::new(HashSet::new()),
drain_notify: Notify::new(),
k8s_awareness,
}
@@ -122,7 +210,7 @@ impl PodHandle {
// This keeps the lease alive so the coordinator sees a Draining pod
// (not a crashed one with an expired lease).
let heartbeat_cancel = CancellationToken::new();
- let heartbeat_handle = {
+ let mut heartbeat_handle = {
let store = Arc::clone(&self.store);
let interval = self.config.heartbeat_interval;
let token = heartbeat_cancel.child_token();
@@ -144,22 +232,73 @@ impl PodHandle {
// re-polled. Racing the cancel token at this level drops the
// in-flight loop future via cancel-by-drop, unwinding any stuck
// handler and letting the pod proceed to drain + lease revoke.
+ //
+ // The heartbeat task is raced here too: the coordinator treats
+ // lease expiry as pod death and hands this pod's partitions to
+ // new owners, so a pod that outlives its lease is a zombie — it
+ // would keep accepting writes for partitions the protocol has
+ // already moved. Losing the lease therefore terminates the run
+ // loop (self-fence) and the process restarts through the normal
+ // lifecycle.
+ let mut lease_lost = false;
let result = tokio::select! {
- r = self.watch_handoff_loop(cancel.clone()) => r,
+ r = async {
+ // Converge every partition this pod is involved in before
+ // watching for new events. A pod that crash-restarts within
+ // its lease TTL keeps its registration and assignments but
+ // loses all in-memory state (cache, fences) — and because
+ // nothing about etcd changed, no event will ever arrive to
+ // repair the divergence. Re-deriving local state from the
+ // durable state at startup closes that structurally: cold
+ // assigned partitions re-warm, in-flight handoffs get their
+ // drain/warm/ack, completed ones release. The watch is
+ // anchored to the snapshot's revision, so an event landing
+ // between the snapshot and the watch attaching is replayed
+ // rather than lost.
+ let snapshot_revision = self.reconcile_all().await?;
+ let stream = self.store.watch_handoffs_from(snapshot_revision + 1).await?;
+ self.watch_handoff_loop(stream, cancel.clone()).await
+ } => r,
+ r = &mut heartbeat_handle => {
+ lease_lost = true;
+ let err = match r {
+ Ok(Ok(())) => {
+ Error::invalid_state("lease keepalive exited unexpectedly".to_string())
+ }
+ Ok(Err(e)) => e,
+ Err(join_err) => {
+ Error::invalid_state(format!("keepalive task panicked: {join_err}"))
+ }
+ };
+ tracing::error!(
+ pod = %self.config.pod_name,
+ error = %err,
+ "lease keepalive failed; self-fencing"
+ );
+ Err(err)
+ }
_ = cancel.cancelled() => Ok(()),
};
- // Phase 2: If cancelled externally (SIGTERM), drain gracefully
- if cancel.is_cancelled() {
+ // Phase 2: If cancelled externally (SIGTERM), drain gracefully.
+ // Skipped on lease loss: the coordinator already considers this
+ // pod dead and is reassigning its partitions via the dead-owner
+ // path — a graceful drain would race it, and every status write
+ // would fail against the expired lease anyway.
+ if cancel.is_cancelled() && !lease_lost {
if let Err(e) = self.drain(lease_id).await {
tracing::warn!(pod = %self.config.pod_name, error = %e, "drain failed");
}
}
- // Cleanup: stop heartbeat and revoke lease
- heartbeat_cancel.cancel();
- drop(heartbeat_handle.await);
- drop(self.store.revoke_lease(lease_id).await);
+ // Cleanup: stop heartbeat and revoke lease. On lease loss the
+ // heartbeat task has already exited (its handle must not be
+ // awaited twice) and there is no lease left to revoke.
+ if !lease_lost {
+ heartbeat_cancel.cancel();
+ drop(heartbeat_handle.await);
+ drop(self.store.revoke_lease(lease_id).await);
+ }
result
}
@@ -224,24 +363,32 @@ impl PodHandle {
"set status to Draining, waiting for partition handoffs"
);
- if self.owned_partitions.lock().await.is_empty() {
+ if self.held_partition_count().await == 0 {
tracing::info!(pod = %self.config.pod_name, "no partitions to drain");
return Ok(());
}
- // Keep watching handoffs during drain so we can release partitions
- // when the coordinator completes them.
+ // 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 snapshot_revision = self.reconcile_all().await?;
+ let stream = self
+ .store
+ .watch_handoffs_from(snapshot_revision + 1)
+ .await?;
tokio::select! {
- r = self.watch_handoff_loop(drain_cancel.clone()) => {
+ r = self.watch_handoff_loop(stream, drain_cancel.clone()) => {
r?;
},
_ = self.wait_for_drain() => {
tracing::info!(pod = %self.config.pod_name, "all partitions drained successfully");
},
_ = tokio::time::sleep(self.config.drain_timeout) => {
- let remaining = self.owned_partitions.lock().await.len();
+ let remaining = self.held_partition_count().await;
tracing::warn!(
pod = %self.config.pod_name,
remaining_partitions = remaining,
@@ -254,106 +401,330 @@ impl PodHandle {
Ok(())
}
- /// Wait until all owned partitions have been released via handoffs.
+ /// Number of partitions this process still holds state for — warmed
+ /// 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;
+ warmed.union(&fenced).count()
+ }
+
+ /// Wait until all held partitions have been released via handoffs.
/// Woken reactively by `drain_notify` each time a partition is released.
async fn wait_for_drain(&self) {
loop {
- if self.owned_partitions.lock().await.is_empty() {
+ if self.held_partition_count().await == 0 {
return;
}
self.drain_notify.notified().await;
}
}
- async fn watch_handoff_loop(&self, cancel: CancellationToken) -> Result<()> {
- let mut stream = self.store.watch_handoffs().await?;
+ /// Converge every partition this pod is involved in — assigned to it,
+ /// or named in a handoff as old or new owner — from a consistent
+ /// snapshot of the durable state. Returns the smaller of the two
+ /// snapshot revisions so the caller can anchor the handoff watch: any
+ /// change landing between the two reads (or between them and the watch
+ /// attaching) is redelivered as an event and re-converged with fresh
+ /// reads.
+ async fn reconcile_all(&self) -> Result<i64> {
+ let (assignments, rev_a) = self.store.list_assignments_with_revision().await?;
+ let (handoffs, rev_h) = self.store.list_handoffs_with_revision().await?;
+ let pod = &self.config.pod_name;
+
+ let assignment_map: std::collections::HashMap<u32, &PartitionAssignment> =
+ assignments.iter().map(|a| (a.partition, a)).collect();
+ let handoff_map: std::collections::HashMap<u32, &HandoffState> =
+ handoffs.iter().map(|h| (h.partition, h)).collect();
+
+ let mut partitions: HashSet<u32> = HashSet::new();
+ for a in &assignments {
+ if a.owner == *pod {
+ partitions.insert(a.partition);
+ }
+ }
+ for h in &handoffs {
+ if h.old_owner.as_deref() == Some(pod.as_str()) || h.new_owner == *pod {
+ partitions.insert(h.partition);
+ }
+ }
+
+ tracing::info!(
+ pod,
+ partitions = partitions.len(),
+ "reconciling local state against durable state"
+ );
+ for partition in partitions {
+ self.apply(
+ partition,
+ assignment_map.get(&partition).copied(),
+ handoff_map.get(&partition).copied(),
+ )
+ .await?;
+ }
+
+ Ok(rev_a.min(rev_h))
+ }
+ /// 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
+ /// event payloads, so missed, reordered, or replayed events cannot
+ /// corrupt local state.
+ async fn converge(&self, partition: u32) -> Result<()> {
+ let handoff = self.store.get_handoff(partition).await?;
+ let assignment = self.store.get_assignment(partition).await?;
+ self.apply(partition, assignment.as_ref(), handoff.as_ref())
+ .await
+ }
+
+ /// Drive local state (cache warmth, write fence, acks, held set) to
+ /// the desired state. Every transition is idempotent; callers are
+ /// serialized (startup reconcile, then the single watch loop), so no
+ /// two applications for the same partition ever interleave.
+ async fn apply(
+ &self,
+ partition: u32,
+ assignment: Option<&PartitionAssignment>,
+ handoff: Option<&HandoffState>,
+ ) -> Result<()> {
+ let pod = &self.config.pod_name;
+ let desired = desired_state(pod, assignment, handoff);
+
+ match desired {
+ DesiredState::Serving => {
+ if !self.warmed_partitions.lock().await.contains(&partition) {
+ tracing::info!(pod, partition, "converging to Serving: warming");
+ self.handler.warm_partition(partition).await?;
+ self.warmed_partitions.lock().await.insert(partition);
+ } else if self.fenced_partitions.lock().await.contains(&partition) {
+ tracing::info!(pod, partition, "converging to Serving: resuming writes");
+ self.handler.resume_partition(partition).await?;
+ }
+ self.fenced_partitions.lock().await.remove(&partition);
+ }
+ DesiredState::Drained { ack } => {
+ // The coordinator only advances Freezing → Draining once
+ // every router has FreezeAcked, so no new request can flow
+ // from any router to this pod and the inflight==0 the drain
+ // waits for is meaningful. The produce path awaits Kafka
+ // delivery before returning, so "no inflight handlers"
+ // implies "every acked write is durable in Kafka."
+ if !self.fenced_partitions.lock().await.contains(&partition) {
+ tracing::info!(pod, partition, "converging to Drained: fencing + draining");
+ }
+ self.handler.drain_partition_inflight(partition).await?;
+ self.fenced_partitions.lock().await.insert(partition);
+ if ack {
+ let handoff = handoff.expect("Drained state only derives from a handoff");
+ self.store
+ .put_drained_ack(&PodDrainedAck {
+ pod_name: pod.clone(),
+ partition,
+ acked_at: util::now_seconds(),
+ handoff_id: handoff.handoff_id.clone(),
+ })
+ .await?;
+ tracing::info!(pod, partition, "drained ack written");
+ }
+ }
+ DesiredState::Acquiring => {
+ if !self.warmed_partitions.lock().await.contains(&partition) {
+ tracing::info!(pod, partition, "converging to Acquiring: warming");
+ self.handler.warm_partition(partition).await?;
+ self.warmed_partitions.lock().await.insert(partition);
+ }
+ self.fenced_partitions.lock().await.remove(&partition);
+ let handoff = handoff.expect("Acquiring state only derives from a handoff");
+ self.store
+ .put_warmed_ack(&PodWarmedAck {
+ pod_name: pod.clone(),
+ partition,
+ acked_at: util::now_seconds(),
+ handoff_id: handoff.handoff_id.clone(),
+ })
+ .await?;
+ tracing::info!(pod, partition, "warmed ack written");
+ }
+ DesiredState::Released => {
+ let was_warmed = self.warmed_partitions.lock().await.remove(&partition);
+ let was_fenced = self.fenced_partitions.lock().await.remove(&partition);
+ if was_warmed || was_fenced {
+ tracing::info!(pod, partition, "converging to Released: releasing");
+ self.handler.release_partition(partition).await?;
+ self.drain_notify.notify_one();
+ }
+ }
+ }
+
+ Ok(())
+ }
+
+ async fn watch_handoff_loop(
+ &self,
+ mut stream: WatchStream,
+ cancel: CancellationToken,
+ ) -> Result<()> {
loop {
tokio::select! {
_ = cancel.cancelled() => return Ok(()),
msg = stream.message() => {
let resp = msg?.ok_or_else(|| Error::invalid_state("handoff watch stream ended".to_string()))?;
for event in resp.events() {
- if event.event_type() == EventType::Put {
- match parse_watch_value::<HandoffState>(event) {
- Ok(handoff) => {
- self.handle_handoff_event(&handoff).await?;
- }
+ let partition = match event.event_type() {
+ EventType::Put => match parse_watch_value::<HandoffState>(event) {
+ Ok(handoff) => Some(handoff.partition),
Err(e) => {
tracing::error!(pod = %self.config.pod_name, error = %e, "failed to parse handoff");
+ None
}
- }
+ },
+ EventType::Delete => event
+ .kv()
+ .and_then(|kv| std::str::from_utf8(kv.key()).ok())
+ .and_then(store::extract_partition_from_key),
+ };
+ if let Some(partition) = partition {
+ self.converge(partition).await?;
}
}
}
}
}
}
+}
- async fn handle_handoff_event(&self, handoff: &HandoffState) -> Result<()> {
- let pod = &self.config.pod_name;
- let is_old_owner = handoff.old_owner.as_deref() == Some(pod.as_str());
-
- // Old owner: on Draining, drain inflight and write a DrainedAck.
- // The produce path awaits Kafka delivery before returning, so "no
- // inflight handlers" implies "every acked write is durable in Kafka."
- // The coordinator only advances Freezing → Draining once every
- // router has FreezeAcked, so by the time we observe Draining no
- // new request can flow from any router to this pod and the
- // inflight==0 check is meaningful.
- if is_old_owner && handoff.phase == HandoffPhase::Draining {
- tracing::info!(
- pod,
- partition = handoff.partition,
- "draining inflight for partition"
- );
- self.handler
- .drain_partition_inflight(handoff.partition)
- .await?;
-
- let ack = PodDrainedAck {
- pod_name: pod.clone(),
- partition: handoff.partition,
- acked_at: util::now_seconds(),
- };
- self.store.put_drained_ack(&ack).await?;
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::types::AssignmentStatus;
- tracing::info!(pod, partition = handoff.partition, "drained ack written");
- }
+ const POD: &str = "pod-self";
+ const OTHER: &str = "pod-other";
+ const THIRD: &str = "pod-third";
- // New owner: on Warming, populate cache from Kafka to current HWM,
- // then write a WarmedAck so the coordinator can advance to Complete.
- if handoff.new_owner == *pod && handoff.phase == HandoffPhase::Warming {
- tracing::info!(
- pod,
- partition = handoff.partition,
- "warming cache for partition"
- );
- self.handler.warm_partition(handoff.partition).await?;
- self.owned_partitions.lock().await.insert(handoff.partition);
-
- let ack = PodWarmedAck {
- pod_name: pod.clone(),
- partition: handoff.partition,
- acked_at: util::now_seconds(),
- };
- self.store.put_warmed_ack(&ack).await?;
-
- tracing::info!(pod, partition = handoff.partition, "warmed ack written");
+ fn assignment(owner: &str) -> PartitionAssignment {
+ PartitionAssignment {
+ partition: 1,
+ owner: owner.to_string(),
+ status: AssignmentStatus::Active,
}
+ }
- // Old owner: release on Complete. Skipped when old_owner is None
- // (initial assignment) — there is nothing to release.
- if is_old_owner && handoff.phase == HandoffPhase::Complete {
- tracing::info!(pod, partition = handoff.partition, "releasing partition");
- self.handler.release_partition(handoff.partition).await?;
- self.owned_partitions
- .lock()
- .await
- .remove(&handoff.partition);
- self.drain_notify.notify_one();
+ fn handoff(old_owner: Option<&str>, new_owner: &str, phase: HandoffPhase) -> HandoffState {
+ HandoffState {
+ partition: 1,
+ old_owner: old_owner.map(str::to_string),
+ new_owner: new_owner.to_string(),
+ phase,
+ started_at: 0,
+ handoff_id: "h-test".to_string(),
}
+ }
- Ok(())
+ #[test]
+ fn desired_state_covers_the_full_role_phase_matrix() {
+ use DesiredState::*;
+ use HandoffPhase::*;
+
+ // (case, assignment, handoff, expected). Assignments mirror what
+ // the protocol would hold at that point: they name the old owner
+ // (or nobody) until Complete flips them to the new owner.
+ let cases: Vec<(
+ &str,
+ Option<PartitionAssignment>,
+ Option<HandoffState>,
+ DesiredState,
+ )> = vec![
+ (
+ "old owner serves through Freezing",
+ Some(assignment(POD)),
+ Some(handoff(Some(POD), OTHER, Freezing)),
+ Serving,
+ ),
+ (
+ "old owner drains and acks in Draining",
+ Some(assignment(POD)),
+ Some(handoff(Some(POD), OTHER, Draining)),
+ Drained { ack: true },
+ ),
+ (
+ "old owner stays drained without re-acking in Warming",
+ Some(assignment(POD)),
+ Some(handoff(Some(POD), OTHER, Warming)),
+ Drained { ack: false },
+ ),
+ (
+ "old owner releases at Complete",
+ Some(assignment(OTHER)),
+ Some(handoff(Some(POD), OTHER, Complete)),
+ Released,
+ ),
+ (
+ "new owner must not hold the partition in Freezing",
+ Some(assignment(OTHER)),
+ Some(handoff(Some(OTHER), POD, Freezing)),
+ Released,
+ ),
+ (
+ "new owner must not warm early in Draining",
+ Some(assignment(OTHER)),
+ Some(handoff(Some(OTHER), POD, Draining)),
+ Released,
+ ),
+ (
+ "new owner acquires in Warming",
+ Some(assignment(OTHER)),
+ Some(handoff(Some(OTHER), POD, Warming)),
+ Acquiring,
+ ),
+ (
+ "new owner serves at Complete",
+ Some(assignment(POD)),
+ Some(handoff(Some(OTHER), POD, Complete)),
+ Serving,
+ ),
+ (
+ "initial assignment (no old owner) acquires in Warming",
+ None,
+ Some(handoff(None, POD, Warming)),
+ Acquiring,
+ ),
+ (
+ "handoff between two other pods defers to owned assignment",
+ Some(assignment(POD)),
+ Some(handoff(Some(OTHER), THIRD, Draining)),
+ Serving,
+ ),
+ (
+ "handoff between two other pods defers to unowned assignment",
+ Some(assignment(OTHER)),
+ Some(handoff(Some(OTHER), THIRD, Warming)),
+ Released,
+ ),
+ (
+ "no handoff: owned assignment serves",
+ Some(assignment(POD)),
+ None,
+ Serving,
+ ),
+ (
+ "no handoff: someone else's assignment releases",
+ Some(assignment(OTHER)),
+ None,
+ Released,
+ ),
+ ("no assignment at all releases", None, None, Released),
+ ];
+
+ for (case, assignment, handoff, expected) in cases {
+ assert_eq!(
+ desired_state(POD, assignment.as_ref(), handoff.as_ref()),
+ expected,
+ "{case}"
+ );
+ }
}
}
diff --git a/rust/personhog-coordination/src/routing_table.rs b/rust/personhog-coordination/src/routing_table.rs
index 738dff3e9b69..55554f546756 100644
--- a/rust/personhog-coordination/src/routing_table.rs
+++ b/rust/personhog-coordination/src/routing_table.rs
@@ -3,7 +3,7 @@ use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
-use etcd_client::EventType;
+use etcd_client::{EventType, WatchStream};
use tokio::sync::RwLock;
use tokio_util::sync::CancellationToken;
@@ -119,9 +119,19 @@ impl RoutingTable {
let lease_id = self.store.grant_lease(self.config.lease_ttl).await?;
self.register_router(lease_id).await?;
- self.load_initial(&handler).await?;
+ let snapshot_revision = self.load_initial(&handler).await?;
- // Run heartbeat, assignment watch, and handoff watch concurrently
+ // Anchor the handoff watch to the snapshot's revision: every event
+ // at or before it was handled by `load_initial`, every later one
+ // is replayed by the watch regardless of when it attaches. Without
+ // the anchor, an event landing between the snapshot read and the
+ // watch attaching is in neither and is never redelivered.
+ let handoff_stream = self
+ .store
+ .watch_handoffs_from(snapshot_revision + 1)
+ .await?;
+
+ // Run heartbeat and handoff watch concurrently
let mut tasks = tokio::task::JoinSet::new();
{
@@ -140,7 +150,8 @@ impl RoutingTable {
let router_name = self.config.router_name.clone();
let token = cancel.child_token();
tasks.spawn(async move {
- Self::watch_handoffs_loop(store, table, handler, router_name, token).await
+ Self::watch_handoffs_loop(store, table, handler, router_name, token, handoff_stream)
+ .await
});
}
@@ -167,21 +178,23 @@ impl RoutingTable {
self.store.register_router(&router, lease_id).await
}
- async fn load_initial(&self, handler: &Arc<dyn StashHandler>) -> Result<()> {
- let assignments = self.store.list_assignments().await?;
- let mut table = self.table.write().await;
- for a in assignments {
- table.insert(a.partition, a.owner);
- }
- tracing::info!(count = table.len(), "loaded initial routing table");
- drop(table);
-
- // Catch up on any in-progress handoffs. A late-joining router that
- // observes a non-terminal handoff needs to begin stashing — and if
- // we're still in Freezing, also write a FreezeAck so the
- // coordinator's quorum can progress. Handoffs already at Complete
- // arrive as a normal Put event through the watch loop below.
- let handoffs = self.store.list_handoffs().await?;
+ /// Returns the etcd revision of the handoff snapshot, so the caller
+ /// can anchor the handoff watch to it.
+ async fn load_initial(&self, handler: &Arc<dyn StashHandler>) -> Result<i64> {
+ // Catch up on any in-progress handoffs BEFORE populating the
+ // routing table. The table starts empty, so every lookup fails
+ // closed until it is loaded; opening the stashes first guarantees
+ // that by the time a mid-handoff partition becomes routable it is
+ // already stashing. In the reverse order there is a window where a
+ // write routes to the old owner with no stash open — potentially
+ // after the old owner has already drained.
+ //
+ // A late-joining router that observes a non-terminal handoff needs
+ // to begin stashing — and if we're still in Freezing, also write a
+ // FreezeAck so the coordinator's quorum can progress. Handoffs
+ // 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?;
for handoff in handoffs {
if matches!(
handoff.phase,
@@ -210,13 +223,22 @@ impl RoutingTable {
router_name: self.config.router_name.clone(),
partition: handoff.partition,
acked_at: util::now_seconds(),
+ handoff_id: handoff.handoff_id.clone(),
};
self.store.put_freeze_ack(&ack).await?;
}
}
}
- Ok(())
+ let assignments = self.store.list_assignments().await?;
+ let mut table = self.table.write().await;
+ for a in assignments {
+ table.insert(a.partition, a.owner);
+ }
+ tracing::info!(count = table.len(), "loaded initial routing table");
+ drop(table);
+
+ Ok(snapshot_revision)
}
async fn watch_handoffs_loop(
@@ -225,9 +247,8 @@ impl RoutingTable {
handler: Arc<dyn StashHandler>,
router_name: String,
cancel: CancellationToken,
+ mut stream: WatchStream,
) -> Result<()> {
- let mut stream = store.watch_handoffs().await?;
-
loop {
tokio::select! {
_ = cancel.cancelled() => return Ok(()),
@@ -320,6 +341,7 @@ impl RoutingTable {
router_name: router_name.to_string(),
partition: handoff.partition,
acked_at: util::now_seconds(),
+ handoff_id: handoff.handoff_id.clone(),
};
store.put_freeze_ack(&ack).await?;
}
diff --git a/rust/personhog-coordination/src/store.rs b/rust/personhog-coordination/src/store.rs
index 324430a3942e..f1cfed326063 100644
--- a/rust/personhog-coordination/src/store.rs
+++ b/rust/personhog-coordination/src/store.rs
@@ -1,5 +1,5 @@
use assignment_coordination::store::EtcdStore;
-use etcd_client::{Compare, CompareOp, PutOptions, Txn, TxnOp, WatchStream};
+use etcd_client::{Compare, CompareOp, DeleteOptions, PutOptions, Txn, TxnOp, WatchStream};
use crate::error::{Error, Result};
use crate::types::{
@@ -132,6 +132,19 @@ impl PersonhogStore {
Ok(self.inner.watch(&key).await?)
}
+ /// Watch pod registrations from an explicit revision (inclusive),
+ /// 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> {
+ 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> {
+ Ok(self.inner.current_revision().await?)
+ }
+
// ── Router operations ────────────────────────────────────────
pub async fn register_router(&self, router: &RegisteredRouter, lease_id: i64) -> Result<()> {
@@ -161,6 +174,13 @@ impl PersonhogStore {
Ok(self.inner.list(&key).await?)
}
+ /// 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)> {
+ let key = self.key(StoreKey::AssignmentsPrefix);
+ Ok(self.inner.list_with_revision(&key).await?)
+ }
+
pub async fn put_assignments(&self, assignments: &[PartitionAssignment]) -> Result<()> {
if assignments.is_empty() {
return Ok(());
@@ -190,6 +210,14 @@ impl PersonhogStore {
Ok(self.inner.list(&key).await?)
}
+ /// Like `list_handoffs`, but also returns the etcd revision of the
+ /// 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)> {
+ let key = self.key(StoreKey::HandoffsPrefix);
+ Ok(self.inner.list_with_revision(&key).await?)
+ }
+
pub async fn put_handoff(&self, handoff: &HandoffState) -> Result<()> {
let key = self.key(StoreKey::Handoff(handoff.partition));
Ok(self.inner.put(&key, handoff, None).await?)
@@ -197,7 +225,9 @@ impl PersonhogStore {
/// Compare-and-swap a handoff's phase. Reads the current handoff,
/// verifies its phase matches `expected`, and writes a copy with
- /// `new_phase` only if the etcd key version hasn't changed.
+ /// `new_phase` only if the etcd key's mod_revision hasn't changed —
+ /// mod_revision rather than version, so the guard can never match a
+ /// different incarnation of the key after a delete-and-recreate.
///
/// Returns `Ok(true)` if the swap succeeded, `Ok(false)` if the handoff
/// was concurrently modified or its phase no longer matches `expected`.
@@ -211,9 +241,9 @@ impl PersonhogStore {
new_phase: crate::types::HandoffPhase,
) -> Result<bool> {
let handoff_key = self.key(StoreKey::Handoff(partition));
- let Some((mut handoff, version)) = self
+ let Some((mut handoff, mod_revision)) = self
.inner
- .get_versioned::<HandoffState>(&handoff_key)
+ .get_with_mod_revision::<HandoffState>(&handoff_key)
.await?
else {
return Ok(false);
@@ -223,10 +253,10 @@ impl PersonhogStore {
}
handoff.phase = new_phase;
let txn = Txn::new()
- .when(vec![Compare::version(
+ .when(vec![Compare::mod_revision(
handoff_key.clone(),
CompareOp::Equal,
- version,
+ mod_revision,
)])
.and_then(vec![TxnOp::put(
handoff_key,
@@ -237,6 +267,55 @@ impl PersonhogStore {
Ok(resp.succeeded())
}
+ /// Read a handoff along with its etcd mod_revision, for use with
+ /// `delete_handoff_and_acks_if_unchanged`.
+ pub async fn get_handoff_with_mod_revision(
+ &self,
+ partition: u32,
+ ) -> Result<Option<(HandoffState, i64)>> {
+ let key = self.key(StoreKey::Handoff(partition));
+ Ok(self.inner.get_with_mod_revision(&key).await?)
+ }
+
+ /// Atomically delete a handoff record and every ack written for its
+ /// partition — but only if the record's mod_revision still matches
+ /// `expected_mod_revision`. Cleanup decisions are made against snapshot
+ /// reads that can race a concurrent delete-and-recreate at the same
+ /// key (cancellation followed by an immediate rebalance); an unguarded
+ /// delete pair would destroy the healthy successor handoff and its
+ /// acks. Returns whether the delete happened.
+ pub async fn delete_handoff_and_acks_if_unchanged(
+ &self,
+ partition: u32,
+ expected_mod_revision: i64,
+ ) -> Result<bool> {
+ let handoff_key = self.key(StoreKey::Handoff(partition));
+ let prefix_delete = || Some(DeleteOptions::new().with_prefix());
+ let txn = Txn::new()
+ .when(vec![Compare::mod_revision(
+ handoff_key.clone(),
+ CompareOp::Equal,
+ expected_mod_revision,
+ )])
+ .and_then(vec![
+ TxnOp::delete(
+ self.key(StoreKey::FreezeAcksForPartition(partition)),
+ prefix_delete(),
+ ),
+ TxnOp::delete(
+ self.key(StoreKey::DrainedAcksForPartition(partition)),
+ prefix_delete(),
+ ),
+ TxnOp::delete(
+ self.key(StoreKey::WarmedAcksForPartition(partition)),
+ prefix_delete(),
+ ),
+ TxnOp::delete(handoff_key, None),
+ ]);
+ let resp = self.inner.txn(txn).await?;
+ Ok(resp.succeeded())
+ }
+
pub async fn delete_handoff(&self, partition: u32) -> Result<()> {
let key = self.key(StoreKey::Handoff(partition));
Ok(self.inner.delete(&key).await?)
@@ -247,6 +326,14 @@ impl PersonhogStore {
Ok(self.inner.watch(&key).await?)
}
+ /// Watch handoffs from an explicit revision (inclusive), replaying
+ /// events since that revision even if they predate the watch's
+ /// creation.
+ pub async fn watch_handoffs_from(&self, start_revision: i64) -> Result<WatchStream> {
+ let key = self.key(StoreKey::HandoffsPrefix);
+ Ok(self.inner.watch_from(&key, start_revision).await?)
+ }
+
// ── Freeze ack operations (router -> coordinator) ────────────
pub async fn put_freeze_ack(&self, ack: &RouterFreezeAck) -> Result<()> {
@@ -272,6 +359,11 @@ impl PersonhogStore {
Ok(self.inner.watch(&key).await?)
}
+ pub async fn watch_freeze_acks_from(&self, start_revision: i64) -> Result<WatchStream> {
+ let key = self.key(StoreKey::FreezeAcksPrefix);
+ Ok(self.inner.watch_from(&key, start_revision).await?)
+ }
+
// ── Drained ack operations (old owner -> coordinator) ────────
pub async fn put_drained_ack(&self, ack: &PodDrainedAck) -> Result<()> {
@@ -297,6 +389,11 @@ impl PersonhogStore {
Ok(self.inner.watch(&key).await?)
}
+ pub async fn watch_drained_acks_from(&self, start_revision: i64) -> Result<WatchStream> {
+ let key = self.key(StoreKey::DrainedAcksPrefix);
+ Ok(self.inner.watch_from(&key, start_revision).await?)
+ }
+
// ── Warmed ack operations (new owner -> coordinator) ─────────
pub async fn put_warmed_ack(&self, ack: &PodWarmedAck) -> Result<()> {
@@ -322,13 +419,9 @@ impl PersonhogStore {
Ok(self.inner.watch(&key).await?)
}
- /// Clean up every handoff-related ack for a partition. Called when a
- /// handoff is completed or cancelled.
- pub async fn delete_all_handoff_acks(&self, partition: u32) -> Result<()> {
- self.delete_freeze_acks(partition).await?;
- self.delete_drained_acks(partition).await?;
- self.delete_warmed_acks(partition).await?;
- Ok(())
+ pub async fn watch_warmed_acks_from(&self, start_revision: i64) -> Result<WatchStream> {
+ let key = self.key(StoreKey::WarmedAcksPrefix);
+ Ok(self.inner.watch_from(&key, start_revision).await?)
}
// ── Transactional operations ────────────────────────────────
@@ -375,9 +468,9 @@ impl PersonhogStore {
pub async fn complete_handoff(&self, partition: u32) -> Result<bool> {
let handoff_key = self.key(StoreKey::Handoff(partition));
- let (mut handoff, version) = self
+ let (mut handoff, mod_revision) = self
.inner
- .get_versioned::<HandoffState>(&handoff_key)
+ .get_with_mod_revision::<HandoffState>(&handoff_key)
.await?
.ok_or_else(|| Error::NotFound(format!("handoff for partition {partition}")))?;
@@ -392,10 +485,10 @@ impl PersonhogStore {
let assignment_key = self.key(StoreKey::Assignment(partition));
let txn = Txn::new()
- .when(vec![Compare::version(
+ .when(vec![Compare::mod_revision(
handoff_key.clone(),
CompareOp::Equal,
- version,
+ mod_revision,
)])
.and_then(vec![
TxnOp::put(handoff_key, serde_json::to_vec(&handoff)?, None),
diff --git a/rust/personhog-coordination/src/types.rs b/rust/personhog-coordination/src/types.rs
index edc821c87773..df4fd3e2c2f0 100644
--- a/rust/personhog-coordination/src/types.rs
+++ b/rust/personhog-coordination/src/types.rs
@@ -84,6 +84,14 @@ pub struct HandoffState {
pub new_owner: String,
pub phase: HandoffPhase,
pub started_at: i64,
+ /// Unique identity of this handoff attempt. Acks echo it, and the
+ /// coordinator's quorum checks only count acks whose id matches —
+ /// without this, an ack written for a previous handoff of the same
+ /// partition (e.g. re-put by a participant racing the coordinator's
+ /// ack cleanup) could satisfy a later handoff's quorum and advance it
+ /// past a drain or warm that never happened.
+ #[serde(default)]
+ pub handoff_id: String,
}
/// State machine for partition handoffs:
@@ -137,6 +145,10 @@ pub struct RouterFreezeAck {
pub router_name: String,
pub partition: u32,
pub acked_at: i64,
+ /// Echo of the handoff's `handoff_id`; the coordinator only counts
+ /// this ack toward the handoff whose id it names.
+ #[serde(default)]
+ pub handoff_id: String,
}
/// The old owner's acknowledgment that all inflight request handlers for a
@@ -150,6 +162,10 @@ pub struct PodDrainedAck {
pub pod_name: String,
pub partition: u32,
pub acked_at: i64,
+ /// Echo of the handoff's `handoff_id`; the coordinator only counts
+ /// this ack toward the handoff whose id it names.
+ #[serde(default)]
+ pub handoff_id: String,
}
/// The new owner's acknowledgment that it has consumed Kafka up to the stable
@@ -160,6 +176,10 @@ pub struct PodWarmedAck {
pub pod_name: String,
pub partition: u32,
pub acked_at: i64,
+ /// Echo of the handoff's `handoff_id`; the coordinator only counts
+ /// this ack toward the handoff whose id it names.
+ #[serde(default)]
+ pub handoff_id: String,
}
/// Written to `{prefix}coordinator/leader` by the coordinator that wins
@@ -221,6 +241,7 @@ mod tests {
new_owner: "personhog-writer-3".to_string(),
phase: HandoffPhase::Freezing,
started_at: 1700000000,
+ handoff_id: "1700000000000-0".to_string(),
};
let json = serde_json::to_string(&handoff).unwrap();
let deserialized: HandoffState = serde_json::from_str(&json).unwrap();
@@ -235,6 +256,7 @@ mod tests {
new_owner: "personhog-writer-3".to_string(),
phase: HandoffPhase::Freezing,
started_at: 1700000000,
+ handoff_id: "1700000000000-0".to_string(),
};
let json = serde_json::to_string(&handoff).unwrap();
let deserialized: HandoffState = serde_json::from_str(&json).unwrap();
@@ -247,6 +269,7 @@ mod tests {
router_name: "router-0".to_string(),
partition: 42,
acked_at: 1700000000,
+ handoff_id: "1700000000000-0".to_string(),
};
let json = serde_json::to_string(&ack).unwrap();
let deserialized: RouterFreezeAck = serde_json::from_str(&json).unwrap();
@@ -259,6 +282,7 @@ mod tests {
pod_name: "leader-0".to_string(),
partition: 42,
acked_at: 1700000000,
+ handoff_id: "1700000000000-0".to_string(),
};
let json = serde_json::to_string(&ack).unwrap();
let deserialized: PodDrainedAck = serde_json::from_str(&json).unwrap();
@@ -271,6 +295,7 @@ mod tests {
pod_name: "leader-1".to_string(),
partition: 42,
acked_at: 1700000000,
+ handoff_id: "1700000000000-0".to_string(),
};
let json = serde_json::to_string(&ack).unwrap();
let deserialized: PodWarmedAck = serde_json::from_str(&json).unwrap();
diff --git a/rust/personhog-coordination/src/util.rs b/rust/personhog-coordination/src/util.rs
index 2c8e327a34f5..bcd93319a51b 100644
--- a/rust/personhog-coordination/src/util.rs
+++ b/rust/personhog-coordination/src/util.rs
@@ -1,13 +1,26 @@
use std::sync::Arc;
-use std::time::Duration;
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio_util::sync::CancellationToken;
+use uuid::Uuid;
pub use assignment_coordination::util::now_seconds;
use crate::error::{Error, Result};
use crate::store::PersonhogStore;
+/// Generate a handoff id unique across handoff attempts. The uuid makes
+/// uniqueness structural — ids cannot collide across coordinator
+/// failovers even if the wall clock steps backward — while the millis
+/// prefix keeps ids sortable and debuggable.
+pub fn new_handoff_id() -> String {
+ let millis = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_millis())
+ .unwrap_or(0);
+ format!("{}-{}", millis, Uuid::new_v4())
+}
+
pub async fn run_lease_keepalive(
store: Arc<PersonhogStore>,
lease_id: i64,
@@ -21,10 +34,32 @@ pub async fn run_lease_keepalive(
_ = cancel.cancelled() => return Ok(()),
_ = tokio::time::sleep(interval) => {
keeper.keep_alive().await?;
- if stream.message().await?.is_none() {
- return Err(Error::leadership_lost());
+ match stream.message().await? {
+ None => return Err(Error::leadership_lost()),
+ // etcd answers keepalives for a revoked or expired
+ // lease with a normal response carrying TTL 0 — the
+ // stream stays open, so stream-end alone never
+ // detects lease loss.
+ Some(resp) if resp.ttl() <= 0 => return Err(Error::leadership_lost()),
+ Some(_) => {}
}
}
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::HashSet;
+
+ use super::new_handoff_id;
+
+ /// Quorum correlation and cancellation detection hang off id
+ /// uniqueness; ids minted in the same instant (a handoff cancelled
+ /// and recreated within one millisecond) must never collide.
+ #[test]
+ fn new_handoff_id_is_unique_within_same_instant() {
+ let ids: HashSet<String> = (0..1000).map(|_| new_handoff_id()).collect();
+ assert_eq!(ids.len(), 1000);
+ }
+}
diff --git a/rust/personhog-coordination/tests/common/mod.rs b/rust/personhog-coordination/tests/common/mod.rs
index f7deace1abfc..4238d9ecf9c5 100644
--- a/rust/personhog-coordination/tests/common/mod.rs
+++ b/rust/personhog-coordination/tests/common/mod.rs
@@ -22,15 +22,38 @@ pub const WAIT_TIMEOUT: Duration = Duration::from_secs(10);
pub const POLL_INTERVAL: Duration = Duration::from_millis(100);
pub async fn test_store(test_name: &str) -> Arc<PersonhogStore> {
+ test_store_with_prefix(test_name).await.0
+}
+
+/// Like `test_store`, but also returns the generated etcd prefix so tests
+/// can inspect or manipulate raw keys (e.g. revoking a component's lease).
+pub async fn test_store_with_prefix(test_name: &str) -> (Arc<PersonhogStore>, String) {
let prefix = format!("/test-{}-{}/", test_name, uuid::Uuid::new_v4());
let config = StoreConfig {
endpoints: vec![ETCD_ENDPOINT.to_string()],
- prefix,
+ prefix: prefix.clone(),
};
let inner = EtcdStore::connect(config)
.await
.expect("failed to connect to etcd");
- Arc::new(PersonhogStore::new(inner))
+ (Arc::new(PersonhogStore::new(inner)), prefix)
+}
+
+/// Revoke the etcd lease attached to `key`, simulating a component whose
+/// lease expired (etcd partition, missed heartbeats) while the process
+/// itself is still running.
+pub async fn revoke_lease_of_key(key: &str) {
+ let mut client = etcd_client::Client::connect([ETCD_ENDPOINT], None)
+ .await
+ .expect("connect raw etcd client");
+ let resp = client.get(key, None).await.expect("get key");
+ let kv = resp
+ .kvs()
+ .first()
+ .unwrap_or_else(|| panic!("key {key} not found"));
+ let lease_id = kv.lease();
+ assert_ne!(lease_id, 0, "key {key} has no lease attached");
+ client.lease_revoke(lease_id).await.expect("revoke lease");
}
pub async fn wait_for_condition<F, Fut>(timeout: Duration, interval: Duration, f: F)
@@ -74,6 +97,7 @@ pub fn start_coordinator_named(
keepalive_interval: Duration::from_secs(keepalive_secs),
election_retry_interval: Duration::from_secs(1),
rebalance_debounce_interval: Duration::from_millis(100),
+ reconcile_interval: Duration::from_millis(500),
},
strategy,
None,
@@ -193,6 +217,7 @@ pub fn start_pod_slow(
pub struct RouterHandles {
pub events: Arc<Mutex<Vec<CutoverEvent>>>,
pub table: Arc<tokio::sync::RwLock<std::collections::HashMap<u32, String>>>,
+ pub join_handle: Option<JoinHandle<Result<()>>>,
}
pub fn start_router(
@@ -200,19 +225,33 @@ pub fn start_router(
name: &str,
cancel: CancellationToken,
) -> RouterHandles {
+ start_router_with_lease_ttl(store, name, 10, cancel)
+}
+
+pub fn start_router_with_lease_ttl(
+ store: Arc<PersonhogStore>,
+ name: &str,
+ lease_ttl: i64,
+ cancel: CancellationToken,
+) -> RouterHandles {
+ let heartbeat_secs = (lease_ttl as u64 / 3).max(1);
let (handler, events) = MockCutoverHandler::new();
let router = RoutingTable::new(
store,
RoutingTableConfig {
router_name: name.to_string(),
- lease_ttl: 10,
- heartbeat_interval: Duration::from_secs(3),
+ lease_ttl,
+ heartbeat_interval: Duration::from_secs(heartbeat_secs),
},
);
let table = router.table_handle();
let token = cancel.child_token();
- tokio::spawn(async move { router.run(token, Arc::new(handler)).await });
- RouterHandles { events, table }
+ let join_handle = tokio::spawn(async move { router.run(token, Arc::new(handler)).await });
+ RouterHandles {
+ events,
+ table,
+ join_handle: Some(join_handle),
+ }
}
// ── Mock handlers ───────────────────────────────────────────────
@@ -222,6 +261,7 @@ pub enum HandoffEvent {
Drained(u32),
Warmed(u32),
Released(u32),
+ Resumed(u32),
}
pub struct MockHandoffHandler {
@@ -265,6 +305,14 @@ impl HandoffHandler for MockHandoffHandler {
.push(HandoffEvent::Released(partition));
Ok(())
}
+
+ async fn resume_partition(&self, partition: u32) -> Result<()> {
+ self.events
+ .lock()
+ .await
+ .push(HandoffEvent::Resumed(partition));
+ Ok(())
+ }
}
/// A handoff handler that blocks forever on warm_partition.
@@ -307,6 +355,14 @@ impl HandoffHandler for BlockingHandoffHandler {
.push(HandoffEvent::Released(partition));
Ok(())
}
+
+ async fn resume_partition(&self, partition: u32) -> Result<()> {
+ self.events
+ .lock()
+ .await
+ .push(HandoffEvent::Resumed(partition));
+ Ok(())
+ }
}
/// A handoff handler that adds a configurable delay to warm_partition.
@@ -355,6 +411,14 @@ impl HandoffHandler for SlowHandoffHandler {
.push(HandoffEvent::Released(partition));
Ok(())
}
+
+ async fn resume_partition(&self, partition: u32) -> Result<()> {
+ self.events
+ .lock()
+ .await
+ .push(HandoffEvent::Resumed(partition));
+ Ok(())
+ }
}
#[derive(Debug, Clone, PartialEq, Eq)]
diff --git a/rust/personhog-coordination/tests/integration.rs b/rust/personhog-coordination/tests/integration.rs
index 1dcda8f9ad30..6d61449fdc2d 100644
--- a/rust/personhog-coordination/tests/integration.rs
+++ b/rust/personhog-coordination/tests/integration.rs
@@ -1415,6 +1415,7 @@ async fn handoff_delete_drains_stash_to_current_owner() {
new_owner: "phantom-pod".to_string(),
phase: HandoffPhase::Freezing,
started_at: 0,
+ handoff_id: String::new(),
};
store.put_handoff(&stuck_handoff).await.unwrap();
@@ -1587,6 +1588,7 @@ async fn late_joining_router_during_warming_begins_stash() {
new_owner: "writer-1".to_string(),
phase: HandoffPhase::Warming,
started_at: 0,
+ handoff_id: String::new(),
};
store.put_handoff(&warming_handoff).await.unwrap();
@@ -1626,13 +1628,14 @@ async fn late_joining_router_during_warming_begins_stash() {
cancel.cancel();
}
-/// When a Freezing handoff has a dead `old_owner` (one that's not a
-/// registered pod), `cleanup_stale_handoffs` should delete it so the
-/// handoff doesn't stall waiting for a `PodDrainedAck` that will never
-/// come. Verified by injecting a stale handoff into etcd and triggering
-/// a pod-change event.
+/// A Freezing handoff whose `old_owner` is dead (not a registered pod)
+/// must still run to completion: the old owner plays no role in Freezing
+/// (routers ack the freeze), and Draining treats an absent old owner as
+/// vacuously drained. The handoff advances Freezing → Draining → Warming
+/// → Complete on the live new owner and is cleaned up by completion, not
+/// by `cleanup_stale_handoffs`.
#[tokio::test]
-async fn dead_old_owner_in_freezing_triggers_cleanup() {
+async fn dead_old_owner_in_freezing_advances_to_completion() {
use personhog_coordination::types::{HandoffPhase, HandoffState};
let store = test_store("dead-old-owner-freezing").await;
@@ -1640,38 +1643,32 @@ async fn dead_old_owner_in_freezing_triggers_cleanup() {
store.set_total_partitions(NUM_PARTITIONS).await.unwrap();
- // Inject a stale Freezing handoff: old_owner=phantom-old (never
- // registered as a pod), new_owner=writer-0 (will be registered next).
- // The DrainedAck for phantom-old will never be written, so without
- // cleanup the handoff would stall in Freezing forever.
+ // Inject a Freezing handoff: old_owner=phantom-old (never registered
+ // as a pod), new_owner=writer-0 (will be registered next).
let stale = HandoffState {
partition: 4,
old_owner: Some("phantom-old".to_string()),
new_owner: "writer-0".to_string(),
phase: HandoffPhase::Freezing,
started_at: 0,
+ handoff_id: String::new(),
};
store.put_handoff(&stale).await.unwrap();
let strategy: Arc<dyn AssignmentStrategy> = Arc::new(StickyBalancedStrategy);
let _coord = start_coordinator(Arc::clone(&store), strategy, cancel.clone());
let _router = start_router(Arc::clone(&store), "router-0", cancel.clone());
-
- // Starting writer-0 fires a pod-change event which calls
- // handle_pod_change_static → cleanup_stale_handoffs. The dead
- // old_owner check should detect the phantom and delete the handoff.
let _pod = start_pod(Arc::clone(&store), "writer-0", cancel.clone());
- // Wait for the stale handoff to be deleted and the system to settle.
+ // router-0 acks the freeze, the absent old owner drains vacuously,
+ // writer-0 warms and acks, and completion deletes the handoff. The
+ // deferred rebalance then assigns the remaining partitions.
let check_store = Arc::clone(&store);
wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
let store = Arc::clone(&check_store);
async move {
let handoffs = store.list_handoffs().await.unwrap_or_default();
let assignments = store.list_assignments().await.unwrap_or_default();
- // The stale handoff for partition 4 should be gone; full set
- // of assignments should be present once normal bootstrap
- // completes (independent of partition 4's stale handoff).
!handoffs
.iter()
.any(|h| h.partition == 4 && h.old_owner.as_deref() == Some("phantom-old"))
@@ -1705,6 +1702,7 @@ async fn late_joining_router_during_freezing_acks_and_stashes() {
new_owner: "writer-1".to_string(),
phase: HandoffPhase::Freezing,
started_at: 0,
+ handoff_id: String::new(),
};
store.put_handoff(&freezing_handoff).await.unwrap();
@@ -1782,6 +1780,7 @@ async fn handoff_delete_during_warming_drains_to_current_owner() {
new_owner: "phantom-pod".to_string(),
phase: HandoffPhase::Warming,
started_at: 0,
+ handoff_id: String::new(),
};
store.put_handoff(&stuck).await.unwrap();
@@ -1878,6 +1877,7 @@ async fn reconcile_advances_warming_with_pre_staged_warmed_ack() {
new_owner: "writer-1".to_string(),
phase: HandoffPhase::Warming,
started_at: 0,
+ handoff_id: String::new(),
};
store.put_handoff(&warming).await.unwrap();
store
@@ -1885,6 +1885,7 @@ async fn reconcile_advances_warming_with_pre_staged_warmed_ack() {
pod_name: "writer-1".to_string(),
partition: 6,
acked_at: 0,
+ handoff_id: String::new(),
})
.await
.unwrap();
@@ -1953,6 +1954,7 @@ async fn draining_old_owner_blocks_phase_advance() {
new_owner: "writer-new".to_string(),
phase: HandoffPhase::Freezing,
started_at: 0,
+ handoff_id: String::new(),
};
store.put_handoff(&handoff).await.unwrap();
@@ -1997,6 +1999,7 @@ async fn draining_old_owner_blocks_phase_advance() {
pod_name: "writer-draining".to_string(),
partition: 7,
acked_at: 0,
+ handoff_id: String::new(),
})
.await
.unwrap();
@@ -2016,11 +2019,12 @@ async fn draining_old_owner_blocks_phase_advance() {
cancel.cancel();
}
-/// `cleanup_stale_handoffs` must use registration presence, not Ready
-/// status, when judging whether a pod is gone. Otherwise a `Draining` pod
-/// in the middle of a handoff would have its handoff record deleted
-/// before it could write its `DrainedAck`. Regression test for that
-/// scenario.
+/// `cleanup_stale_handoffs` judges only the new owner; the old owner's
+/// state — Draining, or even fully deregistered — must never cause a
+/// handoff deletion. A `Draining` old owner mid-handoff is the most
+/// failure-prone shape: it still owes the protocol a `DrainedAck`, and
+/// deleting its handoff record would strand the drain. Regression test
+/// for cleanup wrongly keying off old-owner liveness.
#[tokio::test]
async fn draining_old_owner_does_not_trigger_cleanup() {
use personhog_coordination::types::{HandoffPhase, HandoffState, PodStatus, RegisteredPod};
@@ -2030,8 +2034,7 @@ async fn draining_old_owner_does_not_trigger_cleanup() {
store.set_total_partitions(NUM_PARTITIONS).await.unwrap();
- // Register a Draining pod with no DrainedAck written yet — the most
- // failure-prone state for `cleanup_stale_handoffs`.
+ // Register a Draining pod with no DrainedAck written yet.
let lease = store.grant_lease(30).await.unwrap();
let draining_pod = RegisteredPod {
pod_name: "writer-draining".to_string(),
@@ -2050,14 +2053,14 @@ async fn draining_old_owner_does_not_trigger_cleanup() {
new_owner: "writer-new".to_string(),
phase: HandoffPhase::Freezing,
started_at: 0,
+ handoff_id: String::new(),
};
store.put_handoff(&handoff).await.unwrap();
// Start the coordinator and a real pod. The new pod registering
- // triggers a pod-change event and runs `cleanup_stale_handoffs`. With
- // the bug, the Draining pod is "not active" and the handoff is
- // deleted as stuck-on-dead-old-owner. With the fix, the handoff
- // survives because the Draining pod's etcd key is still present.
+ // triggers a pod-change event and runs `cleanup_stale_handoffs`,
+ // which must leave the handoff alone: the new owner is live, and the
+ // old owner's state is not cleanup's concern.
let strategy: Arc<dyn AssignmentStrategy> = Arc::new(StickyBalancedStrategy);
let _coord = start_coordinator(Arc::clone(&store), strategy, cancel.clone());
let _new_pod = start_pod(Arc::clone(&store), "writer-new", cancel.clone());
@@ -2095,9 +2098,10 @@ async fn freezing_blocks_until_routers_ack_before_draining() {
store.set_total_partitions(NUM_PARTITIONS).await.unwrap();
- // Register both old and new owner pods so `cleanup_stale_handoffs`
- // doesn't delete the injected handoff. They don't run real
- // handlers — we just need their etcd registrations to exist.
+ // Register both owner pods: the new owner so `cleanup_stale_handoffs`
+ // doesn't delete the injected handoff, the old owner so the scenario
+ // matches a live in-flight handoff. They don't run real handlers — we
+ // just need their etcd registrations to exist.
let old_lease = store.grant_lease(60).await.unwrap();
let new_lease = store.grant_lease(60).await.unwrap();
for (name, lease) in [("writer-old", old_lease), ("writer-new", new_lease)] {
@@ -2137,6 +2141,7 @@ async fn freezing_blocks_until_routers_ack_before_draining() {
new_owner: "writer-new".to_string(),
phase: HandoffPhase::Freezing,
started_at: 0,
+ handoff_id: String::new(),
};
store.put_handoff(&handoff).await.unwrap();
@@ -2160,6 +2165,7 @@ async fn freezing_blocks_until_routers_ack_before_draining() {
router_name: "slow-router".to_string(),
partition: 1,
acked_at: 0,
+ handoff_id: String::new(),
})
.await
.unwrap();
@@ -2220,6 +2226,7 @@ async fn initial_assignment_skips_draining_phase() {
new_owner: "writer-new".to_string(),
phase: HandoffPhase::Freezing,
started_at: 0,
+ handoff_id: String::new(),
};
store.put_handoff(&handoff).await.unwrap();
@@ -2239,17 +2246,11 @@ async fn initial_assignment_skips_draining_phase() {
}
/// If the old owner dies *during* Draining (lease expiry, pod crash),
-/// the handoff must still progress — either by advancing via
-/// `check_phase_advance`'s "old_owner not registered" branch, or by
-/// being cleaned up and replaced via rebalance. Either way the
-/// partition must end up assigned to a healthy pod, not stuck in
-/// Draining indefinitely.
-///
-/// The actual path is racy: pod-change events run
-/// `cleanup_stale_handoffs` (which may delete) while ack-watch events
-/// can fire `check_phase_advance` (which may advance). The test
-/// asserts the end state — partition has an active assignment and no
-/// lingering Draining handoff — which both paths converge to.
+/// the handoff must still progress: `check_phase_advance`'s "old_owner
+/// not registered" branch treats the drain as vacuously complete, and
+/// the reconcile tick guarantees re-evaluation even if no watch event
+/// fires. The partition must end up assigned to a healthy pod, not
+/// stuck in Draining indefinitely.
#[tokio::test]
async fn dead_old_owner_in_draining_recovers() {
use personhog_coordination::types::{HandoffPhase, HandoffState, PodStatus, RegisteredPod};
@@ -2259,8 +2260,8 @@ async fn dead_old_owner_in_draining_recovers() {
store.set_total_partitions(NUM_PARTITIONS).await.unwrap();
- // Register both old and new owner. We need both initially so the
- // injected Draining handoff isn't immediately cleaned up.
+ // Register both owners so the injected handoff starts as a live
+ // in-flight Draining handoff waiting on a real DrainedAck.
let old_lease = store.grant_lease(60).await.unwrap();
let new_lease = store.grant_lease(60).await.unwrap();
for (name, lease) in [("writer-old", old_lease), ("writer-new", new_lease)] {
@@ -2282,6 +2283,7 @@ async fn dead_old_owner_in_draining_recovers() {
new_owner: "writer-new".to_string(),
phase: HandoffPhase::Draining,
started_at: 0,
+ handoff_id: String::new(),
};
store.put_handoff(&handoff).await.unwrap();
@@ -2302,10 +2304,8 @@ async fn dead_old_owner_in_draining_recovers() {
})
.await;
- // Kill the old owner. From this point, recovery must converge
- // regardless of which mechanism wins — direct advance via
- // check_phase_advance OR cleanup_stale_handoffs followed by
- // rebalance.
+ // Kill the old owner. The next re-evaluation (pod-change event or
+ // reconcile tick) must advance the drain vacuously.
store.delete_pod("writer-old").await.unwrap();
// End-state assertion: no Draining handoff lingers for partition
@@ -2380,6 +2380,7 @@ async fn reconcile_advances_draining_with_pre_staged_drained_ack() {
new_owner: "writer-new".to_string(),
phase: HandoffPhase::Draining,
started_at: 0,
+ handoff_id: String::new(),
};
store.put_handoff(&handoff).await.unwrap();
@@ -2388,6 +2389,7 @@ async fn reconcile_advances_draining_with_pre_staged_drained_ack() {
pod_name: "writer-old".to_string(),
partition: 5,
acked_at: 0,
+ handoff_id: String::new(),
})
.await
.unwrap();
@@ -2436,6 +2438,7 @@ async fn late_joining_router_during_draining_begins_stash_no_ack() {
new_owner: "writer-1".to_string(),
phase: HandoffPhase::Draining,
started_at: 0,
+ handoff_id: String::new(),
};
store.put_handoff(&draining_handoff).await.unwrap();
@@ -2518,6 +2521,7 @@ async fn handoff_delete_during_draining_drains_to_current_owner() {
new_owner: "phantom-pod".to_string(),
phase: HandoffPhase::Draining,
started_at: 0,
+ handoff_id: String::new(),
};
store.put_handoff(&stuck).await.unwrap();
diff --git a/rust/personhog-coordination/tests/k3s_integration.rs b/rust/personhog-coordination/tests/k3s_integration.rs
index 5ecf4fe438e7..c27386cfa946 100644
--- a/rust/personhog-coordination/tests/k3s_integration.rs
+++ b/rust/personhog-coordination/tests/k3s_integration.rs
@@ -378,6 +378,14 @@ impl HandoffHandler for MockHandler {
.push(HandoffEvent::Released(partition));
Ok(())
}
+
+ async fn resume_partition(&self, partition: u32) -> Result<()> {
+ self.events
+ .lock()
+ .await
+ .push(HandoffEvent::Resumed(partition));
+ Ok(())
+ }
}
fn start_pod_k8s(
diff --git a/rust/personhog-coordination/tests/protocol_hardening.rs b/rust/personhog-coordination/tests/protocol_hardening.rs
new file mode 100644
index 000000000000..fc445ea3147d
--- /dev/null
+++ b/rust/personhog-coordination/tests/protocol_hardening.rs
@@ -0,0 +1,1322 @@
+//! Regression tests for the handoff-protocol hardening pass: self-fencing
+//! on lease loss, post-drain write fencing, identity-based freeze quorum,
+//! pod state convergence (startup reconcile + event-driven re-derivation),
+//! the coordinator's reconcile tick, revision-anchored watches,
+//! ack-to-handoff correlation, and cleanup scoped to dead new owners.
+//!
+//! All tests run against a real etcd at localhost:2379 with per-test key
+//! prefixes, matching the conventions in `integration.rs`.
+
+mod common;
+
+use std::collections::HashMap;
+use std::sync::Arc;
+use std::time::Duration;
+
+use tokio::sync::{Mutex, RwLock};
+use tokio_util::sync::CancellationToken;
+
+use assignment_coordination::store::parse_watch_value;
+use async_trait::async_trait;
+use common::{
+ revoke_lease_of_key, start_coordinator, start_pod, start_pod_with_lease_ttl,
+ start_router_with_lease_ttl, test_store, test_store_with_prefix, wait_for_condition,
+ HandoffEvent, POLL_INTERVAL, WAIT_TIMEOUT,
+};
+use personhog_coordination::error::Result;
+use personhog_coordination::routing_table::{RoutingTable, RoutingTableConfig, StashHandler};
+use personhog_coordination::store::PersonhogStore;
+use personhog_coordination::strategy::StickyBalancedStrategy;
+use personhog_coordination::types::{
+ AssignmentStatus, HandoffPhase, HandoffState, PartitionAssignment, PodStatus, RegisteredPod,
+ RegisteredRouter, RouterFreezeAck,
+};
+
+/// Write a handoff record directly, bypassing the coordinator — gives the
+/// test full control over phase sequencing.
+async fn put_handoff(
+ store: &PersonhogStore,
+ partition: u32,
+ old_owner: Option<&str>,
+ new_owner: &str,
+ phase: HandoffPhase,
+) {
+ let handoff = HandoffState {
+ partition,
+ old_owner: old_owner.map(str::to_string),
+ new_owner: new_owner.to_string(),
+ phase,
+ started_at: 0,
+ handoff_id: format!("test-handoff-{partition}"),
+ };
+ store
+ .create_assignments_and_handoffs(&[], &[handoff])
+ .await
+ .expect("write handoff");
+}
+
+/// Wait until the pod's recorded events contain `expected`.
+async fn wait_for_event(events: &Arc<Mutex<Vec<HandoffEvent>>>, expected: HandoffEvent) {
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let events = Arc::clone(events);
+ let expected = expected.clone();
+ async move { events.lock().await.contains(&expected) }
+ })
+ .await;
+}
+
+// ============================================================
+// Fix 1: components self-fence when their lease disappears
+// ============================================================
+//
+// The coordinator treats lease expiry as component death: it reassigns a
+// "dead" pod's partitions and drops a "dead" router from the freeze
+// quorum. A component that keeps serving after losing its lease is a
+// zombie — a pod can accept writes for partitions the protocol has
+// already handed off (split-brain changelog produces), and a router can
+// forward writes without stashing during a freeze. Losing the lease must
+// therefore terminate the component's run loop so its process restarts
+// through the normal lifecycle.
+
+/// A pod whose lease is revoked externally (simulating expiry during an
+/// etcd partition or missed heartbeats) must exit its run loop rather
+/// than continue serving as a zombie owner.
+#[tokio::test]
+async fn pod_self_fences_when_lease_revoked() {
+ let (store, prefix) = test_store_with_prefix("pod-self-fence").await;
+ let cancel = CancellationToken::new();
+
+ // lease_ttl 5 → 1s heartbeat interval, so the keepalive observes the
+ // revocation within ~a second.
+ let mut pod = start_pod_with_lease_ttl(Arc::clone(&store), "fence-pod-0", 5, cancel.clone());
+
+ // Wait until the pod has registered (its lease-bound key exists).
+ 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 == "fence-pod-0"))
+ .unwrap_or(false)
+ }
+ })
+ .await;
+
+ revoke_lease_of_key(&format!("{prefix}pods/fence-pod-0")).await;
+
+ // The run loop must observe the dead lease and exit with an error —
+ // NOT keep serving. Generous timeout: one heartbeat tick plus slack.
+ let join = pod.join_handle.take().expect("join handle");
+ let result = tokio::time::timeout(Duration::from_secs(10), join)
+ .await
+ .expect("pod must self-fence after lease revocation instead of serving as a zombie")
+ .expect("pod task must not panic");
+ assert!(
+ result.is_err(),
+ "run() must surface the lease loss as an error so the process restarts"
+ );
+
+ cancel.cancel();
+}
+
+/// A router whose lease is revoked must likewise exit: the coordinator
+/// has already dropped it from the freeze quorum, so if it keeps serving
+/// it can forward writes to a draining old owner without stashing.
+#[tokio::test]
+async fn router_exits_when_lease_revoked() {
+ let (store, prefix) = test_store_with_prefix("router-self-fence").await;
+ let cancel = CancellationToken::new();
+
+ let mut router =
+ start_router_with_lease_ttl(Arc::clone(&store), "fence-router-0", 5, 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_routers()
+ .await
+ .map(|routers| routers.iter().any(|r| r.router_name == "fence-router-0"))
+ .unwrap_or(false)
+ }
+ })
+ .await;
+
+ revoke_lease_of_key(&format!("{prefix}routers/fence-router-0")).await;
+
+ let join = router.join_handle.take().expect("join handle");
+ let result = tokio::time::timeout(Duration::from_secs(10), join)
+ .await
+ .expect("router must exit after lease revocation instead of serving with a stale table")
+ .expect("router task must not panic");
+ assert!(
+ result.is_err(),
+ "run() must surface the lease loss as an error so the process restarts"
+ );
+
+ cancel.cancel();
+}
+
+// ============================================================
+// Cancelled handoffs converge on the durable state
+// ============================================================
+//
+// Draining fences the partition against writes on the old owner. When a
+// handoff is cancelled (`cleanup_stale_handoffs` deletes the record — e.g.
+// the new owner died mid-warm), the pod re-derives its state from what
+// etcd still says: if the assignment names it, it resumes serving (routers
+// drain their stashes back to it); if nothing assigns it the partition, it
+// releases whatever half-acquired state it holds.
+
+/// A handoff deleted mid-flight (after this pod drained as old owner)
+/// must trigger `resume_partition` on the pod the assignment still names.
+#[tokio::test]
+async fn pod_resumes_partition_when_cancelled_handoff_leaves_it_assigned() {
+ let store = test_store("handoff-cancel-resume").await;
+ let cancel = CancellationToken::new();
+
+ let pod = start_pod(Arc::clone(&store), "resume-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 == "resume-pod-a"))
+ .unwrap_or(false)
+ }
+ })
+ .await;
+
+ // Give the pod ownership of partition 0 through the real acquisition
+ // path: warm via an initial-assignment handoff, then complete it
+ // (which writes the assignment atomically) and clean up the record.
+ put_handoff(&store, 0, None, "resume-pod-a", HandoffPhase::Warming).await;
+ wait_for_event(&pod.events, HandoffEvent::Warmed(0)).await;
+ assert!(
+ store.complete_handoff(0).await.expect("complete"),
+ "complete_handoff must succeed"
+ );
+ store.delete_handoff(0).await.expect("cleanup");
+
+ // A later handoff moves the partition away; the pod drains (and, on
+ // the real leader, fences writes).
+ put_handoff(
+ &store,
+ 0,
+ Some("resume-pod-a"),
+ "resume-pod-b",
+ HandoffPhase::Draining,
+ )
+ .await;
+ wait_for_event(&pod.events, HandoffEvent::Drained(0)).await;
+
+ // The handoff is cancelled (new owner gone). The assignment still
+ // names this pod, so it must resume the partition.
+ store.delete_handoff(0).await.expect("delete handoff");
+ wait_for_event(&pod.events, HandoffEvent::Resumed(0)).await;
+
+ cancel.cancel();
+}
+
+/// A cancelled acquisition converges the other way: the pod warmed as new
+/// owner, but the assignment never flipped to it (that happens only at
+/// Complete), so on cancellation it must release the half-acquired
+/// partition rather than serve a partition nothing routes to.
+#[tokio::test]
+async fn pod_releases_partition_when_cancelled_handoff_leaves_it_unassigned() {
+ let store = test_store("handoff-cancel-release").await;
+ let cancel = CancellationToken::new();
+
+ let pod = start_pod(Arc::clone(&store), "release-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 == "release-pod-a"))
+ .unwrap_or(false)
+ }
+ })
+ .await;
+
+ // Mid-acquisition: warmed as new owner, no assignment written yet.
+ put_handoff(&store, 0, None, "release-pod-a", HandoffPhase::Warming).await;
+ wait_for_event(&pod.events, HandoffEvent::Warmed(0)).await;
+
+ // Cancellation deletes the record; nothing assigns the partition to
+ // this pod, so it must drop what it warmed.
+ store.delete_handoff(0).await.expect("delete handoff");
+ wait_for_event(&pod.events, HandoffEvent::Released(0)).await;
+ assert!(
+ !pod.events.lock().await.contains(&HandoffEvent::Resumed(0)),
+ "an unassigned partition must not be resumed"
+ );
+
+ cancel.cancel();
+}
+
+/// The record deletion after a normal `Complete` is cleanup, not a
+/// cancellation: the old owner has already released the partition and
+/// must NOT resume it.
+#[tokio::test]
+async fn handoff_cleanup_after_complete_does_not_resume() {
+ let store = test_store("handoff-cleanup-no-resume").await;
+ let cancel = CancellationToken::new();
+
+ let pod = start_pod(Arc::clone(&store), "cleanup-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 == "cleanup-pod-a"))
+ .unwrap_or(false)
+ }
+ })
+ .await;
+
+ put_handoff(&store, 0, None, "cleanup-pod-a", HandoffPhase::Warming).await;
+ wait_for_event(&pod.events, HandoffEvent::Warmed(0)).await;
+
+ // Normal completion: the pod releases the partition…
+ put_handoff(
+ &store,
+ 0,
+ Some("cleanup-pod-a"),
+ "cleanup-pod-b",
+ HandoffPhase::Complete,
+ )
+ .await;
+ wait_for_event(&pod.events, HandoffEvent::Released(0)).await;
+
+ // …then the coordinator deletes the record. No resume may fire.
+ store.delete_handoff(0).await.expect("delete handoff");
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ assert!(
+ !pod.events.lock().await.contains(&HandoffEvent::Resumed(0)),
+ "post-Complete cleanup must not resume a released partition"
+ );
+
+ cancel.cancel();
+}
+
+// ============================================================
+// Pod state convergence: local state is derived from etcd
+// ============================================================
+//
+// A crash-restart inside the lease TTL preserves a pod's registration and
+// assignments but wipes its memory (cache, fences), and — because nothing
+// in etcd changed — no event ever arrives to repair the divergence. The
+// pod therefore re-derives its per-partition state from the durable state
+// at startup and on every handoff event, instead of accumulating it from
+// remembered events.
+
+/// A pod that crash-restarts within its lease TTL must re-warm the
+/// partitions etcd assigns it. Without the startup reconcile, the same-name
+/// re-registration changes nothing in etcd, so no handoff is ever created
+/// and the pod would serve errors for its own partitions forever.
+#[tokio::test]
+async fn restarted_pod_rewarms_assigned_partitions() {
+ let store = test_store("restart-rewarm").await;
+ let cancel = CancellationToken::new();
+
+ store
+ .put_assignments(&[
+ PartitionAssignment {
+ partition: 0,
+ owner: "phoenix-pod".to_string(),
+ status: AssignmentStatus::Active,
+ },
+ PartitionAssignment {
+ partition: 1,
+ owner: "phoenix-pod".to_string(),
+ status: AssignmentStatus::Active,
+ },
+ ])
+ .await
+ .expect("write assignments");
+
+ // First incarnation warms its assigned partitions at startup.
+ let mut pod = start_pod(Arc::clone(&store), "phoenix-pod", cancel.clone());
+ wait_for_event(&pod.events, HandoffEvent::Warmed(0)).await;
+ wait_for_event(&pod.events, HandoffEvent::Warmed(1)).await;
+
+ // Crash: abort the run loop — no graceful drain, no lease revoke, so
+ // the registration and assignments survive untouched.
+ pod.join_handle.take().expect("join handle").abort();
+
+ // Second incarnation, same name, empty memory. It must converge back
+ // to warm on both partitions from the durable state alone.
+ let pod2 = start_pod(Arc::clone(&store), "phoenix-pod", cancel.clone());
+ wait_for_event(&pod2.events, HandoffEvent::Warmed(0)).await;
+ wait_for_event(&pod2.events, HandoffEvent::Warmed(1)).await;
+
+ cancel.cancel();
+}
+
+/// The full comment-2 scenario: a pod crash-restarts while its outbound
+/// handoff is Draining, participates in the drain from cold (fence + ack,
+/// deliberately without warming), and when the handoff is cancelled it
+/// converges back to Serving — warming the partition it never held in
+/// this process lifetime.
+#[tokio::test]
+async fn restarted_old_owner_serves_again_after_handoff_cancelled() {
+ let store = test_store("restart-cancel-serve").await;
+ let cancel = CancellationToken::new();
+
+ store
+ .put_assignments(&[PartitionAssignment {
+ partition: 0,
+ owner: "victim-pod".to_string(),
+ status: AssignmentStatus::Active,
+ }])
+ .await
+ .expect("write assignment");
+ put_handoff(
+ &store,
+ 0,
+ Some("victim-pod"),
+ "other-pod",
+ HandoffPhase::Draining,
+ )
+ .await;
+
+ // The pod boots cold with the handoff already Draining: it must fence
+ // and ack — but not warm, since the partition is on its way out.
+ let pod = start_pod(Arc::clone(&store), "victim-pod", cancel.clone());
+ wait_for_event(&pod.events, HandoffEvent::Drained(0)).await;
+ assert!(
+ !pod.events.lock().await.contains(&HandoffEvent::Warmed(0)),
+ "a draining partition must not be warmed on the way out"
+ );
+ let acks = store.list_drained_acks(0).await.expect("list acks");
+ assert!(
+ acks.iter()
+ .any(|a| a.pod_name == "victim-pod" && a.handoff_id == "test-handoff-0"),
+ "drained ack must be written and correlated to the handoff"
+ );
+
+ // Cancellation: the assignment still names this pod, so it converges
+ // to Serving — which from cold means warming.
+ store.delete_handoff(0).await.expect("delete handoff");
+ wait_for_event(&pod.events, HandoffEvent::Warmed(0)).await;
+
+ cancel.cancel();
+}
+
+/// A pod restarting while its outbound handoff is already in Warming must
+/// re-fence (its predecessor's fence died with it) without re-acking — the
+/// coordinator consumed the DrainedAck to reach Warming, and a late re-ack
+/// could outlive the handoff's cleanup and orphan into a future handoff.
+#[tokio::test]
+async fn restarted_old_owner_refences_when_handoff_in_warming() {
+ let store = test_store("restart-refence").await;
+ let cancel = CancellationToken::new();
+
+ store
+ .put_assignments(&[PartitionAssignment {
+ partition: 0,
+ owner: "frozen-pod".to_string(),
+ status: AssignmentStatus::Active,
+ }])
+ .await
+ .expect("write assignment");
+ put_handoff(
+ &store,
+ 0,
+ Some("frozen-pod"),
+ "other-pod",
+ HandoffPhase::Warming,
+ )
+ .await;
+
+ let pod = start_pod(Arc::clone(&store), "frozen-pod", cancel.clone());
+ wait_for_event(&pod.events, HandoffEvent::Drained(0)).await;
+
+ let acks = store.list_drained_acks(0).await.expect("list acks");
+ assert!(
+ acks.is_empty(),
+ "no DrainedAck may be written once the phase has advanced past Draining"
+ );
+
+ cancel.cancel();
+}
+
+// ============================================================
+// Cleanup deletes are guarded against recreation
+// ============================================================
+
+/// A cleanup delete acting on a stale snapshot must not destroy a
+/// successor handoff recreated at the same key (cancellation followed by
+/// an immediate rebalance). The guard must be etcd `mod_revision`, not
+/// the per-key `version`: version resets to 1 on recreation, so both
+/// incarnations of a once-written key look identical to a version guard.
+#[tokio::test]
+async fn guarded_handoff_delete_skips_recreated_handoff() {
+ let store = test_store("guarded-delete").await;
+
+ // First incarnation, snapshotted by a would-be deleter.
+ put_handoff(&store, 0, Some("pod-a"), "pod-dead", HandoffPhase::Freezing).await;
+ let (_, stale_revision) = store
+ .get_handoff_with_mod_revision(0)
+ .await
+ .expect("read")
+ .expect("handoff exists");
+
+ // Concurrent cancel + recreate at the same key, with an ack belonging
+ // to the successor.
+ store.delete_handoff(0).await.expect("cancel");
+ put_handoff(&store, 0, Some("pod-a"), "pod-live", HandoffPhase::Freezing).await;
+ store
+ .put_freeze_ack(&RouterFreezeAck {
+ router_name: "router-0".to_string(),
+ partition: 0,
+ acked_at: 0,
+ handoff_id: "test-handoff-0".to_string(),
+ })
+ .await
+ .expect("successor ack");
+
+ // The stale deleter must skip: the successor and its acks survive.
+ let deleted = store
+ .delete_handoff_and_acks_if_unchanged(0, stale_revision)
+ .await
+ .expect("guarded delete");
+ assert!(!deleted, "stale snapshot must not delete the successor");
+ let survivor = store
+ .get_handoff(0)
+ .await
+ .expect("read")
+ .expect("successor must survive");
+ assert_eq!(survivor.new_owner, "pod-live");
+ assert_eq!(
+ store.list_freeze_acks(0).await.expect("acks").len(),
+ 1,
+ "successor's acks must survive"
+ );
+
+ // A fresh read deletes record and acks atomically.
+ let (_, fresh_revision) = store
+ .get_handoff_with_mod_revision(0)
+ .await
+ .expect("read")
+ .expect("handoff exists");
+ assert!(store
+ .delete_handoff_and_acks_if_unchanged(0, fresh_revision)
+ .await
+ .expect("guarded delete"));
+ assert!(store.get_handoff(0).await.expect("read").is_none());
+ assert!(store.list_freeze_acks(0).await.expect("acks").is_empty());
+}
+
+// ============================================================
+// Acks correlate to their handoff
+// ============================================================
+
+/// An ack from the right participant but a previous handoff attempt must
+/// not satisfy the quorum: acks race the coordinator's cleanup, so an
+/// orphaned ack for the same partition can survive into the next handoff
+/// and would otherwise skip a drain or warm that never happened.
+#[tokio::test]
+async fn ack_for_previous_handoff_does_not_satisfy_quorum() {
+ let store = test_store("ack-correlation").await;
+ let cancel = CancellationToken::new();
+
+ // A live, registered router (registered directly so no watch loop
+ // acks on its behalf).
+ let lease_id = store.grant_lease(30).await.expect("lease");
+ store
+ .register_router(
+ &RegisteredRouter {
+ router_name: "r-live".to_string(),
+ registered_at: 0,
+ last_heartbeat: 0,
+ },
+ lease_id,
+ )
+ .await
+ .expect("register router");
+
+ // An ack from this same router, but echoing a previous handoff's id —
+ // the orphan a cleanup race can leave behind.
+ store
+ .put_freeze_ack(&RouterFreezeAck {
+ router_name: "r-live".to_string(),
+ partition: 0,
+ acked_at: 0,
+ handoff_id: "a-previous-handoff".to_string(),
+ })
+ .await
+ .expect("write stale ack");
+
+ let _coord = start_coordinator(
+ Arc::clone(&store),
+ Arc::new(StickyBalancedStrategy),
+ cancel.clone(),
+ );
+
+ put_handoff(
+ &store,
+ 0,
+ Some("pod-old"),
+ "pod-new",
+ HandoffPhase::Freezing,
+ )
+ .await;
+
+ // Identity matches, id doesn't: the quorum must not be satisfied.
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ let handoff = store
+ .get_handoff(0)
+ .await
+ .expect("get handoff")
+ .expect("handoff exists");
+ assert_eq!(
+ handoff.phase,
+ HandoffPhase::Freezing,
+ "an ack from a previous handoff attempt must not satisfy this one's quorum"
+ );
+
+ // The correlated ack clears the quorum.
+ store
+ .put_freeze_ack(&RouterFreezeAck {
+ router_name: "r-live".to_string(),
+ partition: 0,
+ acked_at: 0,
+ handoff_id: "test-handoff-0".to_string(),
+ })
+ .await
+ .expect("write correlated ack");
+
+ let check_store = Arc::clone(&store);
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ 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();
+}
+
+/// An ack written by a pre-`handoff_id` binary (the JSON has no
+/// `handoff_id` field, so it deserializes to "") must not satisfy the
+/// quorum of a handoff carrying a real id. This is the rolling-upgrade
+/// skew case: mixed fleets must fail safe by stalling until the
+/// participant re-acks with the correct id, never by advancing on a
+/// legacy ack.
+#[tokio::test]
+async fn legacy_ack_without_handoff_id_does_not_satisfy_quorum() {
+ let (store, prefix) = test_store_with_prefix("legacy-ack").await;
+ let cancel = CancellationToken::new();
+
+ let lease_id = store.grant_lease(30).await.expect("lease");
+ store
+ .register_router(
+ &RegisteredRouter {
+ router_name: "r-legacy".to_string(),
+ registered_at: 0,
+ last_heartbeat: 0,
+ },
+ lease_id,
+ )
+ .await
+ .expect("register router");
+
+ // Write the ack exactly as an old binary would: raw JSON with no
+ // `handoff_id` field at all.
+ let mut raw = etcd_client::Client::connect([common::ETCD_ENDPOINT], None)
+ .await
+ .expect("connect raw etcd client");
+ raw.put(
+ format!("{prefix}freeze_acks/0/r-legacy"),
+ r#"{"router_name":"r-legacy","partition":0,"acked_at":0}"#,
+ None,
+ )
+ .await
+ .expect("write legacy ack");
+
+ // The legacy JSON must deserialize (serde default fills ""), not error.
+ let acks = store.list_freeze_acks(0).await.expect("list acks");
+ assert_eq!(acks.len(), 1);
+ assert_eq!(acks[0].handoff_id, "");
+
+ let _coord = start_coordinator(
+ Arc::clone(&store),
+ Arc::new(StickyBalancedStrategy),
+ cancel.clone(),
+ );
+
+ put_handoff(
+ &store,
+ 0,
+ Some("pod-old"),
+ "pod-new",
+ HandoffPhase::Freezing,
+ )
+ .await;
+
+ // Router name matches, id ("") doesn't: quorum must not be satisfied.
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ let handoff = store
+ .get_handoff(0)
+ .await
+ .expect("get handoff")
+ .expect("handoff exists");
+ assert_eq!(
+ handoff.phase,
+ HandoffPhase::Freezing,
+ "a legacy ack without a handoff_id must not satisfy an id-bearing handoff's quorum"
+ );
+
+ // A correlated re-ack (what the router writes once upgraded) clears it.
+ store
+ .put_freeze_ack(&RouterFreezeAck {
+ router_name: "r-legacy".to_string(),
+ partition: 0,
+ acked_at: 0,
+ handoff_id: "test-handoff-0".to_string(),
+ })
+ .await
+ .expect("write correlated ack");
+
+ let check_store = Arc::clone(&store);
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ 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();
+}
+
+// ============================================================
+// Cleanup owns only unprogressable handoffs
+// ============================================================
+//
+// A handoff whose OLD owner is dead progresses on its own: Freezing waits
+// on routers (not the old owner), and Draining treats an absent old owner
+// as vacuously drained. `cleanup_stale_handoffs` deleting such handoffs
+// was a second, competing mechanism for the same state — racing the
+// advance path and tearing down a healthy in-flight warm so rebalance
+// could recreate it from scratch. Cleanup's job is only the handoff that
+// truly cannot proceed: a dead NEW owner, whose WarmedAck will never
+// arrive.
+
+/// A Draining handoff with a dead old owner and a live new owner must
+/// advance in place (Draining → Warming, original record intact) rather
+/// than being deleted and recreated by rebalance.
+#[tokio::test]
+async fn dead_old_owner_handoff_advances_in_place_not_cleaned_up() {
+ let store = test_store("advance-not-cleanup").await;
+ let cancel = CancellationToken::new();
+
+ store.set_total_partitions(1).await.expect("partitions");
+
+ // The new owner is registered (directly — it never warms, so the
+ // handoff parks in Warming where we can observe it). The old owner
+ // was never registered: it is dead.
+ let lease = store.grant_lease(60).await.expect("lease");
+ store
+ .register_pod(
+ &RegisteredPod {
+ pod_name: "survivor".to_string(),
+ generation: String::new(),
+ status: PodStatus::Ready,
+ registered_at: 0,
+ last_heartbeat: 0,
+ controller: None,
+ },
+ lease,
+ )
+ .await
+ .expect("register survivor");
+
+ put_handoff(
+ &store,
+ 0,
+ Some("ghost-pod"),
+ "survivor",
+ HandoffPhase::Draining,
+ )
+ .await;
+
+ let _coord = start_coordinator(
+ Arc::clone(&store),
+ Arc::new(StickyBalancedStrategy),
+ cancel.clone(),
+ );
+
+ // The advance path must move the ORIGINAL record to Warming. A
+ // cleanup-and-recreate also produces a Warming handoff, but with
+ // old_owner None — so old_owner is the discriminator throughout.
+ let check_store = Arc::clone(&store);
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let store = Arc::clone(&check_store);
+ async move {
+ store
+ .get_handoff(0)
+ .await
+ .ok()
+ .flatten()
+ .is_some_and(|h| h.phase == HandoffPhase::Warming)
+ }
+ })
+ .await;
+
+ // A pod-change event re-runs cleanup; the parked handoff must not be
+ // touched. Register a bystander to trigger it, then hold the
+ // assertion across several reconcile ticks (500ms in tests).
+ let bystander_lease = store.grant_lease(60).await.expect("lease");
+ store
+ .register_pod(
+ &RegisteredPod {
+ pod_name: "bystander".to_string(),
+ generation: String::new(),
+ status: PodStatus::Ready,
+ registered_at: 0,
+ last_heartbeat: 0,
+ controller: None,
+ },
+ bystander_lease,
+ )
+ .await
+ .expect("register bystander");
+
+ for _ in 0..20 {
+ let handoff = store
+ .get_handoff(0)
+ .await
+ .expect("get handoff")
+ .expect("handoff must survive cleanup passes");
+ assert_eq!(
+ handoff.old_owner.as_deref(),
+ Some("ghost-pod"),
+ "must be the original record advanced in place, not a cleanup-and-recreate"
+ );
+ assert_eq!(handoff.phase, HandoffPhase::Warming);
+ tokio::time::sleep(POLL_INTERVAL).await;
+ }
+
+ cancel.cancel();
+}
+
+// ============================================================
+// Fix 6: revision-anchored watches (no snapshot→watch gap)
+// ============================================================
+//
+// Every participant bootstraps by reading a snapshot and then creating a
+// watch. An unanchored watch begins at "now": any event landing between
+// the snapshot read and the watch attaching is in neither, and etcd never
+// redelivers it — the protocol deadlocks waiting for a response to an
+// event nobody saw. Anchoring the watch to the snapshot's revision makes
+// the gap impossible: events ≤ rev are in the snapshot, events > rev are
+// replayed by the watch no matter when it attaches. This is the race
+// behind the `release_partition_stops_serving` CI flake, made
+// deterministic here.
+
+/// An event written after the snapshot but before the watch exists must
+/// still be delivered when the watch is anchored to the snapshot revision.
+#[tokio::test]
+async fn anchored_watch_delivers_events_written_before_attach() {
+ let store = test_store("anchored-watch").await;
+
+ // Participant startup with the race made certain: snapshot first…
+ let (handoffs, rev) = store
+ .list_handoffs_with_revision()
+ .await
+ .expect("snapshot with revision");
+ assert!(handoffs.is_empty());
+
+ // …then the event lands while no watch exists…
+ put_handoff(&store, 7, None, "anchored-pod", HandoffPhase::Freezing).await;
+
+ // …and only now does the watch attach. Anchored to the snapshot
+ // revision, it replays everything since — including this event, which
+ // predates the watch's existence. (An unanchored watch would start at
+ // "now" and never deliver it.)
+ let mut stream = store
+ .watch_handoffs_from(rev + 1)
+ .await
+ .expect("anchored watch");
+
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
+ loop {
+ let resp = tokio::time::timeout_at(deadline, stream.message())
+ .await
+ .expect("anchored watch must deliver the pre-attach event")
+ .expect("watch stream")
+ .expect("watch response");
+ // The first response may be the watch-created confirmation with no
+ // events; keep reading until the handoff arrives.
+ if let Some(handoff) = resp
+ .events()
+ .iter()
+ .find_map(|e| parse_watch_value::<HandoffState>(e).ok())
+ {
+ assert_eq!(handoff.partition, 7);
+ assert_eq!(handoff.new_owner, "anchored-pod");
+ return;
+ }
+ }
+}
+
+/// A pod's startup reconcile takes two snapshots (assignments, then
+/// handoffs) and anchors its handoff watch to the *lower* of the two
+/// revisions. This pins the contract that anchoring at the lower revision
+/// replays a write that lands between the two reads — anchoring at the
+/// higher one (an easy `min`→`max` typo in `reconcile_all`) would let the
+/// watch skip it.
+#[tokio::test]
+async fn watch_anchored_to_lower_snapshot_revision_replays_interleaved_write() {
+ let store = test_store("min-rev-anchor").await;
+
+ // First snapshot: assignments, at rev_a.
+ let (_, rev_a) = store
+ .list_assignments_with_revision()
+ .await
+ .expect("assignments snapshot");
+
+ // A handoff lands between the two snapshot reads.
+ put_handoff(&store, 3, None, "minrev-pod", HandoffPhase::Freezing).await;
+
+ // Second snapshot: handoffs, at rev_h > rev_a. The interleaved write
+ // is included here, so converging from this snapshot is fine — but a
+ // watch anchored past rev_a must still redeliver it, because a future
+ // reordering of the two reads would otherwise silently drop it.
+ let (handoffs, rev_h) = store
+ .list_handoffs_with_revision()
+ .await
+ .expect("handoffs snapshot");
+ assert!(handoffs.iter().any(|h| h.partition == 3));
+ assert!(
+ rev_h > rev_a,
+ "the interleaved write must bump the revision"
+ );
+
+ let mut stream = store
+ .watch_handoffs_from(rev_a.min(rev_h) + 1)
+ .await
+ .expect("anchored watch");
+
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
+ loop {
+ let resp = tokio::time::timeout_at(deadline, stream.message())
+ .await
+ .expect("watch anchored at min(rev_a, rev_h) must replay the interleaved write")
+ .expect("watch stream")
+ .expect("watch response");
+ if let Some(handoff) = resp
+ .events()
+ .iter()
+ .find_map(|e| parse_watch_value::<HandoffState>(e).ok())
+ {
+ assert_eq!(handoff.partition, 3);
+ assert_eq!(handoff.new_owner, "minrev-pod");
+ return;
+ }
+ }
+}
+
+// ============================================================
+// Fix 5: coordinator reconcile tick (liveness backstop)
+// ============================================================
+//
+// Phase advancement is driven exclusively by watch events on acks and
+// handoffs — but some state changes produce no such event. Nothing
+// watches router registrations: when the one router blocking a freeze
+// quorum departs (lease expiry), the quorum becomes satisfiable but no
+// event ever re-evaluates it, and the handoff sticks in Freezing forever.
+// A periodic reconcile tick re-runs the phase check for in-flight
+// handoffs, backstopping every no-event and missed-event case.
+
+/// A Freezing handoff whose quorum becomes satisfied by a router's
+/// departure (no ack/handoff event fires) must still advance.
+#[tokio::test]
+async fn freezing_handoff_advances_when_unacked_router_departs() {
+ let store = test_store("reconcile-tick").await;
+ let cancel = CancellationToken::new();
+
+ // Two registered routers. One acks; the other stays silent and will
+ // depart.
+ let lease_acked = store.grant_lease(30).await.expect("lease");
+ store
+ .register_router(
+ &RegisteredRouter {
+ router_name: "router-acked".to_string(),
+ registered_at: 0,
+ last_heartbeat: 0,
+ },
+ lease_acked,
+ )
+ .await
+ .expect("register acked router");
+
+ let lease_vanishing = store.grant_lease(30).await.expect("lease");
+ store
+ .register_router(
+ &RegisteredRouter {
+ router_name: "router-vanishing".to_string(),
+ registered_at: 0,
+ last_heartbeat: 0,
+ },
+ lease_vanishing,
+ )
+ .await
+ .expect("register vanishing router");
+
+ let _coord = start_coordinator(
+ Arc::clone(&store),
+ Arc::new(StickyBalancedStrategy),
+ cancel.clone(),
+ );
+
+ put_handoff(
+ &store,
+ 0,
+ Some("pod-old"),
+ "pod-new",
+ HandoffPhase::Freezing,
+ )
+ .await;
+ store
+ .put_freeze_ack(&RouterFreezeAck {
+ router_name: "router-acked".to_string(),
+ partition: 0,
+ acked_at: 0,
+ handoff_id: "test-handoff-0".to_string(),
+ })
+ .await
+ .expect("ack");
+
+ // Quorum unmet: the handoff holds in Freezing.
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ let handoff = store
+ .get_handoff(0)
+ .await
+ .expect("get handoff")
+ .expect("handoff exists");
+ assert_eq!(handoff.phase, HandoffPhase::Freezing);
+
+ // The silent router departs. Its registration vanishes with the
+ // lease — an event on the routers prefix, which nothing watches.
+ store
+ .revoke_lease(lease_vanishing)
+ .await
+ .expect("revoke lease");
+
+ // Only a time-driven reconcile can advance the handoff now.
+ let check_store = Arc::clone(&store);
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ 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();
+}
+
+// ============================================================
+// Fix 4: pod catches up on pre-existing handoffs at startup
+// ============================================================
+//
+// A pod that crash-restarts quickly (within its lease TTL) keeps its etcd
+// registration, so `cleanup_stale_handoffs` never fires and no new Put
+// arrives for a handoff created before the restart. Without a startup
+// scan the restarted pod never learns its part — the handoff stalls in
+// Draining/Warming forever.
+
+/// A Warming handoff naming this pod as new owner that predates the pod's
+/// start must be discovered and acted on: warm, then ack.
+#[tokio::test]
+async fn pod_catches_up_on_existing_warming_handoff_at_startup() {
+ let store = test_store("pod-startup-warm-catchup").await;
+ let cancel = CancellationToken::new();
+
+ // The handoff exists before the pod starts — as after a fast restart.
+ put_handoff(&store, 3, None, "catchup-pod", HandoffPhase::Warming).await;
+
+ let pod = start_pod(Arc::clone(&store), "catchup-pod", cancel.clone());
+
+ wait_for_event(&pod.events, HandoffEvent::Warmed(3)).await;
+
+ // The WarmedAck must reach etcd so the coordinator can complete.
+ let check_store = Arc::clone(&store);
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let store = Arc::clone(&check_store);
+ async move {
+ store
+ .list_warmed_acks(3)
+ .await
+ .map(|acks| acks.iter().any(|a| a.pod_name == "catchup-pod"))
+ .unwrap_or(false)
+ }
+ })
+ .await;
+
+ cancel.cancel();
+}
+
+/// The old-owner variant: a Draining handoff that predates the pod's
+/// start must be drained and acked. The restarted process has no inflight
+/// handlers, so what matters is the DrainedAck reaching etcd.
+#[tokio::test]
+async fn pod_catches_up_on_existing_draining_handoff_at_startup() {
+ let store = test_store("pod-startup-drain-catchup").await;
+ let cancel = CancellationToken::new();
+
+ put_handoff(
+ &store,
+ 4,
+ Some("drain-catchup-pod"),
+ "some-other-pod",
+ HandoffPhase::Draining,
+ )
+ .await;
+
+ let pod = start_pod(Arc::clone(&store), "drain-catchup-pod", cancel.clone());
+
+ wait_for_event(&pod.events, HandoffEvent::Drained(4)).await;
+
+ let check_store = Arc::clone(&store);
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let store = Arc::clone(&check_store);
+ async move {
+ store
+ .list_drained_acks(4)
+ .await
+ .map(|acks| acks.iter().any(|a| a.pod_name == "drain-catchup-pod"))
+ .unwrap_or(false)
+ }
+ })
+ .await;
+
+ cancel.cancel();
+}
+
+// ============================================================
+// Fix 3a: freeze quorum must be identity-based, not count-based
+// ============================================================
+//
+// Freeze acks are not lease-bound: an ack from a router that has since
+// deregistered survives until end-of-handoff cleanup. With a count-based
+// quorum (`acks.len() >= routers.len()`), a stale ack can stand in for a
+// live router that hasn't stashed yet — advancing to Draining while that
+// router still forwards writes to the old owner.
+
+/// A stale ack from a departed router must not satisfy the quorum on
+/// behalf of a registered router that hasn't acked. Once the registered
+/// router does ack, the handoff advances.
+#[tokio::test]
+async fn stale_freeze_ack_does_not_satisfy_quorum_for_live_router() {
+ let store = test_store("identity-quorum").await;
+ let cancel = CancellationToken::new();
+
+ // A stale ack left behind by a router that has since deregistered
+ // (acks are deliberately not lease-bound, so this survives).
+ store
+ .put_freeze_ack(&RouterFreezeAck {
+ router_name: "router-departed".to_string(),
+ partition: 0,
+ acked_at: 0,
+ handoff_id: "test-handoff-0".to_string(),
+ })
+ .await
+ .expect("write stale ack");
+
+ // A live, registered router that has NOT acked yet (registered
+ // directly so no watch loop acks on its behalf).
+ let lease_id = store.grant_lease(30).await.expect("lease");
+ store
+ .register_router(
+ &RegisteredRouter {
+ router_name: "router-silent".to_string(),
+ registered_at: 0,
+ last_heartbeat: 0,
+ },
+ lease_id,
+ )
+ .await
+ .expect("register router");
+
+ let _coord = start_coordinator(
+ Arc::clone(&store),
+ Arc::new(StickyBalancedStrategy),
+ cancel.clone(),
+ );
+
+ // A reassignment handoff enters Freezing. Ack count (1, stale) equals
+ // router count (1, silent) — identity says the quorum is NOT met.
+ put_handoff(
+ &store,
+ 0,
+ Some("pod-old"),
+ "pod-new",
+ HandoffPhase::Freezing,
+ )
+ .await;
+
+ // The handoff must hold in Freezing while the registered router
+ // hasn't acked.
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ let handoff = store
+ .get_handoff(0)
+ .await
+ .expect("get handoff")
+ .expect("handoff exists");
+ assert_eq!(
+ handoff.phase,
+ HandoffPhase::Freezing,
+ "a stale ack from a departed router must not stand in for a live router"
+ );
+
+ // The silent router acks → quorum genuinely met → advance.
+ store
+ .put_freeze_ack(&RouterFreezeAck {
+ router_name: "router-silent".to_string(),
+ partition: 0,
+ acked_at: 0,
+ handoff_id: "test-handoff-0".to_string(),
+ })
+ .await
+ .expect("write live ack");
+
+ let check_store = Arc::clone(&store);
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ 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();
+}
+
+// ============================================================
+// Fix 3b: router catches up on handoffs before serving its table
+// ============================================================
+
+/// Records whether the routing table already exposed the partition at the
+/// moment `begin_stash` fired.
+struct StashOrderProbe {
+ table: Arc<RwLock<HashMap<u32, String>>>,
+ observed: Arc<Mutex<Vec<(u32, bool)>>>,
+}
+
+#[async_trait]
+impl StashHandler for StashOrderProbe {
+ async fn begin_stash(&self, partition: u32, _new_owner: &str) -> Result<()> {
+ let table_populated = self.table.read().await.contains_key(&partition);
+ self.observed
+ .lock()
+ .await
+ .push((partition, table_populated));
+ Ok(())
+ }
+
+ async fn drain_stash(&self, _partition: u32, _target: &str) -> Result<()> {
+ Ok(())
+ }
+}
+
+/// A router joining mid-handoff must open its stash before its routing
+/// table can route the partition. In the reverse order there is a window
+/// where a write routes to the old owner with no stash open — after the
+/// old owner may already have drained.
+#[tokio::test]
+async fn late_joining_router_stashes_before_populating_table() {
+ let store = test_store("stash-before-table").await;
+ let cancel = CancellationToken::new();
+
+ // Pre-existing state: an assignment for partition 0 and an in-flight
+ // Freezing handoff moving it.
+ store
+ .create_assignments_and_handoffs(
+ &[PartitionAssignment {
+ partition: 0,
+ owner: "pod-old".to_string(),
+ status: AssignmentStatus::Active,
+ }],
+ &[],
+ )
+ .await
+ .expect("write assignment");
+ put_handoff(
+ &store,
+ 0,
+ Some("pod-old"),
+ "pod-new",
+ HandoffPhase::Freezing,
+ )
+ .await;
+
+ // A router joins now — its startup catch-up must stash before the
+ // table exposes partition 0.
+ let router = RoutingTable::new(
+ Arc::clone(&store),
+ RoutingTableConfig {
+ router_name: "late-router".to_string(),
+ lease_ttl: 10,
+ heartbeat_interval: Duration::from_secs(3),
+ },
+ );
+ let observed = Arc::new(Mutex::new(Vec::new()));
+ let probe = StashOrderProbe {
+ table: router.table_handle(),
+ observed: Arc::clone(&observed),
+ };
+ let token = cancel.child_token();
+ tokio::spawn(async move { router.run(token, Arc::new(probe)).await });
+
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let observed = Arc::clone(&observed);
+ async move { !observed.lock().await.is_empty() }
+ })
+ .await;
+
+ let calls = observed.lock().await.clone();
+ assert!(
+ calls.contains(&(0, false)),
+ "begin_stash must fire before the table exposes the partition; observed: {calls:?}"
+ );
+
+ cancel.cancel();
+}
diff --git a/rust/personhog-leader/README.md b/rust/personhog-leader/README.md
index 1d6e60167716..58b30e503dc0 100644
--- a/rust/personhog-leader/README.md
+++ b/rust/personhog-leader/README.md
@@ -113,15 +113,26 @@ broker can't park the runtime thread.
The pod participates in `personhog-coordination`'s handoff protocol
via `LeaderHandoffHandler` (see `src/coordination/mod.rs`):
-- `drain_partition_inflight` (Draining): waits for `InflightTracker`'s
- per-partition counter to drop to zero, then writes `PodDrainedAck`.
- Combined with the produce path's sync-await on Kafka delivery, this
- gives the protocol the guarantee that "no in-flight" implies
- "every acked write durable in Kafka."
-- `warm_partition` (Warming): see the section above.
-- `release_partition` (Complete): drops the partition's cache slot
- via `PartitionedCache::drop_partition` once the routing table has
- flipped to the new owner.
+- `drain_partition_inflight` (Draining): fences the partition against
+ new writes (`InflightTracker::fence` — fenced writes are refused with
+ `FAILED_PRECONDITION`), *then* waits for the per-partition counter to
+ drop to zero, then writes `PodDrainedAck`. Fencing before waiting is
+ what makes "counter reached zero" final: without the fence a write
+ admitted after the wait could advance the Kafka HWM past the point
+ warming snapshots. Combined with the produce path's sync-await on
+ Kafka delivery, this gives the protocol the guarantee that
+ "no in-flight" implies "every acked write durable in Kafka."
+ Reads are never fenced — until cutover the frozen cache state is
+ still the latest.
+- `warm_partition` (Warming): see the section above. Also lifts any
+ fence left over from a previous ownership of the same partition.
+- `release_partition` (Complete): lifts the write fence and drops the
+ partition's cache slot via `PartitionedCache::drop_partition` once
+ the routing table has flipped to the new owner.
+- `resume_partition` (handoff cancelled): a handoff deleted before
+ `Complete` while this pod still owns the partition is a
+ cancellation — lifts the write fence so the partition serves writes
+ again.
#### Request Path
diff --git a/rust/personhog-leader/src/coordination/mod.rs b/rust/personhog-leader/src/coordination/mod.rs
index fcd66da82624..3083d1b9b849 100644
--- a/rust/personhog-leader/src/coordination/mod.rs
+++ b/rust/personhog-leader/src/coordination/mod.rs
@@ -18,10 +18,11 @@ const DRAIN_POLL_INTERVAL: Duration = Duration::from_millis(50);
/// matching the four-phase handoff protocol
/// (`Freezing → Draining → Warming → Complete`):
/// - `drain_partition_inflight` (fired in `Draining` for the
-/// old owner): waits until no in-flight request handlers remain
-/// for the partition. By the time the coordinator advances to
-/// `Draining`, every router has acked freeze and stopped
-/// forwarding, so the inflight count strictly drops to zero.
+/// old owner): fences the partition against new writes, then waits
+/// until no in-flight request handlers remain. By the time the
+/// coordinator advances to `Draining`, every router has acked freeze
+/// and stopped forwarding, so any write arriving after this point is
+/// protocol-violating (a router with a stale view) and is rejected.
/// Because the produce path awaits the Kafka delivery future
/// before returning, "no in-flight" implies "every write this
/// pod ever acked is durable in Kafka." The pod then writes
@@ -30,8 +31,15 @@ const DRAIN_POLL_INTERVAL: Duration = Duration::from_millis(50);
/// consumes the `personhog_updates` topic for the partition and
/// repopulates the in-memory cache up to the now-stable HWM.
/// - `release_partition` (fired in `Complete` for the old owner):
-/// drops the partition's cache after the routing table has
-/// flipped to the new owner.
+/// drops the partition's cache (and its write fence) after the
+/// routing table has flipped to the new owner.
+/// - `resume_partition` (fired when a handoff is cancelled while this
+/// pod still owns the partition): lifts the write fence so the
+/// still-owning pod serves normally again.
+///
+/// Reads are never fenced: while writes are frozen the cached state
+/// cannot change, so the old owner's cache remains the latest state
+/// right up to cutover.
pub struct LeaderHandoffHandler {
cache: Arc<PartitionedCache>,
inflight: Arc<InflightTracker>,
@@ -59,27 +67,43 @@ impl LeaderHandoffHandler {
#[async_trait]
impl HandoffHandler for LeaderHandoffHandler {
async fn drain_partition_inflight(&self, partition: u32) -> Result<()> {
- info!(partition, "draining inflight handlers");
+ info!(partition, "fencing writes and draining inflight handlers");
+ // Fence before waiting: fencing only after the wait would leave a
+ // window between the inflight count reaching zero and the
+ // DrainedAck where a late write could advance the Kafka HWM past
+ // the point warming snapshots.
+ self.inflight.fence(partition);
self.inflight
.wait_until_empty(partition, DRAIN_POLL_INTERVAL)
.await;
- info!(partition, "inflight drained");
+ info!(partition, "inflight drained; writes fenced");
Ok(())
}
async fn warm_partition(&self, partition: u32) -> Result<()> {
info!(partition, "warming partition cache from kafka");
warm_from_kafka(&self.warming, &self.cache, partition).await?;
+ // This pod may still carry a fence from a previous ownership of
+ // the partition (a drain whose handoff never completed); taking
+ // ownership through a fresh warm re-admits writes.
+ self.inflight.unfence(partition);
info!(partition, "partition warmed");
Ok(())
}
async fn release_partition(&self, partition: u32) -> Result<()> {
info!(partition, "releasing partition");
+ self.inflight.unfence(partition);
self.cache.drop_partition(partition);
info!(partition, "partition released");
Ok(())
}
+
+ async fn resume_partition(&self, partition: u32) -> Result<()> {
+ info!(partition, "handoff cancelled; re-admitting writes");
+ self.inflight.unfence(partition);
+ Ok(())
+ }
}
#[cfg(test)]
diff --git a/rust/personhog-leader/src/inflight.rs b/rust/personhog-leader/src/inflight.rs
index b6d31c19d27c..2f80f9de4059 100644
--- a/rust/personhog-leader/src/inflight.rs
+++ b/rust/personhog-leader/src/inflight.rs
@@ -2,21 +2,31 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;
-use dashmap::DashMap;
+use dashmap::{DashMap, DashSet};
-/// Per-partition inflight request counter used by the handoff protocol to
+/// Per-partition write-admission state used by the handoff protocol to
/// prove that all writes this pod ever acked are durably in Kafka.
///
-/// Because `produce_person_changelog` awaits the Kafka delivery future before
-/// the handler returns success, "no inflight handlers for partition p" implies
-/// "every write for p that this pod ever acknowledged is in Kafka."
+/// Two pieces work together:
///
-/// Callers obtain a guard via `begin(partition)` and drop it when the handler
-/// completes; the handoff protocol calls `wait_until_empty(partition)` to
-/// block until all inflight handlers have returned.
+/// * An inflight counter. Because `produce_person_changelog` awaits the
+/// Kafka delivery future before the handler returns success, "no
+/// inflight handlers for partition p" implies "every write for p that
+/// this pod ever acknowledged is in Kafka."
+/// * A write fence. Once a partition drains for handoff, no further write
+/// may be admitted: every router acked the freeze before the drain
+/// began, so a late write can only come from a router serving with a
+/// stale view — accepting it would advance the Kafka HWM past the point
+/// warming snapshots, silently losing the write from the new owner.
+///
+/// Callers obtain a guard via `begin(partition)` and drop it when the
+/// handler completes; the handoff protocol fences the partition, then
+/// calls `wait_until_empty(partition)` to block until all inflight
+/// handlers have returned.
#[derive(Default)]
pub struct InflightTracker {
partitions: DashMap<u32, Arc<AtomicUsize>>,
+ fenced: DashSet<u32>,
}
impl InflightTracker {
@@ -34,6 +44,26 @@ impl InflightTracker {
InflightGuard { counter }
}
+ /// Admit a write for the partition unless it is fenced. The increment
+ /// happens *before* the fence check: at every interleaving with the
+ /// drain path (which fences, then waits for the count to reach zero),
+ /// either this write's increment is visible to the drain's wait, or
+ /// this write observes the fence and is refused. Checking the fence
+ /// before incrementing would leave a window where a write passes the
+ /// check, the drain fences and observes a zero count, and the write
+ /// then increments — producing past the HWM the new owner's warming
+ /// snapshots.
+ pub fn try_begin(self: &Arc<Self>, partition: u32) -> Option<InflightGuard> {
+ let guard = self.begin(partition);
+ if self.is_fenced(partition) {
+ // Dropping the guard decrements the transient count the
+ // drain's wait may have observed.
+ drop(guard);
+ return None;
+ }
+ Some(guard)
+ }
+
/// Block until no inflight handlers remain for the partition. Polls at
/// `poll_interval`; intended for handoff-time drain, not hot paths.
pub async fn wait_until_empty(&self, partition: u32, poll_interval: Duration) {
@@ -50,6 +80,25 @@ impl InflightTracker {
}
}
+ /// Reject new writes for the partition. Must be set before the drain
+ /// starts waiting on the inflight count, so no write can slip in
+ /// between the count reaching zero and the drained ack being written.
+ pub fn fence(&self, partition: u32) {
+ self.fenced.insert(partition);
+ }
+
+ /// Re-admit writes for the partition: the handoff completed (the
+ /// partition was released), was cancelled, or this pod re-acquired
+ /// the partition through a fresh warm. Idempotent.
+ pub fn unfence(&self, partition: u32) {
+ self.fenced.remove(&partition);
+ }
+
+ /// Whether writes for the partition are currently rejected.
+ pub fn is_fenced(&self, partition: u32) -> bool {
+ self.fenced.contains(&partition)
+ }
+
#[cfg(test)]
pub fn count(&self, partition: u32) -> usize {
self.partitions
@@ -126,4 +175,56 @@ mod tests {
tracker.wait_until_empty(2, Duration::from_millis(10)).await;
assert_eq!(tracker.count(1), 1);
}
+
+ /// A write admitted before the fence is visible to the drain's wait;
+ /// a write arriving after the fence is refused and leaves no residual
+ /// count. Together these are the two halves of the drain invariant.
+ #[tokio::test]
+ async fn try_begin_admits_before_fence_and_refuses_after() {
+ let tracker = Arc::new(InflightTracker::new());
+
+ let admitted = tracker.try_begin(9).expect("unfenced partition admits");
+ assert_eq!(tracker.count(9), 1, "admitted write counts as inflight");
+
+ tracker.fence(9);
+ assert!(
+ tracker.try_begin(9).is_none(),
+ "fenced partition refuses new writes"
+ );
+ assert_eq!(
+ tracker.count(9),
+ 1,
+ "refused write must not leave a residual count"
+ );
+
+ // The drain's wait blocks on the pre-fence write until it completes.
+ let t = Arc::clone(&tracker);
+ let wait = tokio::spawn(async move {
+ t.wait_until_empty(9, Duration::from_millis(10)).await;
+ });
+ tokio::time::sleep(Duration::from_millis(30)).await;
+ assert!(!wait.is_finished(), "drain waits for the admitted write");
+ drop(admitted);
+ wait.await.unwrap();
+ }
+
+ /// Fences are per-partition, idempotent, and reversible — the exact
+ /// lifecycle the handoff handler drives (fence on drain, unfence on
+ /// release/cancel/re-warm).
+ #[test]
+ fn fence_lifecycle() {
+ let tracker = InflightTracker::new();
+ assert!(!tracker.is_fenced(5));
+
+ tracker.fence(5);
+ assert!(tracker.is_fenced(5));
+ assert!(!tracker.is_fenced(6), "fences are per-partition");
+
+ tracker.fence(5); // idempotent
+ tracker.unfence(5);
+ assert!(!tracker.is_fenced(5));
+
+ tracker.unfence(5); // idempotent on already-clear
+ assert!(!tracker.is_fenced(5));
+ }
}
diff --git a/rust/personhog-leader/src/service.rs b/rust/personhog-leader/src/service.rs
index a51b35675e9e..823fab19885a 100644
--- a/rust/personhog-leader/src/service.rs
+++ b/rust/personhog-leader/src/service.rs
@@ -234,13 +234,25 @@ impl PersonHogLeader for PersonHogLeaderService {
let req = request.into_inner();
self.validate_partition(partition, req.team_id, req.person_id)?;
- // Track this write as inflight for its partition. The handoff protocol
- // waits for the per-partition inflight count to drop to zero before
- // advancing Freezing -> Warming. Combined with sync-acked produces, a
- // zero count implies every acked write is durable in Kafka. Using a
+ // Admit the write as inflight, unless the partition is fenced. A
+ // fenced partition has drained for handoff: every router acked the
+ // freeze, so this write can only come from a router with a stale
+ // view — accepting it would produce past the Kafka HWM that the new
+ // owner's warming snapshots, silently losing the write. Admission
+ // and the fence check are one atomic operation (`try_begin`): the
+ // inflight increment precedes the check, so the drain either waits
+ // for this write or this write sees the fence. Reads are unaffected
+ // — the frozen state stays the latest until cutover. The handoff
+ // protocol waits for the per-partition inflight count to drop to
+ // zero before advancing; combined with sync-acked produces, a zero
+ // count implies every acked write is durable in Kafka. Using a
// non-`_` prefixed binding so the RAII guard is held for the full
// handler lifetime (see the `let_underscore_drop` lint).
- let _inflight_guard = self.inflight.begin(partition);
+ let Some(_inflight_guard) = self.inflight.try_begin(partition) else {
+ return Err(Status::failed_precondition(format!(
+ "partition {partition} is fenced for handoff; writes are rejected"
+ )));
+ };
let cache_key = PersonCacheKey {
team_id: req.team_id,
diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rs
index 33c7c0ad5d44..1e7b4cd96b00 100644
--- a/rust/personhog-leader/tests/common/mod.rs
+++ b/rust/personhog-leader/tests/common/mod.rs
@@ -94,6 +94,7 @@ pub fn start_coordinator(
keepalive_interval: Duration::from_secs(3),
election_retry_interval: Duration::from_secs(1),
rebalance_debounce_interval: Duration::from_millis(100),
+ reconcile_interval: Duration::from_millis(500),
},
strategy,
None,
diff --git a/rust/personhog-leader/tests/integration.rs b/rust/personhog-leader/tests/integration.rs
index 140d6d749634..791421ab998f 100644
--- a/rust/personhog-leader/tests/integration.rs
+++ b/rust/personhog-leader/tests/integration.rs
@@ -9,12 +9,15 @@ use common::{
create_leader_client, create_local_kafka_producer, create_test_kafka,
create_test_kafka_with_partitions, person_id_for_partition, seed_person, start_coordinator,
start_leader_pod, start_leader_pod_with_lease_ttl, start_leader_with_pg_fallback, start_router,
- test_cached_person, test_store, wait_for_condition, CHANGELOG_TOPIC, KAFKA_BOOTSTRAP,
- NUM_PARTITIONS, POLL_INTERVAL, WAIT_TIMEOUT,
+ test_cached_person, test_store, test_warming_config, wait_for_condition, CHANGELOG_TOPIC,
+ KAFKA_BOOTSTRAP, NUM_PARTITIONS, POLL_INTERVAL, WAIT_TIMEOUT,
};
use personhog_common::partitioning::partition_for_person;
+use personhog_coordination::pod::HandoffHandler;
use personhog_coordination::strategy::StickyBalancedStrategy;
use personhog_leader::cache::{CacheLookup, PartitionedCache};
+use personhog_leader::coordination::LeaderHandoffHandler;
+use personhog_leader::inflight::InflightTracker;
use personhog_leader::service::PersonHogLeaderService;
use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeaderServer;
use personhog_proto::personhog::types::v1::{
@@ -377,6 +380,210 @@ async fn mismatched_partition_metadata_returns_invalid_argument() {
cancel.cancel();
}
+// ============================================================
+// Test 2b: Post-drain write fencing
+// (no etcd needed)
+// ============================================================
+
+/// Once the old owner has drained a partition, every router has acked the
+/// freeze — so a later write can only come from a router serving with a
+/// stale table (an expired lease it hasn't noticed, a missed freeze).
+/// Accepting it would produce to Kafka past the HWM that warming
+/// snapshots, silently losing the write from the new owner's cache. After
+/// draining, the old owner must reject writes for the partition while
+/// continuing to serve reads: the frozen state remains the latest until
+/// cutover. Releasing the partition clears the fence with it.
+#[tokio::test]
+async fn writes_fenced_after_drain_reads_still_served() {
+ let cache = Arc::new(PartitionedCache::new(100));
+ let (_mock_cluster, kafka_producer) = create_test_kafka().await;
+ let inflight = Arc::new(InflightTracker::new());
+ let service = PersonHogLeaderService::new(
+ Arc::clone(&cache),
+ kafka_producer,
+ CHANGELOG_TOPIC.to_string(),
+ None,
+ Arc::new(DashMap::new()),
+ Arc::clone(&inflight),
+ NUM_PARTITIONS,
+ );
+ // The handler shares the cache and inflight tracker with the service,
+ // exactly as main.rs wires them.
+ let handler = LeaderHandoffHandler::new(
+ Arc::clone(&cache),
+ Arc::clone(&inflight),
+ test_warming_config("fence-pod", KAFKA_BOOTSTRAP),
+ );
+
+ cache.create_partition(0);
+ seed_person(&cache, 0, test_cached_person());
+
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let cancel = CancellationToken::new();
+ let token = cancel.child_token();
+
+ tokio::spawn(async move {
+ Server::builder()
+ .add_service(PersonHogLeaderServer::new(service))
+ .serve_with_incoming_shutdown(
+ tokio_stream::wrappers::TcpListenerStream::new(listener),
+ token.cancelled(),
+ )
+ .await
+ .unwrap();
+ });
+ tokio::time::sleep(Duration::from_millis(10)).await;
+
+ let mut client = create_leader_client(addr).await;
+
+ let update = |email: &str| {
+ with_partition(
+ UpdatePersonPropertiesRequest {
+ team_id: 1,
+ person_id: 42,
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(&serde_json::json!({ "email": email })).unwrap(),
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ },
+ 0,
+ )
+ };
+
+ // Pre-drain: writes flow normally.
+ let response = client
+ .update_person_properties(update("[email protected]"))
+ .await
+ .unwrap();
+ assert!(response.into_inner().updated);
+
+ // Drain the partition, as the pod does on observing Draining.
+ handler.drain_partition_inflight(0).await.unwrap();
+
+ // Post-drain: writes must be fenced…
+ let status = client
+ .update_person_properties(update("[email protected]"))
+ .await
+ .expect_err("write after drain must be rejected");
+ assert_eq!(status.code(), tonic::Code::FailedPrecondition);
+
+ // …while reads keep serving the frozen, still-latest state.
+ let response = client
+ .get_person(leader_get_request(1, 42, 0))
+ .await
+ .expect("reads must keep serving after drain");
+ let props: serde_json::Value =
+ serde_json::from_slice(&response.into_inner().person.unwrap().properties).unwrap();
+ assert_eq!(props["email"], "[email protected]");
+
+ // Releasing clears the fence along with the partition: when the same
+ // pod later re-acquires the partition (fresh warm), writes flow again.
+ handler.release_partition(0).await.unwrap();
+ cache.create_partition(0);
+ seed_person(&cache, 0, test_cached_person());
+ let response = client
+ .update_person_properties(update("[email protected]"))
+ .await
+ .expect("writes must flow again after release + re-warm");
+ assert!(response.into_inner().updated);
+
+ cancel.cancel();
+}
+
+/// The fence must go up before the drain starts waiting on inflight
+/// handlers — fencing only after `wait_until_empty` returns would leave a
+/// window where a write lands between the inflight count hitting zero and
+/// the DrainedAck being written, advancing the Kafka HWM past what
+/// warming will read. With an inflight write held open, new writes must
+/// already be rejected while the drain is still waiting.
+#[tokio::test]
+async fn drain_fences_before_waiting_on_inflight() {
+ let cache = Arc::new(PartitionedCache::new(100));
+ let (_mock_cluster, kafka_producer) = create_test_kafka().await;
+ let inflight = Arc::new(InflightTracker::new());
+ let service = PersonHogLeaderService::new(
+ Arc::clone(&cache),
+ kafka_producer,
+ CHANGELOG_TOPIC.to_string(),
+ None,
+ Arc::new(DashMap::new()),
+ Arc::clone(&inflight),
+ NUM_PARTITIONS,
+ );
+ let handler = Arc::new(LeaderHandoffHandler::new(
+ Arc::clone(&cache),
+ Arc::clone(&inflight),
+ test_warming_config("fence-race-pod", KAFKA_BOOTSTRAP),
+ ));
+
+ cache.create_partition(0);
+ seed_person(&cache, 0, test_cached_person());
+
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let cancel = CancellationToken::new();
+ let token = cancel.child_token();
+
+ tokio::spawn(async move {
+ Server::builder()
+ .add_service(PersonHogLeaderServer::new(service))
+ .serve_with_incoming_shutdown(
+ tokio_stream::wrappers::TcpListenerStream::new(listener),
+ token.cancelled(),
+ )
+ .await
+ .unwrap();
+ });
+ tokio::time::sleep(Duration::from_millis(10)).await;
+
+ let mut client = create_leader_client(addr).await;
+
+ // Hold a simulated in-flight write so the drain parks in
+ // wait_until_empty rather than completing immediately.
+ let guard = inflight.begin(0);
+
+ let drain_handler = Arc::clone(&handler);
+ let drain = tokio::spawn(async move { drain_handler.drain_partition_inflight(0).await });
+
+ // Give the drain a moment to start waiting.
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ assert!(
+ !drain.is_finished(),
+ "drain must wait for the held inflight"
+ );
+
+ // A write arriving mid-drain must already be fenced.
+ let status = client
+ .update_person_properties(with_partition(
+ UpdatePersonPropertiesRequest {
+ team_id: 1,
+ person_id: 42,
+ event_name: "$set".to_string(),
+ set_properties: serde_json::to_vec(
+ &serde_json::json!({"email": "[email protected]"}),
+ )
+ .unwrap(),
+ set_once_properties: vec![],
+ unset_properties: vec![],
+ },
+ 0,
+ ))
+ .await
+ .expect_err("write during drain must be rejected");
+ assert_eq!(status.code(), tonic::Code::FailedPrecondition);
+
+ // Releasing the held write lets the drain complete.
+ drop(guard);
+ tokio::time::timeout(Duration::from_secs(5), drain)
+ .await
+ .expect("drain must complete once inflight reaches zero")
+ .expect("drain task must not panic")
+ .expect("drain must succeed");
+
+ cancel.cancel();
+}
+
// ============================================================
// Test 3: Release partition stops serving
// ============================================================
diff --git a/rust/personhog-router/README.md b/rust/personhog-router/README.md
index a5796134f6d1..cc5373ac5f14 100644
--- a/rust/personhog-router/README.md
+++ b/rust/personhog-router/README.md
@@ -77,6 +77,14 @@ Two policies layer on the raw mechanism:
the leader; across keys the drain fans out to shrink wall-clock
drain duration.
+3. **Fenced-leader remap**: a `FAILED_PRECONDITION` from the leader
+ during drain means the drain raced the target's write fence — the
+ old owner resuming after a cancelled handoff, or the new owner's
+ cutover — a transient coordination state, not a caller error.
+ Because `FAILED_PRECONDITION` reads as "do not retry" to clients,
+ drain remaps it to `UNAVAILABLE` so callers retry, consistent with
+ the deadline and bounds contracts above.
+
Bounds are configurable per partition (`STASH_MAX_MESSAGES_PER_PARTITION`,
`STASH_MAX_BYTES_PER_PARTITION`); requests that would exceed either bound
are rejected with `UNAVAILABLE` so callers retry rather than the router
diff --git a/rust/personhog-router/src/config.rs b/rust/personhog-router/src/config.rs
index c3e3411b4a24..7fdae6900257 100644
--- a/rust/personhog-router/src/config.rs
+++ b/rust/personhog-router/src/config.rs
@@ -225,6 +225,13 @@ pub struct Config {
#[envconfig(default = "1000")]
pub coordinator_rebalance_debounce_ms: u64,
+ /// How often the coordinator re-evaluates in-flight handoffs
+ /// regardless of watch events — the liveness backstop for state
+ /// changes that fire no event (e.g. router departures) and for
+ /// events missed before a watch attaches.
+ #[envconfig(default = "5")]
+ pub coordinator_reconcile_secs: u64,
+
// ── K8s awareness (leader mode only) ────────────────────────
/// Enable K8s-aware departure classification for smarter rebalancing.
/// When disabled, falls back to lease-based behavior.
@@ -416,6 +423,10 @@ impl Config {
Duration::from_millis(self.coordinator_rebalance_debounce_ms)
}
+ pub fn coordinator_reconcile_interval(&self) -> Duration {
+ Duration::from_secs(self.coordinator_reconcile_secs)
+ }
+
pub fn stash_max_wait(&self) -> Duration {
Duration::from_millis(self.stash_max_wait_ms)
}
diff --git a/rust/personhog-router/src/grpc_http.rs b/rust/personhog-router/src/grpc_http.rs
index 7d576328c752..55eb393407ca 100644
--- a/rust/personhog-router/src/grpc_http.rs
+++ b/rust/personhog-router/src/grpc_http.rs
@@ -40,6 +40,18 @@ pub(crate) fn is_grpc_error_response(response: &http::Response<BoxBody>) -> bool
.is_some_and(|s| s != "0")
}
+/// The `grpc-status` code carried in a response's HTTP headers, if any.
+/// Only trailers-only (error) responses expose their status here; a
+/// successful response carries its status in the trailers and yields
+/// `None`.
+pub(crate) fn grpc_status_code(response: &http::Response<BoxBody>) -> Option<i32> {
+ response
+ .headers()
+ .get("grpc-status")
+ .and_then(|v| v.to_str().ok())
+ .and_then(|s| s.parse::<i32>().ok())
+}
+
/// Percent-encode a gRPC status message so it is safe to carry in the
/// ASCII-only `grpc-message` header.
fn percent_encode_grpc(s: &str) -> String {
diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rs
index 55ec18f017fa..2a0b284502e5 100644
--- a/rust/personhog-router/src/main.rs
+++ b/rust/personhog-router/src/main.rs
@@ -321,6 +321,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
keepalive_interval: config.coordinator_keepalive_interval(),
election_retry_interval: config.coordinator_election_retry_interval(),
rebalance_debounce_interval: config.coordinator_rebalance_debounce_interval(),
+ reconcile_interval: config.coordinator_reconcile_interval(),
},
Arc::new(StickyBalancedStrategy),
k8s_awareness,
diff --git a/rust/personhog-router/src/stash_handler.rs b/rust/personhog-router/src/stash_handler.rs
index ec9cb0ecff0a..215b08dd0119 100644
--- a/rust/personhog-router/src/stash_handler.rs
+++ b/rust/personhog-router/src/stash_handler.rs
@@ -9,7 +9,7 @@ use personhog_coordination::routing_table::StashHandler;
use tonic::Code;
use crate::backend::{LeaderBackend, StashedRequest};
-use crate::grpc_http::{grpc_error_response, is_grpc_error_response};
+use crate::grpc_http::{grpc_error_response, grpc_status_code, is_grpc_error_response};
/// gRPC method name for stashed writes — the stash buffers only the write
/// path, so every replayed frame targets `UpdatePersonProperties`.
@@ -85,10 +85,11 @@ impl RouterStashHandler {
/// the request has been waiting longer than `max_stash_wait`, send back
/// `UNAVAILABLE` without forwarding so the client retries with a fresh
/// request. Otherwise forward via the unified routing path and pipe the
-/// result through the oneshot. Tracks metrics for the four observable
-/// outcomes (expired, success, error, dropped) so operators can see
-/// stash-driven latency, leader failures during drain, and cases where
-/// the original caller disconnected before the reply.
+/// result through the oneshot. Tracks metrics for the five observable
+/// outcomes (expired, success, fenced, error, dropped) so operators can
+/// see stash-driven latency, drains racing a leader's fence or cutover,
+/// leader failures during drain, and cases where the original caller
+/// disconnected before the reply.
async fn forward_one(
leader_backend: &LeaderBackend,
max_stash_wait: Duration,
@@ -133,6 +134,25 @@ async fn forward_one(
)
.await
{
+ // A FailedPrecondition during drain means the target's fence or
+ // ownership is still settling: a cancellation's drain-back races
+ // the old owner's resume, and a completion's drain races the new
+ // owner's cutover. The condition clears in watch-propagation
+ // time, but FailedPrecondition reads as "do not retry" to
+ // clients — remap it to the same definitive retry contract as
+ // the deadline path above. Never silent: the write was never
+ // acked.
+ Ok((response, _call_ms))
+ if grpc_status_code(&response) == Some(Code::FailedPrecondition as i32) =>
+ {
+ (
+ grpc_error_response(
+ Code::Unavailable,
+ "leader transitioning during stash drain; retry",
+ ),
+ "fenced",
+ )
+ }
Ok((response, _call_ms)) => {
let outcome = if is_grpc_error_response(&response) {
"error"
diff --git a/rust/personhog-router/tests/common/mod.rs b/rust/personhog-router/tests/common/mod.rs
index 15a293eb52c8..48dddb92d3c3 100644
--- a/rust/personhog-router/tests/common/mod.rs
+++ b/rust/personhog-router/tests/common/mod.rs
@@ -646,12 +646,16 @@ pub fn create_test_person() -> Person {
/// stamps the header, not just that the body arrives intact.
pub struct TestLeaderService {
persons: DashMap<(i64, i64), Person>,
+ /// When true, writes are rejected with FailedPrecondition, mimicking
+ /// a leader whose partition is write-fenced for a handoff.
+ fenced: bool,
}
impl TestLeaderService {
pub fn new() -> Self {
Self {
persons: DashMap::new(),
+ fenced: false,
}
}
@@ -659,6 +663,11 @@ impl TestLeaderService {
self.persons.insert((person.team_id, person.id), person);
self
}
+
+ pub fn fenced(mut self) -> Self {
+ self.fenced = true;
+ self
+ }
}
/// Extract the routing partition from `x-partition` metadata, matching the
@@ -703,6 +712,11 @@ impl PersonHogLeader for TestLeaderService {
) -> Result<Response<UpdatePersonPropertiesResponse>, Status> {
require_partition_metadata(&request)?;
let req = request.into_inner();
+ if self.fenced {
+ return Err(Status::failed_precondition(
+ "partition is fenced for handoff; writes are rejected",
+ ));
+ }
let key = (req.team_id, req.person_id);
let mut person = self
diff --git a/rust/personhog-router/tests/stash_integration.rs b/rust/personhog-router/tests/stash_integration.rs
index 7459978ec605..89cfdecc3852 100644
--- a/rust/personhog-router/tests/stash_integration.rs
+++ b/rust/personhog-router/tests/stash_integration.rs
@@ -476,6 +476,50 @@ async fn stash_wait_exceeded_returns_unavailable() {
);
}
+/// A drain that races the target leader's fence (a cancellation's
+/// drain-back arriving before the old owner's resume, or a completion's
+/// drain hitting a pod mid-cutover) gets FailedPrecondition from the
+/// leader — but the condition clears in watch-propagation time, so the
+/// client must see the same definitive-retry UNAVAILABLE contract as the
+/// deadline path, not a "do not retry" error for a write that was never
+/// acked.
+#[tokio::test]
+async fn fenced_leader_during_drain_returns_unavailable() {
+ let person = create_test_person();
+ let leader_addr = start_test_leader(
+ TestLeaderService::new()
+ .with_person(person.clone())
+ .fenced(),
+ )
+ .await;
+
+ let stash = StashTable::with_bounds(usize::MAX, usize::MAX);
+ let backend = make_backend(leader_addr, stash.clone()).await;
+ // Generous deadline so only the fence-remap path can produce the
+ // UNAVAILABLE, never the deadline path.
+ let handler = RouterStashHandler::new(Arc::clone(&backend), Duration::from_secs(60), 4);
+
+ let partition = backend.partition_for_person(person.team_id, person.id);
+ handler.begin_stash(partition, "leader-new").await.unwrap();
+
+ let req = mk_request(person.team_id, person.id, "[email protected]");
+ let backend_for_call = Arc::clone(&backend);
+ let pending = tokio::spawn(async move { forward(&backend_for_call, req).await });
+ tokio::time::sleep(Duration::from_millis(50)).await;
+
+ handler.drain_stash(partition, "leader-new").await.unwrap();
+
+ let response = pending.await.unwrap();
+ let code = decode_response(response)
+ .await
+ .expect_err("fenced leader must reject the drained write");
+ assert_eq!(
+ code,
+ Code::Unavailable,
+ "fence rejections during drain must surface as retryable UNAVAILABLE"
+ );
+}
+
/// Convergence invariant: the loop-drain must terminate even when new
/// requests keep arriving during drain (so long as forward-rate keeps
/// up with arrival-rate). This test produces a steady stream of