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): protocol deploy resilience (#74085)

Zach Browna376d29a8493
diff --git a/rust/personhog-coordination/README.md b/rust/personhog-coordination/README.md
index 30a289ad1f66..4f25ef2de07a 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 written an ack matching the current handoff's `handoff_id`, the coordinator advances to `Draining` via a compare-and-swap on the handoff key's `mod_revision`.
+1. **Freezing**: Coordinator creates the handoff, snapshotting the then-registered routers into the record's `freeze_quorum`. Routers begin buffering ("stashing") incoming writes for the partition and write a `RouterFreezeAck`. The old owner does *not* yet drain — it continues serving until the quorum has acked, because while a single router still forwards traffic to the old owner the inflight count cannot meaningfully be observed as zero. The required ackers are the creation-time snapshot intersected with the live registry, so the requirement only ever shrinks: a router that dies drops out, and one that registers later is never added (it anchors its watch after the handoff, may never see the `Freezing` event, and its table starts fail-closed, so its ack is neither obtainable nor needed). Once every required router has written an ack matching the current handoff's `handoff_id`, the coordinator advances to `Draining` via a compare-and-swap on the handoff key's `mod_revision`.
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`.
@@ -66,7 +66,11 @@ 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 — 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.
+- **Cancellation by replacement**: A handoff record is never deleted while non-terminal. To cancel one — its new owner's registration disappeared, or it outstayed its phase's deadline — the planner atomically *replaces* the record, under its `mod_revision` and with the predecessor's acks deleted in the same transaction, with whatever resolves the routers' stashes: a successor `Freezing` handoff when the plan re-places the partition (stashes ride into it without observing a gap), or a reaffirm — `Complete` toward the live current owner, `old_owner: None` — when the placement stands (stashes drain home through the ordinary Complete path, and the owner pod converges back to serving). Only when neither exists (owner dead, nothing placeable) is the record deleted, which is safe fail-closed. A deletion event therefore has exactly one protocol meaning — cleanup after `Complete` — and routers treat it as inert. The cancellation log and a `freeze_ack_missing_total{router}` counter name the required routers whose acks never arrived, so a freeze wedge attributes itself to the non-participating router.
+- **Phase-aware deadline**: Time-in-phase is bounded, not total age — wedged is a property of a phase. Freezing and Draining wait only on acknowledgements and share a tight budget (`COORDINATOR_HANDOFF_DEADLINE_SECS`, default 120 s); Warming replays a changelog whose length scales with the partition and gets its own generous budget (`COORDINATOR_WARMING_DEADLINE_SECS`, default 1800 s, 0 disables). A total-age deadline would cancel a legitimately long warm and restart it from zero, forever. The reconcile tick detects both cancellation triggers and wakes the planning loop; the replacement itself is a planning decision.
+- **Participant stall watchdog**: A router's registration is lease-backed, and the lease keepalive is its own task — so a router whose handoff watch loop has stalled would stay registered (counted in freeze quorums) while never acking. The watch loop stamps a progress marker from a ticker arm inside its own select; a watchdog task fails the run when the stamp goes stale (`ROUTER_PARTICIPANT_STALL_SECS`, default 60 s), deregistering the router on the way down so quorums stop counting it and the process supervisor restarts a healthy participant. Pods deliberately get no such watchdog: their converge loop legitimately blocks for warm-duration, and a pod that stops acking is routed *around* by the phase deadline and replacement instead of being restarted mid-warm.
+- **Level-triggered reconciliation everywhere**: Watches are the latency path; every participant also has a truth path that re-derives its state from a fresh snapshot. The coordinator's tick re-evaluates handoffs; the router's reconcile pass (an arm of its watch loop, `ROUTER_RECONCILE_SECS`, default 5 s) re-asserts stashes and freeze acks, converges its table to the assignment authority, and drains any stash whose partition has no handoff to the assignment owner — which heals a missed Complete, a silently dead watch stream, or an out-of-protocol raw deletion; the pod's tick re-converges every involved partition, including locally-held state the durable world no longer mentions. Every reconcile action is idempotent against the event path. Reconcile failures are tolerated, not fatal: a failed pass leaves the participant exactly as stale as the previous tick (the watch-driven steady state), so brief etcd blips never restart the fleet — sustained outage self-fences through the lease keepalive instead. A consecutive-failure budget (`ROUTER_RECONCILE_FAILURE_BUDGET`, default 12 ticks; same default on pods) bounds the partial mode where snapshot reads fail while the lease stays healthy, and `personhog_coordination_reconcile_failures_total{component}` counts every failure.
+- **Warm provenance**: A pod records what each partition warm was installed for (serving, or a specific handoff id). Warming honors only a warm installed for the *current* handoff — one left over from an earlier ownership era is released and rebuilt, because its cache can hold values that predate writes the changelog accepted since, and a fresh warm replays only from the writer's committed offset. Without this, a returning owner whose `Released` convergence never ran could ack a warm it never performed and lose acknowledged writes — a counterexample the stateright model found and now pins.
- **Coordinator restart**: On startup, the coordinator runs `reconcile_pending_handoffs`. For every existing handoff it applies cleanup if `Complete`, otherwise calls `check_phase_advance` to nudge the state machine. This handles the case where acks were written before the coordinator was up — the ack-watch only fires on Put events, so without reconcile those acks would be invisible.
- **Reconcile tick**: Beyond the startup reconcile, the coordinator re-evaluates every in-flight handoff on a fixed interval (`reconcile_interval`, default 5 s). This is the liveness backstop for state changes that fire no watched event — e.g. a router departing (nothing watches router registrations) newly satisfying a freeze quorum. Everything the tick drives is idempotent: phase transitions use CAS and cleanup tolerates already-deleted records.
- **Lease loss (self-fencing)**: A pod or router whose lease keepalive fails — including etcd answering a keepalive with TTL ≤ 0 for a revoked or expired lease — treats the lease as lost and exits its run loop immediately, skipping the graceful drain: the coordinator already considers it dead and is reassigning its partitions via the dead-owner path, so a graceful drain would only race that. This prevents a zombie owner from continuing to serve partitions the protocol has reassigned.
@@ -80,9 +84,11 @@ Several failure modes are handled explicitly:
## Known limitations
+**The double-zombie residual is open — the one known acked-write-loss path.** A lease-expired router (excluded from the freeze quorum, still routing on a stale table) feeding a lease-expired pod (coordination loop dead, never fenced) can ack a write after the partition's new owner warmed; the write lands beyond the warm HWM, invisible to the new owner forever. Both zombie windows are bounded by lease self-fencing to roughly one heartbeat tick, so the loss needs both to coincide — but nothing rejects the zombie's produce at the broker. The stateright model reproduces the exact interleaving (`current_protocol_double_zombie_loses_acked_writes`) and machine-validates the fix: per-partition Kafka transactional producers, where warming bumps the broker's producer epoch and stale-epoch produces are rejected (`Variant::EpochFenced`). The fix is designed and verified but not yet implemented in the leader.
+
**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.
-**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.
+**Mid-stream watch reconnects don't replay missed events — bounded by reconciliation**: 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. Every participant now bounds the resulting staleness with its level-triggered truth path — the coordinator's tick (which also wakes the planner unconditionally), the router's reconcile pass, and the pod's converge-all tick — so a missed event costs at most one reconcile interval, not correctness.
## Modules
@@ -92,7 +98,7 @@ Several failure modes are handled explicitly:
| `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, 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. |
+| `routing_table` | `RoutingTable` + `StashHandler` trait: routing map maintenance and the begin-stash / drain-stash phase responses. Drains run off the watch loop in per-partition lanes (a newer drain supersedes and never overlaps the one in flight); the loop's progress feeds the stall watchdog. |
| `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. |
diff --git a/rust/personhog-coordination/src/coordinator.rs b/rust/personhog-coordination/src/coordinator.rs
index 89ef3849d0c8..612a1581bf92 100644
--- a/rust/personhog-coordination/src/coordinator.rs
+++ b/rust/personhog-coordination/src/coordinator.rs
@@ -12,10 +12,16 @@ use k8s_awareness::types::ControllerKind;
use k8s_awareness::{DepartureReason, K8sAwareness};
use crate::error::{Error, Result};
-use crate::protocol::{drain_satisfied, freeze_quorum_met, plan_partial_rebalance, warm_satisfied};
+use crate::protocol::{
+ drain_satisfied, freeze_quorum_met, missing_freeze_ackers, past_phase_deadline,
+ plan_partial_rebalance, warm_satisfied,
+};
use crate::store::{self, PersonhogStore};
use crate::strategy::AssignmentStrategy;
-use crate::types::{AssignmentPrecondition, HandoffPhase, HandoffState, PodStatus, RegisteredPod};
+use crate::types::{
+ AssignmentPrecondition, HandoffPhase, HandoffReplacement, HandoffState, PodStatus,
+ RegisteredPod, RegisteredRouter,
+};
use crate::util;
@@ -36,39 +42,37 @@ pub struct CoordinatorConfig {
/// indefinitely, and doubles as defense-in-depth for anything else
/// that slips through the event-driven paths.
pub reconcile_interval: Duration,
- /// How long a handoff may sit in a pre-terminal phase before the
- /// coordinator cancels it and lets the next plan try again.
+ /// How long a handoff may sit in Freezing or Draining before the
+ /// coordinator cancels it — by atomic replacement with whatever
+ /// resolves its stashes — and lets the plan try again.
///
/// This is the backstop for causes we have not found: a participant
- /// that never acks leaves a handoff that no other path removes —
- /// cleanup only deletes handoffs whose new owner is gone, and an
- /// in-flight handoff pins its partition so no re-plan can touch it.
- /// Cancelling is the only safe response; force-advancing past a
+ /// that never acks leaves a handoff that no other path removes, and
+ /// an in-flight handoff pins its partition so no re-plan can touch
+ /// it. Cancelling is the only safe response; force-advancing past a
/// missing freeze ack is exactly the split-brain the quorum exists
/// to prevent.
///
- /// Measured against the handoff's total age rather than time in its
- /// current phase: `started_at` is the only timestamp the record
- /// carries, and a per-phase budget derived from it would silently
- /// shrink for whichever phase happened to run last. One end-to-end
- /// budget is also the honest statement of intent — a handoff should
- /// finish, and how it divides its time between freezing, draining,
- /// and warming is not something to police.
+ /// Measured against time in the current phase (`phase_entered_at_ms`,
+ /// which every phase advance restamps): wedged is a property of a
+ /// phase, not of a lifetime. Freezing and Draining wait only on
+ /// acknowledgements, so their budget can be tight; Warming does real
+ /// work that scales with the partition and gets its own budget below.
///
- /// Generous by design: healthy handoffs complete in a few seconds,
- /// so this sits orders of magnitude above them. Too tight a bound
- /// would cancel the handoffs that are merely slow.
- ///
- /// Ages are wall-clock differences that may span machines: a
- /// handoff created by one coordinator can be evaluated by its
- /// successor after a failover, so clock skew between nodes shifts
- /// the effective deadline by its magnitude. That is tolerated
- /// rather than engineered away — skew is NTP-bounded at
- /// milliseconds against a deadline of minutes, and a mistimed
- /// cancellation is safe in either direction: early, the re-plan
- /// recreates the handoff stamped and judged by one clock; late, a
- /// wedge lives that much longer before cancellation.
+ /// Generous by design: healthy ack waits complete in seconds, so
+ /// this sits orders of magnitude above them. Ages are wall-clock
+ /// differences that may span machines (a failover successor judges
+ /// records its predecessor stamped); NTP-bounded skew against a
+ /// deadline of minutes is tolerated, and a mistimed cancellation is
+ /// safe in either direction — early, the replacement is stamped and
+ /// judged by one clock; late, a wedge lives that much longer.
pub handoff_deadline: Duration,
+ /// How long a handoff may sit in Warming. A warm replays the
+ /// partition's changelog, whose length scales with the data — under
+ /// a general deadline a partition whose replay outlives the budget
+ /// could never complete: cancel, replan, warm from zero, forever.
+ /// Zero disables the Warming budget entirely.
+ pub warming_deadline: Duration,
}
impl Default for CoordinatorConfig {
@@ -88,6 +92,25 @@ impl Default for CoordinatorConfig {
rebalance_debounce_interval: Duration::from_secs(1),
reconcile_interval: Duration::from_secs(5),
handoff_deadline: Duration::from_secs(120),
+ warming_deadline: Duration::from_secs(1800),
+ }
+ }
+}
+
+/// The per-phase cancellation budgets, bundled for every path that
+/// judges handoff age (see `CoordinatorConfig::handoff_deadline` and
+/// `warming_deadline`).
+#[derive(Clone, Copy)]
+struct PhaseDeadlines {
+ handoff: Duration,
+ warming: Duration,
+}
+
+impl CoordinatorConfig {
+ fn phase_deadlines(&self) -> PhaseDeadlines {
+ PhaseDeadlines {
+ handoff: self.handoff_deadline,
+ warming: self.warming_deadline,
}
}
}
@@ -244,6 +267,7 @@ impl Coordinator {
let strategy = Arc::clone(&self.strategy);
let k8s_awareness = self.k8s_awareness.clone();
let debounce_interval = self.config.rebalance_debounce_interval;
+ let deadlines = self.config.phase_deadlines();
let replan = Arc::clone(&replan);
let token = cancel.child_token();
tasks.spawn(async move {
@@ -252,6 +276,7 @@ impl Coordinator {
strategy,
k8s_awareness,
debounce_interval,
+ deadlines,
replan,
token,
pods_stream,
@@ -264,10 +289,18 @@ impl Coordinator {
let store = Arc::clone(&self.store);
let strategy = Arc::clone(&self.strategy);
let k8s_awareness = self.k8s_awareness.clone();
+ let deadlines = self.config.phase_deadlines();
let token = cancel.child_token();
tasks.spawn(async move {
- Self::watch_handoffs_loop(store, strategy, k8s_awareness, token, handoffs_stream)
- .await
+ Self::watch_handoffs_loop(
+ store,
+ strategy,
+ k8s_awareness,
+ deadlines,
+ token,
+ handoffs_stream,
+ )
+ .await
});
}
@@ -298,12 +331,11 @@ impl Coordinator {
{
let store = Arc::clone(&self.store);
let interval = self.config.reconcile_interval;
- let handoff_deadline = self.config.handoff_deadline;
let replan = Arc::clone(&replan);
let token = cancel.child_token();
- tasks.spawn(async move {
- Self::reconcile_tick_loop(store, interval, handoff_deadline, replan, token).await
- });
+ tasks.spawn(
+ async move { Self::reconcile_tick_loop(store, interval, replan, token).await },
+ );
}
// Reconcile any handoffs that already have full ack quorum.
@@ -326,11 +358,13 @@ impl Coordinator {
result
}
+ #[allow(clippy::too_many_arguments)]
async fn watch_pods_loop(
store: Arc<PersonhogStore>,
strategy: Arc<dyn AssignmentStrategy>,
k8s_awareness: Option<Arc<K8sAwareness>>,
debounce_interval: Duration,
+ deadlines: PhaseDeadlines,
replan: Arc<Notify>,
cancel: CancellationToken,
mut stream: WatchStream,
@@ -361,8 +395,13 @@ impl Coordinator {
}
}
- Self::handle_pod_change_static(&store, strategy.as_ref(), k8s_awareness.as_deref())
- .await?;
+ Self::handle_pod_change_static(
+ &store,
+ strategy.as_ref(),
+ k8s_awareness.as_deref(),
+ deadlines,
+ )
+ .await?;
}
}
@@ -379,6 +418,7 @@ impl Coordinator {
store: Arc<PersonhogStore>,
strategy: Arc<dyn AssignmentStrategy>,
k8s_awareness: Option<Arc<K8sAwareness>>,
+ deadlines: PhaseDeadlines,
cancel: CancellationToken,
mut stream: WatchStream,
) -> Result<()> {
@@ -418,6 +458,7 @@ impl Coordinator {
&store,
strategy.as_ref(),
k8s_awareness.as_deref(),
+ deadlines,
)
.await?;
}
@@ -466,7 +507,6 @@ impl Coordinator {
async fn reconcile_tick_loop(
store: Arc<PersonhogStore>,
interval: Duration,
- handoff_deadline: Duration,
replan: Arc<Notify>,
cancel: CancellationToken,
) -> Result<()> {
@@ -480,21 +520,24 @@ impl Coordinator {
Self::handle_handoff_update_static(&store, handoff).await?;
Self::check_phase_advance(&store, handoff.partition).await?;
}
- // Advancement first, cancellation second: a handoff
- // that can still progress gets every chance to before
- // its deadline is considered. A cancellation wakes
- // the planning loop, since deleting a handoff fires
- // no pod event and the placement is now short of
- // desired.
- if Self::cancel_expired_handoffs(&store, &handoffs, handoff_deadline).await? {
- replan.notify_one();
- }
+ // Advancement first, planning second: a handoff that
+ // can still progress gets every chance to before the
+ // planner judges it. The wake is unconditional —
+ // level-triggered planning, exactly as the stateright
+ // model assumes (its Rebalance action is enabled in
+ // every state). The planner is cheap when there is
+ // nothing to do, and an unconditional wake is what
+ // catches the events no watch delivers: a pod
+ // registration lost to a dropped stream, a doomed
+ // handoff whose trigger event never arrived, placement
+ // drift of any cause. Cancellation itself is a
+ // planning decision — the planner replaces a doomed
+ // handoff with whatever resolves its stashes.
+ replan.notify_one();
// The gauge refresh is best-effort and runs after the
// reconcile pass: its reads exist only for metrics and
- // must never delay or interrupt handoff advancement —
- // this tick is the liveness backstop for router
- // departures, which fire no watched event. A skipped
- // refresh is repaired by the next tick.
+ // must never delay or interrupt handoff advancement.
+ // A skipped refresh is repaired by the next tick.
let pods = store.list_pods().await;
let routers = store.list_routers().await;
match (pods, routers) {
@@ -644,6 +687,7 @@ impl Coordinator {
&self.store,
self.strategy.as_ref(),
self.k8s_awareness.as_deref(),
+ self.config.phase_deadlines(),
)
.await
}
@@ -652,6 +696,7 @@ impl Coordinator {
store: &PersonhogStore,
strategy: &dyn AssignmentStrategy,
k8s_awareness: Option<&K8sAwareness>,
+ deadlines: PhaseDeadlines,
) -> Result<()> {
let pods = store.list_pods().await?;
let total_partitions = match store.get_total_partitions().await {
@@ -670,22 +715,30 @@ impl Coordinator {
active_pods = filter_pods_for_k8s(k8s, &pods, active_pods).await;
}
- // Clean up any in-flight handoffs targeting pods whose etcd
- // registration has disappeared. This happens when a pod crashes
- // during the Warming phase before it can ack — the handoff would
- // be stuck forever otherwise.
- Self::cleanup_stale_handoffs(store).await?;
-
- // In-flight handoffs pin their partitions: the plan excludes them
- // (no second handoff, no assignment write) and attributes them to
- // their target for the balance math, so a stuck handoff defers
- // only its own partition instead of all rebalancing.
- let in_flight = store.list_handoffs().await?;
- if !in_flight.is_empty() {
- tracing::info!(
- pinned = in_flight.len(),
- "planning around in-flight handoffs"
- );
+ // Classify the in-flight handoffs. One whose new owner's
+ // registration is gone can never advance (no WarmedAck will ever
+ // arrive); one that has outstayed its phase's deadline is wedged
+ // on an acknowledgement that is not coming. Both are cancelled by
+ // this pass — never by deletion, but by atomic replacement with
+ // whatever resolves their stashes, decided once the plan is
+ // known. A dead *old* owner is deliberately not a trigger:
+ // Freezing waits on routers, an absent old owner in Draining is
+ // vacuously drained, and such handoffs advance on their own —
+ // cancelling them would tear down a healthy in-flight warm.
+ // Everything else pins its partition: the plan excludes it and
+ // attributes it to its target, so a stuck handoff defers only
+ // its own partition.
+ let in_flight = store.list_handoffs_with_mod_revisions().await?;
+ let registered: HashSet<&str> = pods.iter().map(|p| p.pod_name.as_str()).collect();
+ let now_ms = util::now_millis();
+ let (cancelled, pinned): (Vec<_>, Vec<_>) = in_flight.into_iter().partition(|(h, _)| {
+ h.phase != HandoffPhase::Complete
+ && (!registered.contains(h.new_owner.as_str())
+ || past_phase_deadline(h, now_ms, deadlines.handoff, deadlines.warming))
+ });
+ let pinned: Vec<HandoffState> = pinned.into_iter().map(|(h, _)| h).collect();
+ if !pinned.is_empty() {
+ tracing::info!(pinned = pinned.len(), "planning around in-flight handoffs");
}
// One revisioned snapshot feeds both the placement computation and
@@ -705,16 +758,18 @@ impl Coordinator {
// Placement and diff semantics (moves carry the prior owner, fresh
// partitions carry none, everything goes through Freezing) live in
// `protocol::plan_partial_rebalance`, shared with the stateright
- // model.
+ // model. Cancelled partitions are deliberately not pinned: the
+ // plan is free to place them, and whatever it decides becomes
+ // their replacement below.
let plan = plan_partial_rebalance(
strategy,
&current_map,
- &in_flight,
+ &pinned,
&active_pods,
total_partitions,
);
- if plan.handoffs.is_empty() {
+ if plan.handoffs.is_empty() && cancelled.is_empty() {
tracing::debug!("no handoffs needed");
return Ok(());
}
@@ -723,15 +778,10 @@ impl Coordinator {
// once, rather than per-check: the whole point is that the
// requirement is fixed at creation and cannot grow as routers
// come and go (see `HandoffState::freeze_quorum`).
- let freeze_quorum: Vec<String> = store
- .list_routers()
- .await?
- .into_iter()
- .map(|r| r.router_name)
- .collect();
+ let routers = store.list_routers().await?;
+ let freeze_quorum: Vec<String> = routers.iter().map(|r| r.router_name.clone()).collect();
let now = util::now_seconds();
- let now_ms = util::now_millis();
let handoff_objects: Vec<HandoffState> = plan
.handoffs
.iter()
@@ -752,14 +802,93 @@ impl Coordinator {
})
.collect();
- let moves = plan
- .handoffs
+ // Disposition for every cancelled handoff, in one pass over the
+ // plan. A cancelled partition the plan re-placed gets its
+ // successor as an atomic replacement — routers keep stashing
+ // without ever observing a gap. One the plan left alone resolves
+ // to its live current owner as a reaffirm: `Complete` toward that
+ // owner, which drains stashes home through the routers' ordinary
+ // Complete handling and converges the owner pod back to serving.
+ // (`old_owner` stays `None` on a reaffirm — naming the owner on
+ // both sides would match `desired_state`'s old-owner arm first
+ // and make the pod release the partition instead of resuming.)
+ // Only when neither exists — owner dead, nothing placeable — is
+ // the record deleted outright, which is safe fail-closed: with no
+ // live owner there is no one to drain to, and rejected requests
+ // surface as retryable errors rather than lost writes.
+ let mut cancelled_by_partition: HashMap<u32, (HandoffState, i64)> = cancelled
+ .into_iter()
+ .map(|(h, rev)| (h.partition, (h, rev)))
+ .collect();
+ let mut creations: Vec<HandoffState> = Vec::new();
+ let mut replacements: Vec<HandoffReplacement> = Vec::new();
+ let mut fallback_deletes: Vec<(HandoffState, i64)> = Vec::new();
+ let mut replaced_dispositions: Vec<&'static str> = Vec::new();
+
+ for handoff in handoff_objects {
+ match cancelled_by_partition.remove(&handoff.partition) {
+ Some((predecessor, mod_revision)) => {
+ Self::log_cancellation(store, &routers, &predecessor, &registered, "successor")
+ .await;
+ replacements.push(HandoffReplacement {
+ handoff,
+ expected_mod_revision: mod_revision,
+ });
+ replaced_dispositions.push("successor");
+ }
+ None => creations.push(handoff),
+ }
+ }
+ for (predecessor, mod_revision) in cancelled_by_partition.into_values() {
+ let owner = current_map
+ .get(&predecessor.partition)
+ .filter(|owner| registered.contains(owner.as_str()));
+ match owner {
+ Some(owner) => {
+ Self::log_cancellation(store, &routers, &predecessor, &registered, "reaffirm")
+ .await;
+ replacements.push(HandoffReplacement {
+ handoff: HandoffState {
+ partition: predecessor.partition,
+ old_owner: None,
+ new_owner: owner.clone(),
+ new_owner_address: pods
+ .iter()
+ .find(|p| &p.pod_name == owner)
+ .and_then(|p| p.advertise_address.clone()),
+ phase: HandoffPhase::Complete,
+ started_at: now,
+ handoff_id: util::new_handoff_id(),
+ freeze_quorum: Some(Vec::new()),
+ created_at_ms: now_ms,
+ phase_entered_at_ms: now_ms,
+ },
+ expected_mod_revision: mod_revision,
+ });
+ replaced_dispositions.push("reaffirm");
+ }
+ None => {
+ Self::log_cancellation(store, &routers, &predecessor, &registered, "delete")
+ .await;
+ fallback_deletes.push((predecessor, mod_revision));
+ }
+ }
+ }
+
+ let moves = creations
.iter()
- .filter(|h| h.old_owner.is_some())
+ .chain(replacements.iter().map(|r| &r.handoff))
+ .filter(|h| h.phase == HandoffPhase::Freezing && h.old_owner.is_some())
.count();
+ let freezing_total = creations.len()
+ + replacements
+ .iter()
+ .filter(|r| r.handoff.phase == HandoffPhase::Freezing)
+ .count();
tracing::info!(
reassignments = moves,
- fresh = plan.handoffs.len() - moves,
+ fresh = freezing_total - moves,
+ replaced = replacements.len(),
"creating handoffs"
);
@@ -769,8 +898,9 @@ impl Coordinator {
// events, and a stale plan can never restore a superseded owner.
// Each handoff instead carries a precondition tying it to the
// snapshot its old_owner came from.
- let preconditions: Vec<AssignmentPrecondition> = handoff_objects
+ let preconditions: Vec<AssignmentPrecondition> = creations
.iter()
+ .chain(replacements.iter().map(|r| &r.handoff))
.map(|h| match assignment_revisions.get(&h.partition) {
Some(&mod_revision) => AssignmentPrecondition::UnchangedSince {
partition: h.partition,
@@ -782,9 +912,10 @@ impl Coordinator {
})
.collect();
- if !store
- .create_assignments_and_handoffs(&[], &handoff_objects, &preconditions)
- .await?
+ if (!creations.is_empty() || !replacements.is_empty())
+ && !store
+ .apply_plan(&[], &creations, &replacements, &preconditions)
+ .await?
{
// A concurrent invocation (the empty-set re-trigger racing a
// pod event, or a failing-over coordinator) created a handoff
@@ -794,170 +925,103 @@ impl Coordinator {
tracing::info!("concurrent plan won handoff creation; standing down");
return Ok(());
}
+ for disposition in &replaced_dispositions {
+ counter!(
+ "personhog_coordination_handoffs_replaced_total",
+ "disposition" => *disposition,
+ )
+ .increment(1);
+ }
+
+ // The fallback deletes are per-partition guarded transactions
+ // outside the plan txn: each partition's disposition is atomic on
+ // its own, which is what the safety argument needs, and a stale
+ // guard only ever skips a cancel for a record that changed under
+ // us.
+ for (predecessor, mod_revision) in fallback_deletes {
+ if store
+ .delete_handoff_and_acks_if_unchanged(predecessor.partition, mod_revision)
+ .await?
+ {
+ counter!(
+ "personhog_coordination_handoffs_replaced_total",
+ "disposition" => "delete",
+ )
+ .increment(1);
+ }
+ }
counter!("personhog_coordination_handoffs_created_total", "kind" => "move")
.increment(moves as u64);
counter!("personhog_coordination_handoffs_created_total", "kind" => "fresh")
- .increment((plan.handoffs.len() - moves) as u64);
+ .increment((freezing_total - moves) as u64);
// Nudge advancement for handoffs whose preconditions are already
// satisfied at creation time (no old_owner, dead old_owner, vacuous
// router quorum). Without this, such handoffs would stall waiting
// for an ack event that will never arrive — the watch loop's nudge
// only catches subsequent Put events.
- for handoff in &handoff_objects {
+ for handoff in creations
+ .iter()
+ .chain(replacements.iter().map(|r| &r.handoff))
+ {
Self::check_phase_advance(store, handoff.partition).await?;
}
Ok(())
}
- /// Cancel handoffs that have sat in one phase past its deadline.
- ///
- /// Nothing else removes a handoff that simply never gets its ack:
- /// `cleanup_stale_handoffs` only fires when the new owner is gone,
- /// and an in-flight handoff pins its partition so no re-plan can
- /// touch it. Deleting is the only safe response — advancing without
- /// the ack is the split-brain the phase exists to prevent — and the
- /// next plan is free to try again, with a fresh handoff id and a
- /// fresh quorum snapshot.
- ///
- /// Deliberately not backed off: the snapshot rule keeps freeze
- /// quorums satisfiable, so repeated cancellation of one partition
- /// means a new cause, and
- /// `handoffs_cancelled_total{reason="phase_deadline"}` exists to
- /// make that visible rather than absorbed.
- ///
- /// Returns whether anything was cancelled, so the caller can wake
- /// the planning loop — a deletion fires no pod event, and without
- /// the wake no re-plan would run until the next unrelated pod
- /// change. `handoffs` is the caller's already-listed snapshot; each
- /// candidate is re-read under mod_revision before deletion, so the
- /// snapshot's staleness only ever skips a cancel, never misdirects
- /// one.
- async fn cancel_expired_handoffs(
+ /// One log line per cancellation, error-level with the cause and the
+ /// disposition — and, for a Freezing predecessor, the required
+ /// routers whose acks never arrived: a freeze wedge is almost always
+ /// one specific non-acking router, and naming it turns the diagnosis
+ /// into reading a label. Attribution is best-effort; a failed ack
+ /// read must not block the replacement.
+ async fn log_cancellation(
store: &PersonhogStore,
- handoffs: &[HandoffState],
- handoff_deadline: Duration,
- ) -> Result<bool> {
- let now = util::now_seconds();
- let deadline = handoff_deadline.as_secs() as i64;
- let mut cancelled = false;
- for handoff in handoffs {
- // Complete is terminal and cleaned up by its own path.
- if handoff.phase == HandoffPhase::Complete {
- continue;
- }
- // A record carrying no creation time cannot be judged on age;
- // deleting it would be acting on an age of "since the epoch"
- // rather than on evidence that it is stuck.
- if handoff.started_at <= 0 {
- continue;
- }
- let age = now.saturating_sub(handoff.started_at);
- if age < deadline {
- continue;
- }
- // Re-read under mod_revision and re-verify the phase before
- // deleting: this runs alongside the watch-driven paths, and
- // the record at this key may already be a successor handoff
- // that has not had its own chance yet.
- let Some((current, mod_revision)) = store
- .get_handoff_with_mod_revision(handoff.partition)
- .await?
- else {
- continue;
- };
- if current.handoff_id != handoff.handoff_id
- || current.phase == HandoffPhase::Complete
- || now.saturating_sub(current.started_at) < deadline
- {
- continue;
- }
- tracing::error!(
- partition = current.partition,
- phase = ?current.phase,
- age_secs = age,
- new_owner = %current.new_owner,
- old_owner = ?current.old_owner,
- "handoff exceeded its deadline; cancelling so a later plan can retry"
- );
- if store
- .delete_handoff_and_acks_if_unchanged(current.partition, mod_revision)
- .await?
- {
- cancelled = true;
- counter!(
- "personhog_coordination_handoffs_cancelled_total",
- "reason" => "phase_deadline",
- )
- .increment(1);
- }
- }
- Ok(cancelled)
- }
-
- /// 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.
- async fn cleanup_stale_handoffs(store: &PersonhogStore) -> Result<()> {
- let handoffs = store.list_handoffs().await?;
- let pods = store.list_pods().await?;
- let registered_set: HashSet<&str> = pods.iter().map(|p| p.pod_name.as_str()).collect();
-
- for handoff in &handoffs {
- 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 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?
- {
- counter!("personhog_coordination_handoffs_cancelled_total", "reason" => "dead_new_owner")
- .increment(1);
- } else {
- tracing::info!(
- partition = current.partition,
- "handoff changed concurrently, skipping cleanup"
- );
+ routers: &[RegisteredRouter],
+ predecessor: &HandoffState,
+ registered: &HashSet<&str>,
+ disposition: &'static str,
+ ) {
+ let reason = if registered.contains(predecessor.new_owner.as_str()) {
+ "phase_deadline"
+ } else {
+ "dead_new_owner"
+ };
+ let missing_ackers = if predecessor.phase == HandoffPhase::Freezing {
+ match store.list_freeze_acks(predecessor.partition).await {
+ Ok(acks) => missing_freeze_ackers(routers, &acks, predecessor),
+ Err(e) => {
+ tracing::warn!(error = %e, "could not read freeze acks for attribution");
+ Vec::new()
+ }
}
+ } else {
+ Vec::new()
+ };
+ tracing::error!(
+ partition = predecessor.partition,
+ phase = ?predecessor.phase,
+ new_owner = %predecessor.new_owner,
+ old_owner = ?predecessor.old_owner,
+ reason,
+ disposition,
+ missing_freeze_ackers = ?missing_ackers,
+ "cancelling handoff by replacement"
+ );
+ counter!(
+ "personhog_coordination_handoffs_cancelled_total",
+ "reason" => reason,
+ )
+ .increment(1);
+ for router in &missing_ackers {
+ counter!(
+ "personhog_coordination_freeze_ack_missing_total",
+ "router" => router.clone(),
+ )
+ .increment(1);
}
-
- Ok(())
}
async fn handle_handoff_update_static(
diff --git a/rust/personhog-coordination/src/pod.rs b/rust/personhog-coordination/src/pod.rs
index b0810f95036d..567ef8f0a68e 100644
--- a/rust/personhog-coordination/src/pod.rs
+++ b/rust/personhog-coordination/src/pod.rs
@@ -1,4 +1,4 @@
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -147,6 +147,17 @@ pub struct PodConfig {
/// Should be less than K8s terminationGracePeriodSeconds to allow
/// time for lease revocation before SIGKILL.
pub drain_timeout: Duration,
+ /// How often the watch loop re-derives every involved partition's
+ /// state from a fresh snapshot, independent of events — the same
+ /// truth path the router's reconcile pass provides. Runs as an arm
+ /// of the watch loop, serialized with event-driven convergence.
+ pub reconcile_interval: Duration,
+ /// How many consecutive reconcile failures to tolerate before
+ /// failing the run. Same reasoning as the router's budget: a failed
+ /// pass only means staleness equal to one tick, brief etcd blips
+ /// must not restart the fleet, and sustained outage self-fences
+ /// through the lease keepalive.
+ pub reconcile_failure_budget: u32,
/// `host:port` where this pod's gRPC server is reachable; registered
/// so routers can dial the pod through the routing table.
pub advertise_address: Option<String>,
@@ -161,19 +172,38 @@ impl Default for PodConfig {
lease_ttl: 30,
heartbeat_interval: Duration::from_secs(10),
drain_timeout: Duration::from_secs(30),
+ reconcile_interval: Duration::from_secs(5),
+ reconcile_failure_budget: 12,
advertise_address: None,
}
}
}
+/// What a partition's warm was installed for. A warm is only as fresh as
+/// the moment it replayed the changelog; `converge` records why each one
+/// was installed so a later Acquiring can tell a warm it may honor from
+/// one left over from an earlier era.
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum WarmProvenance {
+ /// Warmed as (or on the way back to being) the serving owner: a
+ /// process restart, or the returning old owner of an in-flight
+ /// handoff. Current at install time and kept current by the pod's
+ /// own accepted writes for as long as it remains the owner.
+ Serving,
+ /// Warmed for one specific handoff's Warming phase, identified by
+ /// its id.
+ Handoff(String),
+}
+
pub struct PodHandle {
store: Arc<PersonhogStore>,
config: PodConfig,
handler: Arc<dyn HandoffHandler>,
- /// 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 warmed by this process — local, dies with the process —
+ /// each with the provenance of its warm. `converge` consults it to
+ /// decide whether a Serving/Acquiring partition still needs a warm,
+ /// and `drain()` waits for it to empty.
+ warmed_partitions: Mutex<HashMap<u32, WarmProvenance>>,
/// Partitions this process has write-fenced via a drain — local,
/// consulted so convergence to Serving only issues a resume when a
/// fence actually exists.
@@ -195,7 +225,7 @@ impl PodHandle {
store,
config,
handler,
- warmed_partitions: Mutex::new(HashSet::new()),
+ warmed_partitions: Mutex::new(HashMap::new()),
fenced_partitions: Mutex::new(HashSet::new()),
drain_notify: Notify::new(),
k8s_awareness,
@@ -418,7 +448,11 @@ impl PodHandle {
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()
+ warmed
+ .keys()
+ .chain(fenced.iter())
+ .collect::<HashSet<_>>()
+ .len()
}
/// Wait until all held partitions have been released via handoffs.
@@ -460,6 +494,12 @@ impl PodHandle {
partitions.insert(h.partition);
}
}
+ // Locally-held partitions the durable state no longer involves
+ // this pod in still need convergence — that is how a warm or
+ // fence left over from a departed ownership gets released when
+ // the Complete event that should have done it was missed.
+ partitions.extend(self.warmed_partitions.lock().await.keys().copied());
+ partitions.extend(self.fenced_partitions.lock().await.iter().copied());
tracing::info!(
pod,
@@ -505,13 +545,16 @@ impl PodHandle {
match desired {
DesiredState::Serving => {
- if !self.warmed_partitions.lock().await.contains(&partition) {
+ if !self.warmed_partitions.lock().await.contains_key(&partition) {
tracing::info!(pod, partition, "converging to Serving: warming");
let start = Instant::now();
self.handler.warm_partition(partition).await?;
histogram!("personhog_coordination_partition_warm_ms", "trigger" => "restart")
.record(start.elapsed().as_secs_f64() * 1000.0);
- self.warmed_partitions.lock().await.insert(partition);
+ self.warmed_partitions
+ .lock()
+ .await
+ .insert(partition, WarmProvenance::Serving);
} else if self.fenced_partitions.lock().await.contains(&partition) {
tracing::info!(pod, partition, "converging to Serving: resuming writes");
self.handler.resume_partition(partition).await?;
@@ -553,16 +596,47 @@ impl PodHandle {
}
}
DesiredState::Acquiring => {
- if !self.warmed_partitions.lock().await.contains(&partition) {
+ let handoff = handoff.expect("Acquiring state only derives from a handoff");
+ // Only a warm installed for *this* handoff satisfies its
+ // warming. One left over from an earlier era — the pod
+ // was this partition's owner or warming target before,
+ // ownership moved away, and the intervening Released
+ // convergence never ran — can hold values that predate
+ // writes the changelog accepted since. A fresh warm
+ // replays only from the writer's committed offset, so a
+ // stale cache below that offset would keep hitting;
+ // release first and rebuild from clean.
+ let valid = self.warmed_partitions.lock().await.get(&partition).is_some_and(
+ |provenance| {
+ matches!(provenance, WarmProvenance::Handoff(id) if *id == handoff.handoff_id)
+ },
+ );
+ if !valid {
+ if self
+ .warmed_partitions
+ .lock()
+ .await
+ .remove(&partition)
+ .is_some()
+ {
+ tracing::info!(
+ pod,
+ partition,
+ "converging to Acquiring: releasing a warm from an earlier era"
+ );
+ self.handler.release_partition(partition).await?;
+ }
tracing::info!(pod, partition, "converging to Acquiring: warming");
let start = Instant::now();
self.handler.warm_partition(partition).await?;
histogram!("personhog_coordination_partition_warm_ms", "trigger" => "handoff")
.record(start.elapsed().as_secs_f64() * 1000.0);
- self.warmed_partitions.lock().await.insert(partition);
+ self.warmed_partitions.lock().await.insert(
+ partition,
+ WarmProvenance::Handoff(handoff.handoff_id.clone()),
+ );
}
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(),
@@ -574,7 +648,12 @@ impl PodHandle {
tracing::info!(pod, partition, "warmed ack written");
}
DesiredState::Released => {
- let was_warmed = self.warmed_partitions.lock().await.remove(&partition);
+ let was_warmed = self
+ .warmed_partitions
+ .lock()
+ .await
+ .remove(&partition)
+ .is_some();
let was_fenced = self.fenced_partitions.lock().await.remove(&partition);
if was_warmed || was_fenced {
tracing::info!(pod, partition, "converging to Released: releasing");
@@ -596,9 +675,48 @@ impl PodHandle {
mut stream: WatchStream,
cancel: CancellationToken,
) -> Result<()> {
+ // The truth path: periodically re-derive every involved
+ // partition from a fresh snapshot, repairing whatever the event
+ // path failed to deliver. First pass one interval out — the
+ // startup reconcile has just run. An arm of this loop on
+ // purpose: convergence stays serialized with event handling.
+ let mut reconcile_tick = tokio::time::interval_at(
+ tokio::time::Instant::now() + self.config.reconcile_interval,
+ self.config.reconcile_interval,
+ );
+ let mut consecutive_reconcile_failures: u32 = 0;
loop {
tokio::select! {
_ = cancel.cancelled() => return Ok(()),
+ _ = reconcile_tick.tick() => {
+ // Tolerated for the same reason as the router's
+ // reconcile arm: a failed pass leaves the pod as
+ // stale as one tick ago and the next success fully
+ // compensates, so a brief etcd blip must not take
+ // the data plane down with it. The budget bounds
+ // the reads-failing-while-lease-healthy mode.
+ match self.reconcile_all().await {
+ Ok(_) => consecutive_reconcile_failures = 0,
+ Err(e) => {
+ consecutive_reconcile_failures += 1;
+ counter!(
+ "personhog_coordination_reconcile_failures_total",
+ "component" => "pod"
+ )
+ .increment(1);
+ tracing::warn!(
+ pod = %self.config.pod_name,
+ error = %e,
+ consecutive = consecutive_reconcile_failures,
+ budget = self.config.reconcile_failure_budget,
+ "pod reconcile failed; continuing on last-known state"
+ );
+ if consecutive_reconcile_failures >= self.config.reconcile_failure_budget {
+ return Err(e);
+ }
+ }
+ }
+ }
msg = stream.message() => {
let resp = msg?.ok_or_else(|| Error::invalid_state("handoff watch stream ended".to_string()))?;
for event in resp.events() {
diff --git a/rust/personhog-coordination/src/protocol.rs b/rust/personhog-coordination/src/protocol.rs
index 463c311ea302..e710e60417eb 100644
--- a/rust/personhog-coordination/src/protocol.rs
+++ b/rust/personhog-coordination/src/protocol.rs
@@ -11,12 +11,14 @@
//! `list_*_acks(partition)` returns them).
use std::collections::{HashMap, HashSet};
+use std::time::Duration;
use assignment_coordination::util::compute_required_handoffs;
use crate::strategy::AssignmentStrategy;
use crate::types::{
- HandoffState, PodDrainedAck, PodWarmedAck, RegisteredPod, RegisteredRouter, RouterFreezeAck,
+ HandoffPhase, HandoffState, PodDrainedAck, PodWarmedAck, RegisteredPod, RegisteredRouter,
+ RouterFreezeAck,
};
/// One handoff a rebalance has decided to create. `old_owner` is `None`
@@ -167,6 +169,69 @@ pub fn required_freeze_ackers<'a>(
})
}
+/// Whether `handoff` has sat in its *current phase* longer than that
+/// phase's deadline.
+///
+/// Per-phase rather than total-age on purpose: the deadline exists to
+/// catch a handoff that is wedged, and wedged is a property of a phase,
+/// not of a lifetime. Freezing and Draining wait only on
+/// acknowledgements, so their budget is short. Warming replays a
+/// changelog whose length scales with the partition — a total-age
+/// deadline would cancel a legitimately long warm and restart it from
+/// zero, forever. Warming therefore gets its own, far more generous
+/// budget (`warming_deadline`; zero disables it).
+///
+/// Records written before the phase clock existed carry a zero
+/// `phase_entered_at_ms`; they fall back to the creation-time seconds
+/// clock. A record with neither stamp cannot be judged on age at all —
+/// acting on it would be acting on an age of "since the epoch".
+pub fn past_phase_deadline(
+ handoff: &HandoffState,
+ now_ms: i64,
+ handoff_deadline: Duration,
+ warming_deadline: Duration,
+) -> bool {
+ if handoff.phase == HandoffPhase::Complete {
+ return false;
+ }
+ let entered_ms = if handoff.phase_entered_at_ms > 0 {
+ handoff.phase_entered_at_ms
+ } else if handoff.started_at > 0 {
+ handoff.started_at.saturating_mul(1000)
+ } else {
+ return false;
+ };
+ let deadline = match handoff.phase {
+ HandoffPhase::Warming => warming_deadline,
+ _ => handoff_deadline,
+ };
+ if deadline.is_zero() {
+ return false;
+ }
+ now_ms.saturating_sub(entered_ms) > deadline.as_millis() as i64
+}
+
+/// The subset of [`required_freeze_ackers`] whose ack for `handoff` has
+/// not arrived. Acks are correlated by handoff id, exactly as in
+/// [`freeze_quorum_met`]: a stale ack left over from a predecessor
+/// handoff of the same partition must not mask a router that has yet to
+/// observe this one.
+pub fn missing_freeze_ackers(
+ routers: &[RegisteredRouter],
+ freeze_acks: &[RouterFreezeAck],
+ handoff: &HandoffState,
+) -> Vec<String> {
+ let acked: HashSet<&str> = freeze_acks
+ .iter()
+ .filter(|a| a.handoff_id == handoff.handoff_id)
+ .map(|a| a.router_name.as_str())
+ .collect();
+ required_freeze_ackers(routers, handoff)
+ .filter(|name| !acked.contains(name))
+ .map(str::to_string)
+ .collect()
+}
+
/// Whether the drain requirement for `handoff` is satisfied.
///
/// "Alive" here means the old owner's etcd registration key still exists
@@ -215,7 +280,7 @@ mod tests {
partition,
old_owner: old_owner.map(str::to_string),
new_owner: new_owner.to_string(),
- phase: crate::types::HandoffPhase::Warming,
+ phase: HandoffPhase::Warming,
started_at: 0,
handoff_id: String::new(),
freeze_quorum: None,
@@ -258,6 +323,76 @@ mod tests {
);
}
+ /// The deadline is a per-phase clock: a warm that outlives the
+ /// general deadline must survive on Warming's own budget, while a
+ /// wedged freeze of the same age cancels. A total-age deadline would
+ /// livelock any partition whose changelog replay exceeds it — cancel,
+ /// replan, warm from zero, cancel again.
+ #[test]
+ fn deadline_is_per_phase_and_patient_with_warming() {
+ let short = Duration::from_secs(120);
+ let long = Duration::from_secs(1800);
+ let mut h = handoff(0, Some("pod-a"), "pod-b");
+ h.phase = HandoffPhase::Warming;
+ h.phase_entered_at_ms = 1_000;
+ let now = 1_000 + 600_000;
+
+ assert!(
+ !past_phase_deadline(&h, now, short, long),
+ "ten minutes into a warm is within Warming's budget"
+ );
+ h.phase = HandoffPhase::Freezing;
+ assert!(
+ past_phase_deadline(&h, now, short, long),
+ "the same age in Freezing is a wedge"
+ );
+
+ // The phase clock restarts on advancement: a warm that follows a
+ // slow freeze starts a fresh budget.
+ h.phase = HandoffPhase::Warming;
+ h.phase_entered_at_ms = now - 1_000;
+ assert!(!past_phase_deadline(&h, now, short, long));
+
+ // Zero disables a budget outright.
+ h.phase_entered_at_ms = 1_000;
+ assert!(!past_phase_deadline(&h, now, short, Duration::ZERO));
+ }
+
+ /// Pre-upgrade records fall back to the creation-time seconds clock;
+ /// a record with no stamp at all is never judged on age.
+ #[test]
+ fn deadline_falls_back_to_started_at_and_skips_unstamped_records() {
+ let short = Duration::from_secs(120);
+ let long = Duration::from_secs(1800);
+ let mut h = handoff(0, Some("pod-a"), "pod-b");
+ h.phase = HandoffPhase::Freezing;
+
+ h.started_at = 1;
+ assert!(past_phase_deadline(&h, 601_000, short, long));
+
+ h.started_at = 0;
+ assert!(!past_phase_deadline(&h, i64::MAX, short, long));
+ }
+
+ /// Attribution mirror of the quorum predicate: the missing set names
+ /// exactly the required routers whose ack for *this* handoff hasn't
+ /// arrived — a stale ack from a predecessor handoff must not hide
+ /// one.
+ #[test]
+ fn missing_ackers_names_the_holdout_and_ignores_stale_acks() {
+ let mut h = handoff(0, Some("pod-a"), "pod-b");
+ h.freeze_quorum = Some(vec!["router-0".to_string(), "router-1".to_string()]);
+ let mut stale = freeze_ack("router-1", &h);
+ stale.handoff_id = "a-previous-handoff".to_string();
+ let acks = [freeze_ack("router-0", &h), stale];
+
+ assert_eq!(
+ missing_freeze_ackers(&[router("router-0"), router("router-1")], &acks, &h),
+ vec!["router-1".to_string()],
+ "router-1's stale ack proves nothing about this handoff"
+ );
+ }
+
/// The other direction is what keeps it safe: a router that was
/// present at creation may hold a routing table pointing at the old
/// owner, so its ack stays mandatory.
diff --git a/rust/personhog-coordination/src/routing_table.rs b/rust/personhog-coordination/src/routing_table.rs
index 453fb5581b96..0a198dcd6c84 100644
--- a/rust/personhog-coordination/src/routing_table.rs
+++ b/rust/personhog-coordination/src/routing_table.rs
@@ -1,10 +1,12 @@
-use std::collections::HashMap;
-use std::sync::{Arc, RwLock as StdRwLock};
-use std::time::Duration;
+use std::collections::{HashMap, HashSet};
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, Mutex as StdMutex, RwLock as StdRwLock};
+use std::time::{Duration, Instant};
use async_trait::async_trait;
use etcd_client::{EventType, WatchStream};
use tokio::sync::RwLock;
+use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use assignment_coordination::store::parse_watch_value;
@@ -26,7 +28,125 @@ pub trait StashHandler: Send + Sync {
async fn begin_stash(&self, partition: u32, new_owner: &str) -> Result<()>;
/// Drain stashed writes to the given target and resume normal routing.
- async fn drain_stash(&self, partition: u32, target: &str) -> Result<()>;
+ /// `cancel` requests a cooperative stop: implementations yield at a
+ /// batch boundary, leaving any remaining stash intact for a successor
+ /// drain.
+ async fn drain_stash(
+ &self,
+ partition: u32,
+ target: &str,
+ cancel: CancellationToken,
+ ) -> Result<()>;
+
+ /// Whether the partition's stash lifecycle is still open — an entry
+ /// exists, holding parked requests or an unflushed (possibly empty)
+ /// stash window. This is the authority the reconcile pass consults
+ /// before re-requesting a drain: a settled partition has no entry
+ /// (the drain's final act evicts it), while a drain that yielded
+ /// early leaves the entry and its backlog behind, so re-requesting
+ /// is exactly the retry mechanism. Entry existence — not backlog
+ /// depth — is the correct predicate, because a completed handoff
+ /// with an empty stash window still needs one drain to settle and
+ /// evict the entry; gating on parked requests would leave that
+ /// window open forever.
+ ///
+ /// Defaults to `true`, which preserves the always-request behavior
+ /// for implementations that don't track stash state.
+ fn stash_pending(&self, _partition: u32) -> bool {
+ true
+ }
+}
+
+/// Runs drains off the handoff watch loop, one lane per partition.
+///
+/// A drain's duration is data-plane work — it scales with queue depth,
+/// arrival rate, and the health of the target pod — so it is never awaited
+/// on the watch loop, where it would gate freeze acks and routing updates
+/// for every partition. Lanes serialize drains per partition: requesting a
+/// drain toward a different target supersedes the one in flight (its token
+/// is cancelled and it yields at a batch boundary, leaving the stash entry
+/// live), and the new drain starts only after the old one has fully
+/// stopped, so two drains can never interleave batches toward different
+/// targets. A request toward the same target is absorbed by the running
+/// drain, whose loop already covers later arrivals. Lane entries are
+/// retained after completion — the map is bounded by the partition count,
+/// and a finished lane costs one no-op cancel and an immediate join on the
+/// next request.
+struct DrainLanes {
+ /// Parent of every drain token, so cancelling it stops all drains on
+ /// shutdown.
+ cancel: CancellationToken,
+ lanes: StdMutex<HashMap<u32, Lane>>,
+}
+
+struct Lane {
+ token: CancellationToken,
+ handle: JoinHandle<()>,
+ target: String,
+}
+
+impl DrainLanes {
+ fn new(cancel: CancellationToken) -> Self {
+ Self {
+ cancel,
+ lanes: StdMutex::new(HashMap::new()),
+ }
+ }
+
+ /// Start the drain for `partition` toward `target`, superseding any
+ /// drain already in flight for the partition toward a different
+ /// target.
+ fn request(
+ &self,
+ handler: Arc<dyn StashHandler>,
+ router_name: String,
+ partition: u32,
+ target: String,
+ ) {
+ let token = self.cancel.child_token();
+ let task_token = token.clone();
+ let mut lanes = self.lanes.lock().expect("drain lanes lock poisoned");
+ // A drain already running toward the same target covers everything
+ // this request would: its loop keeps taking batches until it
+ // observes the queue empty, including arrivals after this point.
+ // Restarting it would only fail the requests it has in flight —
+ // which the routine post-`Complete` handoff cleanup would do on
+ // every healthy handoff, since its deletion event drains back to
+ // the owner the table already flipped to.
+ if let Some(prev) = lanes.get(&partition) {
+ if prev.target == target && !prev.token.is_cancelled() && !prev.handle.is_finished() {
+ return;
+ }
+ }
+ let prev = lanes.remove(&partition);
+ let task_target = target.clone();
+ let handle = tokio::spawn(async move {
+ if let Some(prev) = prev {
+ prev.token.cancel();
+ drop(prev.handle.await);
+ }
+ if let Err(e) = handler
+ .drain_stash(partition, &task_target, task_token)
+ .await
+ {
+ tracing::error!(
+ router = %router_name,
+ partition,
+ target = %task_target,
+ error = %e,
+ "stash drain failed; remaining stash awaits a successor drain"
+ );
+ }
+ });
+ lanes.insert(
+ partition,
+ Lane {
+ token,
+ handle,
+ target,
+ },
+ );
+ }
}
/// Configuration for the routing table.
@@ -35,6 +155,36 @@ pub struct RoutingTableConfig {
pub router_name: String,
pub lease_ttl: i64,
pub heartbeat_interval: Duration,
+ /// Fail the run when the handoff watch loop makes no progress for
+ /// this long. Registration is lease-backed and the lease keepalive is
+ /// its own task, so a router whose watch loop has stalled stays
+ /// registered — counted in every freeze quorum — while never acking:
+ /// one such router wedges every handoff in the cluster. The watchdog
+ /// closes that divergence by tying the registration's fate to loop
+ /// progress: on a stall the run errors out, deregisters on the way
+ /// down, and the process supervisor restarts a healthy participant.
+ /// `None` disables the watchdog.
+ pub participant_stall_threshold: Option<Duration>,
+ /// How often the watch loop re-derives its state from a fresh etcd
+ /// snapshot, independent of events. Watches are the latency path;
+ /// this pass is the truth path — it repairs anything a dropped,
+ /// stalled, or reconnected watch stream failed to deliver, exactly
+ /// as the coordinator's reconcile tick and the pod's fresh-read
+ /// convergence do for theirs. It runs as an arm of the watch loop
+ /// itself, so the routing table keeps a single writer and the stall
+ /// watchdog supervises it too.
+ pub reconcile_interval: Duration,
+ /// How many consecutive reconcile-pass failures to tolerate before
+ /// failing the run. A failed pass leaves the router exactly as
+ /// stale as the previous tick — the watch-driven steady state — so
+ /// a single failure carries no safety content and brief etcd blips
+ /// must not restart the fleet; sustained outage already self-fences
+ /// through the lease keepalive. The budget bounds the partial mode
+ /// where snapshot reads fail while the lease stays healthy, which
+ /// would otherwise silently stall the healing the pass provides
+ /// (freeze-ack re-assertion, yielded-drain re-requests, address
+ /// refresh).
+ pub reconcile_failure_budget: u32,
}
impl Default for RoutingTableConfig {
@@ -47,6 +197,9 @@ impl Default for RoutingTableConfig {
// immediately on the way out).
lease_ttl: 10,
heartbeat_interval: Duration::from_secs(3),
+ participant_stall_threshold: Some(Duration::from_secs(60)),
+ reconcile_interval: Duration::from_secs(5),
+ reconcile_failure_budget: 12,
}
}
}
@@ -160,6 +313,19 @@ impl RoutingTable {
// Run heartbeat and handoff watch concurrently
let mut tasks = tokio::task::JoinSet::new();
+ // Loop progress is measured against a process-local monotonic
+ // epoch, immune to wall-clock steps. The watch loop stamps it
+ // from a ticker arm inside its own select, so the stamp only
+ // advances while the loop is actually free to iterate; the
+ // watchdog task fails the run when the stamp goes stale.
+ let progress_epoch = Instant::now();
+ let last_progress = Arc::new(AtomicU64::new(0));
+ let stamp_interval = self
+ .config
+ .participant_stall_threshold
+ .map(|t| (t / 4).clamp(Duration::from_millis(250), Duration::from_secs(5)))
+ .unwrap_or(Duration::from_secs(5));
+
{
let store = Arc::clone(&self.store);
let interval = self.config.heartbeat_interval;
@@ -169,6 +335,34 @@ impl RoutingTable {
});
}
+ if let Some(threshold) = self.config.participant_stall_threshold {
+ let last_progress = Arc::clone(&last_progress);
+ let router_name = self.config.router_name.clone();
+ let token = cancel.child_token();
+ tasks.spawn(async move {
+ let mut check = tokio::time::interval(stamp_interval);
+ loop {
+ tokio::select! {
+ _ = token.cancelled() => return Ok(()),
+ _ = check.tick() => {
+ let stamped_ms = last_progress.load(Ordering::Relaxed);
+ let now_ms = progress_epoch.elapsed().as_millis() as u64;
+ let stale_ms = now_ms.saturating_sub(stamped_ms);
+ if stale_ms > threshold.as_millis() as u64 {
+ return Err(Error::invalid_state(format!(
+ "handoff watch loop of router {router_name} made no \
+ progress for {stale_ms}ms (threshold \
+ {}ms); failing the run so the router deregisters \
+ and restarts as a healthy participant",
+ threshold.as_millis()
+ )));
+ }
+ }
+ }
+ }
+ });
+ }
+
{
let addresses = Arc::clone(&self.addresses);
let token = cancel.child_token();
@@ -177,12 +371,23 @@ impl RoutingTable {
});
}
+ // Drain lanes get their own token, cancelled in the teardown below:
+ // drains must wind down on any exit path — including an error
+ // teardown, where the caller's token was never cancelled — rather
+ // than outliving the run as orphans forwarding for a deregistered
+ // router.
+ let lanes_cancel = cancel.child_token();
+
{
let store = Arc::clone(&self.store);
let table = Arc::clone(&self.table);
let addresses = Arc::clone(&self.addresses);
let handler = Arc::clone(&handler);
let router_name = self.config.router_name.clone();
+ let lanes = Arc::new(DrainLanes::new(lanes_cancel.clone()));
+ let last_progress = Arc::clone(&last_progress);
+ let reconcile_interval = self.config.reconcile_interval;
+ let reconcile_failure_budget = self.config.reconcile_failure_budget;
let token = cancel.child_token();
tasks.spawn(async move {
Self::watch_handoffs_loop(
@@ -190,9 +395,15 @@ impl RoutingTable {
table,
addresses,
handler,
+ lanes,
router_name,
token,
handoff_stream,
+ last_progress,
+ progress_epoch,
+ stamp_interval,
+ reconcile_interval,
+ reconcile_failure_budget,
)
.await
});
@@ -205,8 +416,10 @@ impl RoutingTable {
}
};
- // Abort and await all remaining tasks for clean shutdown
+ // Abort and await all remaining tasks for clean shutdown, and stop
+ // any in-flight drains at their next batch boundary.
tasks.shutdown().await;
+ lanes_cancel.cancel();
// Deregister so freeze quorums stop counting this router
// immediately. Left to lease expiry, every handoff frozen in the
@@ -357,13 +570,83 @@ impl RoutingTable {
table: Arc<RwLock<HashMap<u32, String>>>,
addresses: Arc<StdRwLock<HashMap<String, String>>>,
handler: Arc<dyn StashHandler>,
+ lanes: Arc<DrainLanes>,
router_name: String,
cancel: CancellationToken,
mut stream: WatchStream,
+ last_progress: Arc<AtomicU64>,
+ progress_epoch: Instant,
+ stamp_interval: Duration,
+ reconcile_interval: Duration,
+ reconcile_failure_budget: u32,
) -> Result<()> {
+ let mut consecutive_reconcile_failures: u32 = 0;
+ // The stamp arm can only run while the loop is free to iterate —
+ // an event handler stuck in an inline await freezes the stamp,
+ // which is exactly what the watchdog listens for.
+ let mut stamp_tick = tokio::time::interval(stamp_interval);
+ // The truth path: periodically re-derive stash, table, and drain
+ // state from a fresh snapshot, repairing whatever the event path
+ // failed to deliver. An arm of this loop on purpose — the routing
+ // table keeps a single writer, and a reconcile that hangs stops
+ // the progress stamp and trips the watchdog.
+ // First pass one full interval out: load_initial has just done
+ // this exact convergence, and an immediate re-pass would only
+ // duplicate handler calls.
+ let mut reconcile_tick = tokio::time::interval_at(
+ tokio::time::Instant::now() + reconcile_interval,
+ reconcile_interval,
+ );
loop {
tokio::select! {
_ = cancel.cancelled() => return Ok(()),
+ _ = stamp_tick.tick() => {
+ last_progress.store(
+ progress_epoch.elapsed().as_millis() as u64,
+ Ordering::Relaxed,
+ );
+ }
+ _ = reconcile_tick.tick() => {
+ // A failed pass is tolerated: the router is exactly
+ // as stale as one tick ago (the watch-driven steady
+ // state), and the next successful pass compensates
+ // fully. Making single failures fatal would let a
+ // brief etcd blip restart every router in the fleet
+ // simultaneously; sustained outage is the lease
+ // keepalive's job. The consecutive budget bounds the
+ // partial-failure mode where reads fail while the
+ // lease stays healthy.
+ match Self::reconcile_pass(
+ &store,
+ &table,
+ &addresses,
+ &handler,
+ &lanes,
+ &router_name,
+ )
+ .await
+ {
+ Ok(()) => consecutive_reconcile_failures = 0,
+ Err(e) => {
+ consecutive_reconcile_failures += 1;
+ metrics::counter!(
+ "personhog_coordination_reconcile_failures_total",
+ "component" => "router"
+ )
+ .increment(1);
+ tracing::warn!(
+ router = %router_name,
+ error = %e,
+ consecutive = consecutive_reconcile_failures,
+ budget = reconcile_failure_budget,
+ "reconcile pass failed; continuing on last-known state"
+ );
+ if consecutive_reconcile_failures >= reconcile_failure_budget {
+ return Err(e);
+ }
+ }
+ }
+ }
msg = stream.message() => {
let resp = msg?.ok_or_else(|| Error::invalid_state("handoff watch stream ended".to_string()))?;
for event in resp.events() {
@@ -374,42 +657,33 @@ impl RoutingTable {
store.as_ref(),
&table,
&addresses,
- handler.as_ref(),
+ &handler,
+ &lanes,
&router_name,
).await?;
}
EventType::Delete => {
- // Handoff cancelled (typically by
- // cleanup_stale_handoffs). Drain any stash
- // back to whoever the routing table still
- // points at — during Freezing/Warming the
- // assignment never moved, so that's the old
- // owner (or an initial target with no prior
- // assignment yet).
+ // A handoff record is never deleted while
+ // non-terminal — cancellation replaces it
+ // with the record that resolves its stashes
+ // — so a deletion has exactly one protocol
+ // meaning: cleanup after Complete, which
+ // requires nothing from the router. If a
+ // stash is somehow still open here (an
+ // out-of-protocol raw deletion), it stays
+ // parked; the reconcile tick derives
+ // disposal from durable state and drains it
+ // to the assignment owner.
let Some(kv) = event.kv() else { continue };
let key = std::str::from_utf8(kv.key()).unwrap_or("");
let Some(partition) = store::extract_partition_from_key(key) else {
continue
};
- let target = table.read().await.get(&partition).cloned();
- match target {
- Some(owner) => {
- tracing::warn!(
- router = %router_name,
- partition,
- owner = %owner,
- "handoff cancelled, draining stash back to current owner"
- );
- handler.drain_stash(partition, &owner).await?;
- }
- None => {
- tracing::warn!(
- router = %router_name,
- partition,
- "handoff cancelled with no current assignment; stash left intact"
- );
- }
- }
+ tracing::debug!(
+ router = %router_name,
+ partition,
+ "handoff record deleted"
+ );
}
}
}
@@ -418,12 +692,129 @@ impl RoutingTable {
}
}
+ /// One level-triggered convergence pass over a fresh snapshot: the
+ /// router's equivalent of the coordinator's reconcile tick and the
+ /// pod's fresh-read convergence. Every action here is idempotent
+ /// against the event path — `begin_stash` no-ops on a live entry,
+ /// freeze acks are id-correlated, table writes are last-writer-wins
+ /// from the authority, and drain requests are absorbed by a running
+ /// same-target lane.
+ ///
+ /// Ordering matters exactly as in `load_initial`: stashes converge
+ /// before tables, so a mid-handoff partition is stashing before it is
+ /// routable. The final rule — no handoff means no stash, so drain
+ /// anything parked to the assignment owner — makes stash disposal a
+ /// property derived from durable state rather than a decision taken
+ /// on any single event, which is what heals a missed Complete, a
+ /// silently dead watch stream, or an out-of-protocol raw deletion.
+ async fn reconcile_pass(
+ store: &PersonhogStore,
+ table: &Arc<RwLock<HashMap<u32, String>>>,
+ addresses: &Arc<StdRwLock<HashMap<String, String>>>,
+ handler: &Arc<dyn StashHandler>,
+ lanes: &Arc<DrainLanes>,
+ router_name: &str,
+ ) -> Result<()> {
+ // Registrations are the address authority; refresh them wholesale
+ // so a pod that re-registered at a new address is dialable even
+ // when the address watch missed the event.
+ let pods = store.list_pods().await?;
+ {
+ let mut addresses = addresses.write().expect("addresses lock poisoned");
+ for pod in pods {
+ if let Some(address) = pod.advertise_address {
+ addresses.insert(pod.pod_name, address);
+ }
+ }
+ }
+
+ let handoffs = store.list_handoffs().await?;
+ let mut constrained: HashSet<u32> = HashSet::new();
+ for handoff in &handoffs {
+ constrained.insert(handoff.partition);
+ match handoff.phase {
+ HandoffPhase::Freezing | HandoffPhase::Draining | HandoffPhase::Warming => {
+ handler
+ .begin_stash(handoff.partition, &handoff.new_owner)
+ .await?;
+ if handoff.phase == HandoffPhase::Freezing {
+ let ack = RouterFreezeAck {
+ 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?;
+ }
+ }
+ HandoffPhase::Complete => {
+ if let Some(address) = &handoff.new_owner_address {
+ addresses
+ .write()
+ .expect("addresses lock poisoned")
+ .entry(handoff.new_owner.clone())
+ .or_insert_with(|| address.clone());
+ }
+ table
+ .write()
+ .await
+ .insert(handoff.partition, handoff.new_owner.clone());
+ // Only request a drain while the stash lifecycle is
+ // open. A settled partition has no entry, and its
+ // finished lane never absorbs (a finished drain may
+ // have yielded with backlog), so an unconditional
+ // request here would respawn a no-op drain every
+ // tick for every quiet partition.
+ if handler.stash_pending(handoff.partition) {
+ lanes.request(
+ Arc::clone(handler),
+ router_name.to_string(),
+ handoff.partition,
+ handoff.new_owner.clone(),
+ );
+ }
+ }
+ }
+ }
+
+ let assignments = store.list_assignments().await?;
+ for assignment in assignments {
+ if constrained.contains(&assignment.partition) {
+ continue;
+ }
+ if let Some(address) = &assignment.advertise_address {
+ addresses
+ .write()
+ .expect("addresses lock poisoned")
+ .entry(assignment.owner.clone())
+ .or_insert_with(|| address.clone());
+ }
+ table
+ .write()
+ .await
+ .insert(assignment.partition, assignment.owner.clone());
+ // Same gate as the Complete arm: "no handoff means no stash"
+ // only demands a drain when something is actually parked or
+ // a window is still open.
+ if handler.stash_pending(assignment.partition) {
+ lanes.request(
+ Arc::clone(handler),
+ router_name.to_string(),
+ assignment.partition,
+ assignment.owner,
+ );
+ }
+ }
+ Ok(())
+ }
+
async fn handle_handoff_put(
event: &etcd_client::Event,
store: &PersonhogStore,
table: &Arc<RwLock<HashMap<u32, String>>>,
addresses: &Arc<StdRwLock<HashMap<String, String>>>,
- handler: &dyn StashHandler,
+ handler: &Arc<dyn StashHandler>,
+ lanes: &Arc<DrainLanes>,
router_name: &str,
) -> Result<()> {
let handoff: HandoffState = match parse_watch_value(event) {
@@ -506,11 +897,107 @@ impl RoutingTable {
new_owner = %handoff.new_owner,
"updated routing table and draining stash to new owner"
);
- handler
- .drain_stash(handoff.partition, &handoff.new_owner)
- .await?;
+ lanes.request(
+ Arc::clone(handler),
+ router_name.to_string(),
+ handoff.partition,
+ handoff.new_owner.clone(),
+ );
}
}
Ok(())
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tokio::sync::mpsc;
+
+ /// A drain that parks until its token is cancelled, reporting when it
+ /// starts and stops — enough to pin the lane contract.
+ struct ParkingDrainHandler {
+ events: mpsc::UnboundedSender<String>,
+ }
+
+ #[async_trait]
+ impl StashHandler for ParkingDrainHandler {
+ async fn begin_stash(&self, _partition: u32, _new_owner: &str) -> Result<()> {
+ Ok(())
+ }
+
+ async fn drain_stash(
+ &self,
+ _partition: u32,
+ target: &str,
+ cancel: CancellationToken,
+ ) -> Result<()> {
+ drop(self.events.send(format!("start:{target}")));
+ cancel.cancelled().await;
+ drop(self.events.send(format!("stop:{target}")));
+ Ok(())
+ }
+ }
+
+ fn parking_lanes() -> (
+ DrainLanes,
+ Arc<dyn StashHandler>,
+ mpsc::UnboundedReceiver<String>,
+ ) {
+ let (tx, rx) = mpsc::unbounded_channel();
+ let lanes = DrainLanes::new(CancellationToken::new());
+ let handler: Arc<dyn StashHandler> = Arc::new(ParkingDrainHandler { events: tx });
+ (lanes, handler, rx)
+ }
+
+ /// Two drains for one partition must never overlap: interleaved
+ /// batches toward different targets would break per-key ordering at
+ /// the leader. A new request cancels the old drain and starts only
+ /// after it has fully stopped.
+ #[tokio::test]
+ async fn a_new_drain_supersedes_and_never_overlaps_the_old() {
+ let (lanes, handler, mut rx) = parking_lanes();
+
+ lanes.request(Arc::clone(&handler), "r".into(), 0, "a".into());
+ assert_eq!(rx.recv().await.unwrap(), "start:a");
+
+ lanes.request(handler, "r".into(), 0, "b".into());
+ assert_eq!(rx.recv().await.unwrap(), "stop:a");
+ assert_eq!(rx.recv().await.unwrap(), "start:b");
+ }
+
+ /// One partition's stalled drain must not delay another partition's —
+ /// the lanes exist precisely so cross-partition work is independent.
+ #[tokio::test]
+ async fn drains_for_different_partitions_run_concurrently() {
+ let (lanes, handler, mut rx) = parking_lanes();
+
+ lanes.request(Arc::clone(&handler), "r".into(), 0, "a".into());
+ assert_eq!(rx.recv().await.unwrap(), "start:a");
+
+ lanes.request(handler, "r".into(), 1, "b".into());
+ assert_eq!(rx.recv().await.unwrap(), "start:b");
+ }
+
+ /// A request toward the target already being drained must not restart
+ /// the drain: the running loop covers all arrivals, and restarting
+ /// would fail its in-flight requests — on every healthy handoff, since
+ /// post-`Complete` cleanup deletion drains back to the same owner the
+ /// table just flipped to.
+ #[tokio::test]
+ async fn a_same_target_request_does_not_supersede_the_running_drain() {
+ let (lanes, handler, mut rx) = parking_lanes();
+
+ lanes.request(Arc::clone(&handler), "r".into(), 0, "a".into());
+ assert_eq!(rx.recv().await.unwrap(), "start:a");
+
+ lanes.request(Arc::clone(&handler), "r".into(), 0, "a".into());
+
+ // The first drain was neither stopped nor restarted: the next
+ // events are its supersession by a different target — with no
+ // duplicate "a" drain in between.
+ lanes.request(handler, "r".into(), 0, "b".into());
+ assert_eq!(rx.recv().await.unwrap(), "stop:a");
+ assert_eq!(rx.recv().await.unwrap(), "start:b");
+ }
+}
diff --git a/rust/personhog-coordination/src/store.rs b/rust/personhog-coordination/src/store.rs
index f4127da4f313..327f0c282aa8 100644
--- a/rust/personhog-coordination/src/store.rs
+++ b/rust/personhog-coordination/src/store.rs
@@ -3,8 +3,9 @@ use etcd_client::{Compare, CompareOp, DeleteOptions, PutOptions, Txn, TxnOp, Wat
use crate::error::{Error, Result};
use crate::types::{
- AssignmentPrecondition, AssignmentStatus, HandoffState, LeaderInfo, PartitionAssignment,
- PodDrainedAck, PodStatus, PodWarmedAck, RegisteredPod, RegisteredRouter, RouterFreezeAck,
+ AssignmentPrecondition, AssignmentStatus, HandoffReplacement, HandoffState, LeaderInfo,
+ PartitionAssignment, PodDrainedAck, PodStatus, PodWarmedAck, RegisteredPod, RegisteredRouter,
+ RouterFreezeAck,
};
/// All etcd key patterns used by the PersonHog store.
@@ -235,6 +236,14 @@ impl PersonhogStore {
Ok(self.inner.list_with_revision(&key).await?)
}
+ /// Like `list_handoffs`, but pairs each record with its key's
+ /// `mod_revision`, so a later replacement can be guarded on the
+ /// record being exactly the one this snapshot read.
+ pub async fn list_handoffs_with_mod_revisions(&self) -> Result<Vec<(HandoffState, i64)>> {
+ let key = self.key(StoreKey::HandoffsPrefix);
+ Ok(self.inner.list_with_mod_revisions(&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?)
@@ -464,14 +473,37 @@ impl PersonhogStore {
/// All-or-nothing on purpose — a plan is one consistent placement
/// computation, and the losing caller replans off the winner's writes
/// rather than applying a half-stale plan.
+ ///
+ /// `replacements` carry cancellations-by-replacement: each swaps the
+ /// record at its partition's key — guarded on the `mod_revision` the
+ /// planner read — for the successor (or reaffirm) record, deleting
+ /// the predecessor's acks in the same transaction. A non-terminal
+ /// handoff record is never deleted; it is only ever replaced by the
+ /// thing that resolves its stashes.
pub async fn create_assignments_and_handoffs(
&self,
assignments: &[PartitionAssignment],
handoffs: &[HandoffState],
preconditions: &[AssignmentPrecondition],
) -> Result<bool> {
- let mut guards: Vec<Compare> = Vec::with_capacity(handoffs.len() + preconditions.len());
- let mut ops: Vec<TxnOp> = Vec::with_capacity(assignments.len() + handoffs.len());
+ self.apply_plan(assignments, handoffs, &[], preconditions)
+ .await
+ }
+
+ /// The full plan-application transaction: creations (absent-guarded)
+ /// plus cancellations-by-replacement (mod_revision-guarded), all or
+ /// nothing.
+ pub async fn apply_plan(
+ &self,
+ assignments: &[PartitionAssignment],
+ handoffs: &[HandoffState],
+ replacements: &[HandoffReplacement],
+ preconditions: &[AssignmentPrecondition],
+ ) -> Result<bool> {
+ let mut guards: Vec<Compare> =
+ Vec::with_capacity(handoffs.len() + replacements.len() + preconditions.len());
+ let mut ops: Vec<TxnOp> =
+ Vec::with_capacity(assignments.len() + handoffs.len() + replacements.len() * 4);
for a in assignments {
let key = self.key(StoreKey::Assignment(a.partition));
@@ -486,6 +518,30 @@ impl PersonhogStore {
guards.push(Compare::create_revision(key.clone(), CompareOp::Equal, 0));
ops.push(TxnOp::put(key, value, None));
}
+ let prefix_delete = || Some(DeleteOptions::new().with_prefix());
+ for r in replacements {
+ let partition = r.handoff.partition;
+ let key = self.key(StoreKey::Handoff(partition));
+ let value = serde_json::to_vec(&r.handoff)?;
+ guards.push(Compare::mod_revision(
+ key.clone(),
+ CompareOp::Equal,
+ r.expected_mod_revision,
+ ));
+ ops.push(TxnOp::delete(
+ self.key(StoreKey::FreezeAcksForPartition(partition)),
+ prefix_delete(),
+ ));
+ ops.push(TxnOp::delete(
+ self.key(StoreKey::DrainedAcksForPartition(partition)),
+ prefix_delete(),
+ ));
+ ops.push(TxnOp::delete(
+ self.key(StoreKey::WarmedAcksForPartition(partition)),
+ prefix_delete(),
+ ));
+ ops.push(TxnOp::put(key, value, None));
+ }
for precondition in preconditions {
match precondition {
AssignmentPrecondition::UnchangedSince {
diff --git a/rust/personhog-coordination/src/types.rs b/rust/personhog-coordination/src/types.rs
index 7e921ef9e428..8e275b076e29 100644
--- a/rust/personhog-coordination/src/types.rs
+++ b/rust/personhog-coordination/src/types.rs
@@ -83,6 +83,18 @@ pub enum AssignmentPrecondition {
Absent { partition: u32 },
}
+/// One cancellation-by-replacement in a plan application: the handoff
+/// record at the partition's key is swapped — guarded on the
+/// `mod_revision` the planner read — for the record that resolves its
+/// stashes (a successor `Freezing` handoff, or a reaffirm `Complete`
+/// toward the live current owner), with the predecessor's acks deleted
+/// in the same transaction.
+#[derive(Debug, Clone)]
+pub struct HandoffReplacement {
+ pub handoff: HandoffState,
+ pub expected_mod_revision: i64,
+}
+
/// Tracks the progress of moving a partition from one writer pod to another,
/// or a fresh initial assignment.
///
diff --git a/rust/personhog-coordination/tests/common/mod.rs b/rust/personhog-coordination/tests/common/mod.rs
index 5fd7a541c1a5..f188396e4983 100644
--- a/rust/personhog-coordination/tests/common/mod.rs
+++ b/rust/personhog-coordination/tests/common/mod.rs
@@ -118,9 +118,11 @@ pub fn start_coordinator_with_deadline(
reconcile_interval: Duration::from_millis(500),
// Callers default this to a day: these tests deliberately
// park handoffs mid-phase to assert what the protocol does
- // with them, and a live deadline would delete the state under
- // test. The cancellation test passes a short one explicitly.
+ // with them, and a live deadline would replace the state
+ // under test. The cancellation test passes a short one
+ // explicitly.
handoff_deadline,
+ warming_deadline: Duration::from_secs(86_400),
},
strategy,
None,
@@ -163,6 +165,9 @@ pub fn start_pod_with_address(
lease_ttl,
heartbeat_interval: Duration::from_secs(heartbeat_secs),
advertise_address,
+ // Parked: event-driven tests assert exact handler-call
+ // sequences a live reconcile pass would duplicate.
+ reconcile_interval: Duration::from_secs(86_400),
..Default::default()
},
Arc::new(handler),
@@ -192,6 +197,9 @@ pub fn start_pod_blocking(
pod_name: name.to_string(),
lease_ttl,
heartbeat_interval: Duration::from_secs(heartbeat_secs),
+ // Parked: event-driven tests assert exact handler-call
+ // sequences a live reconcile pass would duplicate.
+ reconcile_interval: Duration::from_secs(86_400),
..Default::default()
},
Arc::new(handler),
@@ -235,6 +243,9 @@ pub fn start_pod_slow(
store,
PodConfig {
pod_name: name.to_string(),
+ // Parked: event-driven tests assert exact handler-call
+ // sequences a live reconcile pass would duplicate.
+ reconcile_interval: Duration::from_secs(86_400),
..Default::default()
},
Arc::new(handler),
@@ -277,6 +288,12 @@ pub fn start_router_with_lease_ttl(
router_name: name.to_string(),
lease_ttl,
heartbeat_interval: Duration::from_secs(heartbeat_secs),
+ // Parked: event-driven tests assert exact handler-call
+ // sequences, which a live reconcile pass would re-assert
+ // nondeterministically. Reconcile-specific tests pass a
+ // short interval explicitly.
+ reconcile_interval: Duration::from_secs(86_400),
+ ..RoutingTableConfig::default()
},
);
let table = router.table_handle();
@@ -490,7 +507,12 @@ impl StashHandler for MockCutoverHandler {
Ok(())
}
- async fn drain_stash(&self, partition: u32, target: &str) -> Result<()> {
+ async fn drain_stash(
+ &self,
+ partition: u32,
+ target: &str,
+ _cancel: CancellationToken,
+ ) -> Result<()> {
self.events.lock().await.push(CutoverEvent::StashDrained {
partition,
target: target.to_string(),
diff --git a/rust/personhog-coordination/tests/integration.rs b/rust/personhog-coordination/tests/integration.rs
index 2e96ffd2ee0e..817dd07eda77 100644
--- a/rust/personhog-coordination/tests/integration.rs
+++ b/rust/personhog-coordination/tests/integration.rs
@@ -1372,17 +1372,17 @@ async fn old_owner_retains_partition_through_warming() {
cancel.cancel();
}
-/// When the routing table sees a handoff `Delete` event (because
-/// cleanup_stale_handoffs deleted a stuck handoff), the router must drain
-/// its stash back to the current routing-table owner. This proves the
-/// `EventType::Delete` branch of `watch_handoffs_loop` works.
+/// A handoff toward a dead new owner is cancelled by the coordinator's
+/// own replacement path: the planner reaffirms the partition to its live
+/// current owner, and the router resolves the stash through its ordinary
+/// Complete handling — draining home.
///
/// Verified by manually injecting and deleting a handoff via the store —
/// avoids the flakiness of relying on a blocking pod's lease to expire,
/// which is brittle because the pod's cancellation can't preempt a stuck
/// `warm_partition`.
#[tokio::test]
-async fn handoff_delete_drains_stash_to_current_owner() {
+async fn a_dead_new_owner_handoff_is_reaffirmed_to_the_current_owner() {
use personhog_coordination::types::{HandoffPhase, HandoffState};
let store = test_store("delete-drains-stash").await;
@@ -1452,14 +1452,16 @@ async fn handoff_delete_drains_stash_to_current_owner() {
.filter(|e| matches!(e, common::CutoverEvent::StashDrained { .. }))
.count();
- // Now delete the handoff to simulate cleanup_stale_handoffs firing.
- store.delete_handoff(0).await.unwrap();
+ // No deletion is injected: the coordinator's own reconcile tick
+ // detects the dead new owner, wakes the planner, and the planner
+ // cancels the handoff by replacement — a reaffirm Complete toward
+ // the live current owner, since the placement needs no move.
// Wait for the drain *count* to grow past `drains_before`. An
// event-existence check would race the bootstrap drains: those
// already record `StashDrained{partition: 0, target: writer-0}`,
// so any "does an event matching this exist" predicate would
- // return true immediately without waiting for the Delete-driven
+ // return true immediately without waiting for the reaffirm-driven
// drain to fire.
let check_router = Arc::clone(&router.events);
wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
@@ -1817,7 +1819,7 @@ async fn late_joining_router_during_warming_begins_stash() {
/// (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`.
+/// by cancellation.
#[tokio::test]
async fn dead_old_owner_in_freezing_advances_to_completion() {
use personhog_coordination::types::{HandoffPhase, HandoffState};
@@ -1937,7 +1939,7 @@ async fn late_joining_router_during_freezing_acks_and_stashes() {
/// the post-freeze state — the router has already begun stashing and the
/// freeze quorum has been collected.
#[tokio::test]
-async fn handoff_delete_during_warming_drains_to_current_owner() {
+async fn a_dead_new_owner_handoff_in_warming_is_reaffirmed() {
use personhog_coordination::types::{HandoffPhase, HandoffState};
let store = test_store("delete-during-warming").await;
@@ -2007,10 +2009,10 @@ async fn handoff_delete_during_warming_drains_to_current_owner() {
.filter(|e| matches!(e, common::CutoverEvent::StashDrained { .. }))
.count();
- // Delete the Warming handoff. The Delete branch must drain the stash
- // back to the current routing-table owner (writer-0), independent of
- // the phase the handoff was in when deleted.
- store.delete_handoff(0).await.unwrap();
+ // No deletion is injected: the coordinator detects the dead new
+ // owner and cancels by replacement — a reaffirm Complete toward the
+ // current owner (writer-0), independent of the phase the doomed
+ // handoff was in.
let check_router = Arc::clone(&router.events);
wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
@@ -2224,9 +2226,9 @@ async fn draining_old_owner_blocks_phase_advance() {
cancel.cancel();
}
-/// `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
+/// The dead-new-owner cancellation trigger judges only the new owner; the
+/// old owner's state — Draining, or even fully deregistered — must never
+/// cancel a handoff. 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.
@@ -2831,7 +2833,7 @@ async fn late_joining_router_during_draining_begins_stash_no_ack() {
/// `watch_handoffs_loop` is phase-agnostic, so this exercises the same
/// code path; the test confirms the recovery is uniform across phases.
#[tokio::test]
-async fn handoff_delete_during_draining_drains_to_current_owner() {
+async fn a_dead_new_owner_handoff_in_draining_is_reaffirmed() {
use personhog_coordination::types::{HandoffPhase, HandoffState};
let store = test_store("delete-during-draining").await;
@@ -2899,10 +2901,10 @@ async fn handoff_delete_during_draining_drains_to_current_owner() {
.filter(|e| matches!(e, common::CutoverEvent::StashDrained { .. }))
.count();
- // Delete the Draining handoff. The Delete branch must drain the
- // stash back to the current routing-table owner (writer-0),
- // independent of the phase the handoff was in when deleted.
- store.delete_handoff(0).await.unwrap();
+ // No deletion is injected: the coordinator detects the dead new
+ // owner and cancels by replacement — a reaffirm Complete toward the
+ // current owner (writer-0), independent of the phase the doomed
+ // handoff was in.
// Wait for the drain *count* to grow past `drains_before`.
// Bootstrap drains for partition 0 already exist (each initial
diff --git a/rust/personhog-coordination/tests/k3s_integration.rs b/rust/personhog-coordination/tests/k3s_integration.rs
index dd40c0fcb689..87ef59359d4c 100644
--- a/rust/personhog-coordination/tests/k3s_integration.rs
+++ b/rust/personhog-coordination/tests/k3s_integration.rs
@@ -679,6 +679,8 @@ async fn statefulset_rollout_pod_skips_drain() {
lease_ttl: 10,
heartbeat_interval: Duration::from_secs(3),
drain_timeout: Duration::from_secs(30),
+ reconcile_interval: Duration::from_secs(86_400),
+ reconcile_failure_budget: 12,
advertise_address: None,
};
let (_pod_events, pod_handle) = start_pod_k8s(
diff --git a/rust/personhog-coordination/tests/protocol_hardening.rs b/rust/personhog-coordination/tests/protocol_hardening.rs
index f5cecd50005c..2cf74e85e9f4 100644
--- a/rust/personhog-coordination/tests/protocol_hardening.rs
+++ b/rust/personhog-coordination/tests/protocol_hardening.rs
@@ -21,7 +21,8 @@ use async_trait::async_trait;
use common::{
revoke_lease_of_key, start_coordinator, start_coordinator_named, 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,
+ wait_for_condition, CutoverEvent, HandoffEvent, MockCutoverHandler, POLL_INTERVAL,
+ WAIT_TIMEOUT,
};
use personhog_coordination::error::Result;
use personhog_coordination::routing_table::{RoutingTable, RoutingTableConfig, StashHandler};
@@ -215,10 +216,10 @@ async fn coordinator_abdicates_and_recampaigns_when_election_lease_revoked() {
// ============================================================
//
// 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
+// handoff is cancelled (the coordinator replaces the record — e.g. the
+// new owner died mid-warm and a reaffirm resolves it), the pod re-derives
+// its state from what etcd now says: if the record names it, it resumes
+// serving (routers drain their stashes back to it); if nothing assigns it, it
// releases whatever half-acquired state it holds.
/// A handoff deleted mid-flight (after this pod drained as old owner)
@@ -775,10 +776,10 @@ async fn legacy_ack_without_handoff_id_does_not_satisfy_quorum() {
//
// 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
+// as vacuously drained. Cancelling such handoffs would be a second,
+// competing mechanism for the same state — racing the advance path and
+// tearing down a healthy in-flight warm so the plan could recreate it
+// from scratch. The planner's cancellation trigger is only the handoff that
// truly cannot proceed: a dead NEW owner, whose WarmedAck will never
// arrive.
@@ -1109,7 +1110,7 @@ async fn freezing_handoff_advances_when_unacked_router_departs() {
// ============================================================
//
// A pod that crash-restarts quickly (within its lease TTL) keeps its etcd
-// registration, so `cleanup_stale_handoffs` never fires and no new Put
+// registration, so no dead-new-owner cancellation 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.
@@ -1308,7 +1309,12 @@ impl StashHandler for StashOrderProbe {
Ok(())
}
- async fn drain_stash(&self, _partition: u32, _target: &str) -> Result<()> {
+ async fn drain_stash(
+ &self,
+ _partition: u32,
+ _target: &str,
+ _cancel: CancellationToken,
+ ) -> Result<()> {
Ok(())
}
}
@@ -1354,6 +1360,8 @@ async fn late_joining_router_stashes_before_populating_table() {
router_name: "late-router".to_string(),
lease_ttl: 10,
heartbeat_interval: Duration::from_secs(3),
+ reconcile_interval: Duration::from_secs(86_400),
+ ..RoutingTableConfig::default()
},
);
let observed = Arc::new(Mutex::new(Vec::new()));
@@ -1378,3 +1386,770 @@ async fn late_joining_router_stashes_before_populating_table() {
cancel.cancel();
}
+
+// ============================================================
+// Cancellation disposal: drain back only to a live owner
+// ============================================================
+
+/// Shared fixture for the cancellation-disposal tests: an assignment for
+/// partition 0 owned by `pod-old`, an in-flight Freezing handoff toward
+/// `pod-new`, and a running routing table with a recording stash handler.
+/// Returns the recorded events and the shutdown token.
+async fn start_router_with_frozen_handoff(
+ store: &Arc<PersonhogStore>,
+ router_name: &str,
+) -> (Arc<Mutex<Vec<CutoverEvent>>>, CancellationToken) {
+ assert!(store
+ .create_assignments_and_handoffs(
+ &[PartitionAssignment {
+ partition: 0,
+ owner: "pod-old".to_string(),
+ status: AssignmentStatus::Active,
+ advertise_address: None,
+ }],
+ &[],
+ &[],
+ )
+ .await
+ .expect("write assignment"));
+ put_handoff(store, 0, Some("pod-old"), "pod-new", HandoffPhase::Freezing).await;
+
+ let router = RoutingTable::new(
+ Arc::clone(store),
+ RoutingTableConfig {
+ router_name: router_name.to_string(),
+ reconcile_interval: Duration::from_secs(86_400),
+ ..RoutingTableConfig::default()
+ },
+ );
+ let (handler, events) = MockCutoverHandler::new();
+ let cancel = CancellationToken::new();
+ let token = cancel.child_token();
+ tokio::spawn(async move { router.run(token, Arc::new(handler)).await });
+
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let events = Arc::clone(&events);
+ async move { !events.lock().await.is_empty() }
+ })
+ .await;
+
+ (events, cancel)
+}
+
+/// A raw deletion of a non-terminal handoff is out-of-protocol under
+/// cancellation-by-replacement, and the router treats it as inert: no
+/// drain fires toward anyone. The stash stays parked until the record
+/// that resolves it arrives — here the successor's Complete, which
+/// drains it to the pod that actually won ownership.
+#[tokio::test]
+async fn a_raw_deletion_is_inert_and_the_successor_resolves_the_stash() {
+ let store = test_store("cancel-dead-owner").await;
+
+ // `pod-old` is never registered: it is dead.
+ let (events, cancel) = start_router_with_frozen_handoff(&store, "cdo-router").await;
+
+ store.delete_handoff(0).await.expect("cancel handoff");
+
+ // The successor handoff completes toward a different pod; its drain
+ // is the next stash event. Waiting for it (rather than a negative
+ // wait) also proves no drain-back squeezed in before it: events are
+ // recorded in order and asserted exactly below.
+ put_handoff(
+ &store,
+ 0,
+ Some("pod-old"),
+ "pod-new-2",
+ HandoffPhase::Complete,
+ )
+ .await;
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let events = Arc::clone(&events);
+ async move {
+ events.lock().await.contains(&CutoverEvent::StashDrained {
+ partition: 0,
+ target: "pod-new-2".to_string(),
+ })
+ }
+ })
+ .await;
+
+ let recorded = events.lock().await.clone();
+ assert_eq!(
+ recorded,
+ vec![
+ CutoverEvent::StashBegan {
+ partition: 0,
+ new_owner: "pod-new".to_string(),
+ },
+ CutoverEvent::StashDrained {
+ partition: 0,
+ target: "pod-new-2".to_string(),
+ },
+ ],
+ "stash must not drain toward the dead owner"
+ );
+
+ cancel.cancel();
+}
+
+/// Records drain starts like `MockCutoverHandler`, then parks forever —
+/// ignoring even its cancellation token. The worst-case drain.
+struct BlockedDrainHandler {
+ events: Arc<Mutex<Vec<CutoverEvent>>>,
+}
+
+#[async_trait]
+impl StashHandler for BlockedDrainHandler {
+ async fn begin_stash(&self, partition: u32, new_owner: &str) -> Result<()> {
+ self.events.lock().await.push(CutoverEvent::StashBegan {
+ partition,
+ new_owner: new_owner.to_string(),
+ });
+ Ok(())
+ }
+
+ async fn drain_stash(
+ &self,
+ partition: u32,
+ target: &str,
+ _cancel: CancellationToken,
+ ) -> Result<()> {
+ self.events.lock().await.push(CutoverEvent::StashDrained {
+ partition,
+ target: target.to_string(),
+ });
+ std::future::pending::<Result<()>>().await
+ }
+}
+
+/// A drain's duration is data-plane work — queue depth, arrival rate,
+/// target health — so even a drain that never finishes must not stall
+/// the watch loop: freeze acks are on the critical path of every handoff
+/// in the cluster, and a router that stops acking wedges them all.
+#[tokio::test]
+async fn a_blocked_drain_does_not_stall_freeze_acks_for_other_partitions() {
+ let store = test_store("blocked-drain").await;
+
+ // Partition 0's owner is live and registered, so the cancellation
+ // below drains back to it — and parks forever in this handler.
+ let lease = store.grant_lease(60).await.expect("lease");
+ store
+ .register_pod(
+ &RegisteredPod {
+ pod_name: "pod-old".to_string(),
+ generation: String::new(),
+ status: PodStatus::Ready,
+ registered_at: 0,
+ last_heartbeat: 0,
+ controller: None,
+ advertise_address: None,
+ },
+ lease,
+ )
+ .await
+ .expect("register pod-old");
+ assert!(store
+ .create_assignments_and_handoffs(
+ &[PartitionAssignment {
+ partition: 0,
+ owner: "pod-old".to_string(),
+ status: AssignmentStatus::Active,
+ advertise_address: None,
+ }],
+ &[],
+ &[],
+ )
+ .await
+ .expect("write assignment"));
+ put_handoff(
+ &store,
+ 0,
+ Some("pod-old"),
+ "pod-new",
+ HandoffPhase::Freezing,
+ )
+ .await;
+
+ let router = RoutingTable::new(
+ Arc::clone(&store),
+ RoutingTableConfig {
+ router_name: "bd-router".to_string(),
+ reconcile_interval: Duration::from_secs(86_400),
+ ..RoutingTableConfig::default()
+ },
+ );
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let handler = BlockedDrainHandler {
+ events: Arc::clone(&events),
+ };
+ let cancel = CancellationToken::new();
+ let token = cancel.child_token();
+ tokio::spawn(async move { router.run(token, Arc::new(handler)).await });
+
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let events = Arc::clone(&events);
+ async move { !events.lock().await.is_empty() }
+ })
+ .await;
+
+ // Replace the handoff with a reaffirm toward the live owner and
+ // wait until the resulting drain has started (and parked).
+ put_handoff(&store, 0, None, "pod-old", HandoffPhase::Complete).await;
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let events = Arc::clone(&events);
+ async move {
+ events.lock().await.contains(&CutoverEvent::StashDrained {
+ partition: 0,
+ target: "pod-old".to_string(),
+ })
+ }
+ })
+ .await;
+
+ // A Freezing handoff for another partition must still get this
+ // router's freeze ack.
+ put_handoff(&store, 1, None, "pod-new", HandoffPhase::Freezing).await;
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let store = Arc::clone(&store);
+ async move {
+ store
+ .list_freeze_acks(1)
+ .await
+ .expect("list acks")
+ .iter()
+ .any(|ack| ack.router_name == "bd-router")
+ }
+ })
+ .await;
+
+ cancel.cancel();
+}
+
+/// Passes partition 0 through and parks forever on any other partition —
+/// pins the block inside the watch loop (partition 1 only ever arrives
+/// through it, never through startup catch-up, once partition 0's ack
+/// proves the initial snapshot has been taken).
+struct PartitionOneParker;
+
+#[async_trait]
+impl StashHandler for PartitionOneParker {
+ async fn begin_stash(&self, partition: u32, _new_owner: &str) -> Result<()> {
+ if partition == 0 {
+ return Ok(());
+ }
+ std::future::pending::<Result<()>>().await
+ }
+
+ async fn drain_stash(
+ &self,
+ _partition: u32,
+ _target: &str,
+ _cancel: CancellationToken,
+ ) -> Result<()> {
+ Ok(())
+ }
+}
+
+/// A router whose watch loop stalls stays registered — its lease
+/// keepalive is a separate, healthy task — and is counted in every
+/// freeze quorum while never acking. The watchdog must notice the
+/// missing progress stamps, fail the run, and deregister the router so
+/// quorums stop counting it.
+#[tokio::test]
+async fn a_stalled_watch_loop_trips_the_watchdog_and_deregisters() {
+ let store = test_store("stall-watchdog").await;
+
+ let router = RoutingTable::new(
+ Arc::clone(&store),
+ RoutingTableConfig {
+ router_name: "wd-router".to_string(),
+ participant_stall_threshold: Some(Duration::from_secs(1)),
+ reconcile_interval: Duration::from_secs(86_400),
+ ..RoutingTableConfig::default()
+ },
+ );
+ let cancel = CancellationToken::new();
+ let token = cancel.child_token();
+ let run = tokio::spawn(async move { router.run(token, Arc::new(PartitionOneParker)).await });
+
+ // Partition 0's ack proves the router is up and past its startup
+ // catch-up; partition 1's handoff then arrives via the watch loop
+ // and parks it.
+ put_handoff(&store, 0, None, "pod-new", HandoffPhase::Freezing).await;
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let store = Arc::clone(&store);
+ async move {
+ store
+ .list_freeze_acks(0)
+ .await
+ .expect("list acks")
+ .iter()
+ .any(|ack| ack.router_name == "wd-router")
+ }
+ })
+ .await;
+ put_handoff(&store, 1, None, "pod-new", HandoffPhase::Freezing).await;
+
+ let result = tokio::time::timeout(WAIT_TIMEOUT, run)
+ .await
+ .expect("watchdog should fail the run before the timeout")
+ .expect("run task must not panic");
+ assert!(
+ result.is_err(),
+ "a stalled watch loop must fail the run, not linger as a zombie participant"
+ );
+
+ // Deregistered on the way down: freeze quorums stop counting it.
+ let routers = store.list_routers().await.expect("list routers");
+ assert!(
+ !routers.iter().any(|r| r.router_name == "wd-router"),
+ "the failed router must deregister"
+ );
+
+ cancel.cancel();
+}
+
+/// The reaffirm shape: cancelling a handoff whose current owner is
+/// alive replaces the record with a Complete toward that owner
+/// (`old_owner: None` — naming the owner on both sides would derive
+/// Released at the pod). The router resolves it through its ordinary
+/// Complete handling: parked requests drain straight home.
+#[tokio::test]
+async fn a_reaffirm_resolves_the_stash_back_to_the_owner() {
+ let store = test_store("cancel-live-owner").await;
+
+ let lease = store.grant_lease(60).await.expect("lease");
+ store
+ .register_pod(
+ &RegisteredPod {
+ pod_name: "pod-old".to_string(),
+ generation: String::new(),
+ status: PodStatus::Ready,
+ registered_at: 0,
+ last_heartbeat: 0,
+ controller: None,
+ advertise_address: None,
+ },
+ lease,
+ )
+ .await
+ .expect("register pod-old");
+
+ let (events, cancel) = start_router_with_frozen_handoff(&store, "clo-router").await;
+
+ // The coordinator's replacement, written directly: a reaffirm
+ // Complete toward the live current owner.
+ put_handoff(&store, 0, None, "pod-old", HandoffPhase::Complete).await;
+
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let events = Arc::clone(&events);
+ async move {
+ events.lock().await.contains(&CutoverEvent::StashDrained {
+ partition: 0,
+ target: "pod-old".to_string(),
+ })
+ }
+ })
+ .await;
+
+ cancel.cancel();
+}
+
+/// Build a router with a fast reconcile pass, over an assignment for
+/// partition 0 owned by `pod-old` and an in-flight Freezing handoff.
+async fn start_reconciling_router(
+ store: &Arc<PersonhogStore>,
+ router_name: &str,
+) -> (Arc<Mutex<Vec<CutoverEvent>>>, CancellationToken) {
+ assert!(store
+ .create_assignments_and_handoffs(
+ &[PartitionAssignment {
+ partition: 0,
+ owner: "pod-old".to_string(),
+ status: AssignmentStatus::Active,
+ advertise_address: None,
+ }],
+ &[],
+ &[],
+ )
+ .await
+ .expect("write assignment"));
+ put_handoff(store, 0, Some("pod-old"), "pod-new", HandoffPhase::Freezing).await;
+
+ let router = RoutingTable::new(
+ Arc::clone(store),
+ RoutingTableConfig {
+ router_name: router_name.to_string(),
+ reconcile_interval: Duration::from_millis(200),
+ ..RoutingTableConfig::default()
+ },
+ );
+ let (handler, events) = MockCutoverHandler::new();
+ let cancel = CancellationToken::new();
+ let token = cancel.child_token();
+ tokio::spawn(async move { router.run(token, Arc::new(handler)).await });
+
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let events = Arc::clone(&events);
+ async move { !events.lock().await.is_empty() }
+ })
+ .await;
+
+ (events, cancel)
+}
+
+/// The reconcile pass derives stash disposal from durable state: after
+/// an out-of-protocol raw deletion leaves a stash parked (the Delete
+/// event itself is inert), the next pass observes a partition with an
+/// assignment and no handoff and drains the stash to the assignment
+/// owner. This is the healing no event-driven path can provide.
+#[tokio::test]
+async fn the_reconcile_pass_heals_an_out_of_protocol_deletion() {
+ let store = test_store("reconcile-heals-deletion").await;
+ let (events, cancel) = start_reconciling_router(&store, "rhd-router").await;
+
+ store.delete_handoff(0).await.expect("raw delete");
+
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let events = Arc::clone(&events);
+ async move {
+ events.lock().await.contains(&CutoverEvent::StashDrained {
+ partition: 0,
+ target: "pod-old".to_string(),
+ })
+ }
+ })
+ .await;
+
+ cancel.cancel();
+}
+
+/// The reconcile pass re-derives freeze acks from the snapshot, so an
+/// ack lost out-of-protocol — or a Freezing event lost to a dead watch
+/// stream — is repaired on the next pass instead of wedging the quorum
+/// until the deadline.
+#[tokio::test]
+async fn the_reconcile_pass_reasserts_freeze_acks() {
+ let (store, prefix) = test_store_with_prefix("reconcile-reasserts-acks").await;
+ let (_events, cancel) = start_reconciling_router(&store, "rra-router").await;
+
+ let ack_present = |store: Arc<PersonhogStore>| async move {
+ store
+ .list_freeze_acks(0)
+ .await
+ .expect("list acks")
+ .iter()
+ .any(|a| a.router_name == "rra-router")
+ };
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ ack_present(Arc::clone(&store))
+ })
+ .await;
+
+ let mut raw = etcd_client::Client::connect(["http://localhost:2379"], None)
+ .await
+ .expect("raw client");
+ raw.delete(format!("{prefix}freeze_acks/0/rra-router"), None)
+ .await
+ .expect("delete ack");
+
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ ack_present(Arc::clone(&store))
+ })
+ .await;
+
+ cancel.cancel();
+}
+
+/// A cutover handler whose `begin_stash` fails while the flag is set —
+/// the injection point for reconcile-pass failures, since the pass calls
+/// it for every non-terminal handoff before writing the freeze ack.
+struct FlakyCutoverHandler {
+ events: Arc<Mutex<Vec<CutoverEvent>>>,
+ fail: Arc<std::sync::atomic::AtomicBool>,
+}
+
+#[async_trait]
+impl StashHandler for FlakyCutoverHandler {
+ async fn begin_stash(&self, partition: u32, new_owner: &str) -> Result<()> {
+ if self.fail.load(std::sync::atomic::Ordering::SeqCst) {
+ return Err(personhog_coordination::error::Error::invalid_state(
+ "injected begin_stash failure".to_string(),
+ ));
+ }
+ self.events.lock().await.push(CutoverEvent::StashBegan {
+ partition,
+ new_owner: new_owner.to_string(),
+ });
+ Ok(())
+ }
+
+ async fn drain_stash(
+ &self,
+ partition: u32,
+ target: &str,
+ _cancel: CancellationToken,
+ ) -> Result<()> {
+ self.events.lock().await.push(CutoverEvent::StashDrained {
+ partition,
+ target: target.to_string(),
+ });
+ Ok(())
+ }
+}
+
+/// Start a router over the standard fixture (assignment for partition 0,
+/// Freezing handoff) with a failure-injectable handler and the given
+/// reconcile failure budget.
+async fn start_flaky_router(
+ store: &Arc<PersonhogStore>,
+ router_name: &str,
+ budget: u32,
+) -> (Arc<std::sync::atomic::AtomicBool>, CancellationToken) {
+ assert!(store
+ .create_assignments_and_handoffs(
+ &[PartitionAssignment {
+ partition: 0,
+ owner: "pod-old".to_string(),
+ status: AssignmentStatus::Active,
+ advertise_address: None,
+ }],
+ &[],
+ &[],
+ )
+ .await
+ .expect("write assignment"));
+ put_handoff(store, 0, Some("pod-old"), "pod-new", HandoffPhase::Freezing).await;
+
+ let router = RoutingTable::new(
+ Arc::clone(store),
+ RoutingTableConfig {
+ router_name: router_name.to_string(),
+ reconcile_interval: Duration::from_millis(200),
+ reconcile_failure_budget: budget,
+ ..RoutingTableConfig::default()
+ },
+ );
+ let fail = Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let handler = FlakyCutoverHandler {
+ events: Arc::new(Mutex::new(Vec::new())),
+ fail: Arc::clone(&fail),
+ };
+ let cancel = CancellationToken::new();
+ let token = cancel.child_token();
+ tokio::spawn(async move { router.run(token, Arc::new(handler)).await });
+ (fail, cancel)
+}
+
+/// Reconcile-pass failures within the budget must not kill the run: the
+/// router stays registered while passes fail, and the first successful
+/// pass afterward heals what went unrepaired in the meantime (here, a
+/// freeze ack deleted out-of-protocol). Without tolerance, a brief etcd
+/// blip observed by the 5-second tick would restart every router in the
+/// fleet simultaneously.
+#[tokio::test]
+async fn reconcile_failures_within_budget_are_tolerated_and_heal() {
+ let (store, prefix) = test_store_with_prefix("reconcile-tolerates-failures").await;
+ let (fail, cancel) = start_flaky_router(&store, "rtf-router", 12).await;
+
+ let ack_present = |store: Arc<PersonhogStore>| async move {
+ store
+ .list_freeze_acks(0)
+ .await
+ .expect("list acks")
+ .iter()
+ .any(|a| a.router_name == "rtf-router")
+ };
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ ack_present(Arc::clone(&store))
+ })
+ .await;
+
+ // Break the handler and delete the ack out-of-protocol. Reconcile is
+ // the only healer (no new events arrive), and its passes now fail
+ // before reaching the ack write, so the ack must stay absent while
+ // the run survives the failures.
+ fail.store(true, std::sync::atomic::Ordering::SeqCst);
+ let mut raw = etcd_client::Client::connect(["http://localhost:2379"], None)
+ .await
+ .expect("raw client");
+ raw.delete(format!("{prefix}freeze_acks/0/rtf-router"), None)
+ .await
+ .expect("delete ack");
+
+ // Observe at least four failed ticks' worth of time.
+ tokio::time::sleep(Duration::from_millis(900)).await;
+ assert!(
+ !ack_present(Arc::clone(&store)).await,
+ "failing passes must not have healed the ack"
+ );
+ let registered = store
+ .list_routers()
+ .await
+ .expect("list routers")
+ .iter()
+ .any(|r| r.router_name == "rtf-router");
+ assert!(
+ registered,
+ "the run must survive reconcile failures within the budget"
+ );
+
+ // Recovery: the next successful pass re-asserts the ack.
+ fail.store(false, std::sync::atomic::Ordering::SeqCst);
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ ack_present(Arc::clone(&store))
+ })
+ .await;
+
+ cancel.cancel();
+}
+
+/// Past the consecutive-failure budget the run must fail — the escape
+/// hatch for the partial mode where snapshot reads fail while the lease
+/// stays healthy, which unbounded tolerance would hide forever. Failing
+/// the run deregisters the router so it restarts as a healthy
+/// participant.
+#[tokio::test]
+async fn reconcile_failures_past_the_budget_fail_the_run() {
+ let store = test_store("reconcile-budget-exhaustion").await;
+ let (fail, cancel) = start_flaky_router(&store, "rbe-router", 3).await;
+
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let store = Arc::clone(&store);
+ async move {
+ store
+ .list_routers()
+ .await
+ .expect("list routers")
+ .iter()
+ .any(|r| r.router_name == "rbe-router")
+ }
+ })
+ .await;
+
+ fail.store(true, std::sync::atomic::Ordering::SeqCst);
+
+ // Three failed passes exhaust the budget; the run's teardown
+ // deregisters the router.
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let store = Arc::clone(&store);
+ async move {
+ !store
+ .list_routers()
+ .await
+ .expect("list routers")
+ .iter()
+ .any(|r| r.router_name == "rbe-router")
+ }
+ })
+ .await;
+
+ cancel.cancel();
+}
+
+/// A cutover handler whose stash has fully settled: `stash_pending`
+/// reports no entry, the way the router does once a drain has evicted
+/// the partition from its stash table.
+struct SettledCutoverHandler {
+ events: Arc<Mutex<Vec<CutoverEvent>>>,
+}
+
+#[async_trait]
+impl StashHandler for SettledCutoverHandler {
+ async fn begin_stash(&self, partition: u32, new_owner: &str) -> Result<()> {
+ self.events.lock().await.push(CutoverEvent::StashBegan {
+ partition,
+ new_owner: new_owner.to_string(),
+ });
+ Ok(())
+ }
+
+ async fn drain_stash(
+ &self,
+ partition: u32,
+ target: &str,
+ _cancel: CancellationToken,
+ ) -> Result<()> {
+ self.events.lock().await.push(CutoverEvent::StashDrained {
+ partition,
+ target: target.to_string(),
+ });
+ Ok(())
+ }
+
+ fn stash_pending(&self, _partition: u32) -> bool {
+ false
+ }
+}
+
+/// A settled partition must not have drains respawned by every reconcile
+/// tick: its finished lane can never absorb (a finished drain may have
+/// yielded with backlog), so without the `stash_pending` gate the pass
+/// would spawn a fresh no-op drain for every quiet assigned partition,
+/// every tick. The Freezing handoff on partition 1 acts as the pass
+/// counter — `begin_stash` is re-asserted unconditionally each pass — so
+/// the assertion is provably non-vacuous across multiple passes.
+#[tokio::test]
+async fn the_reconcile_pass_skips_drains_for_settled_partitions() {
+ let store = test_store("reconcile-skips-settled").await;
+ assert!(store
+ .create_assignments_and_handoffs(
+ &[PartitionAssignment {
+ partition: 0,
+ owner: "pod-old".to_string(),
+ status: AssignmentStatus::Active,
+ advertise_address: None,
+ }],
+ &[],
+ &[],
+ )
+ .await
+ .expect("write assignment"));
+ put_handoff(&store, 1, None, "keeper-pod", HandoffPhase::Freezing).await;
+
+ let router = RoutingTable::new(
+ Arc::clone(&store),
+ RoutingTableConfig {
+ router_name: "rss-router".to_string(),
+ reconcile_interval: Duration::from_millis(200),
+ ..RoutingTableConfig::default()
+ },
+ );
+ let events = Arc::new(Mutex::new(Vec::new()));
+ let handler = SettledCutoverHandler {
+ events: Arc::clone(&events),
+ };
+ let cancel = CancellationToken::new();
+ let token = cancel.child_token();
+ tokio::spawn(async move { router.run(token, Arc::new(handler)).await });
+
+ // Wait until partition 1's begin_stash has been asserted at least
+ // three times — proof that multiple reconcile passes have evaluated
+ // partition 0's bare assignment.
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
+ let events = Arc::clone(&events);
+ async move {
+ events
+ .lock()
+ .await
+ .iter()
+ .filter(|e| matches!(e, CutoverEvent::StashBegan { partition: 1, .. }))
+ .count()
+ >= 3
+ }
+ })
+ .await;
+
+ let drained = events
+ .lock()
+ .await
+ .iter()
+ .filter(|e| matches!(e, CutoverEvent::StashDrained { partition: 0, .. }))
+ .count();
+ assert_eq!(
+ drained, 0,
+ "a settled partition must not have drains respawned by reconcile ticks"
+ );
+
+ cancel.cancel();
+}
diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rs
index e233c3ee9dec..60fc421e4c0c 100644
--- a/rust/personhog-leader/tests/common/mod.rs
+++ b/rust/personhog-leader/tests/common/mod.rs
@@ -103,6 +103,7 @@ pub fn start_coordinator(
// warming behavior, and a live deadline would delete the
// state under test.
handoff_deadline: Duration::from_secs(86_400),
+ warming_deadline: Duration::from_secs(86_400),
},
strategy,
None,
@@ -145,7 +146,12 @@ impl StashHandler for MockCutoverHandler {
Ok(())
}
- async fn drain_stash(&self, partition: u32, target: &str) -> Result<()> {
+ async fn drain_stash(
+ &self,
+ partition: u32,
+ target: &str,
+ _cancel: CancellationToken,
+ ) -> Result<()> {
self.events.lock().await.push(CutoverEvent::StashDrained {
partition,
target: target.to_string(),
@@ -166,6 +172,8 @@ pub fn start_router(
router_name: name.to_string(),
lease_ttl: 10,
heartbeat_interval: Duration::from_secs(3),
+ reconcile_interval: Duration::from_secs(86_400),
+ ..RoutingTableConfig::default()
},
);
let token = cancel.child_token();
@@ -345,6 +353,9 @@ pub async fn start_leader_pod(
store,
PodConfig {
pod_name: name.to_string(),
+ // Parked: event-driven tests assert exact handler-call
+ // sequences a live reconcile pass would duplicate.
+ reconcile_interval: Duration::from_secs(86_400),
..Default::default()
},
Arc::new(handler),
@@ -417,6 +428,9 @@ pub async fn start_leader_pod_with_lease_ttl(
pod_name: name.to_string(),
lease_ttl,
heartbeat_interval: Duration::from_secs(heartbeat_secs),
+ // Parked: event-driven tests assert exact handler-call
+ // sequences a live reconcile pass would duplicate.
+ reconcile_interval: Duration::from_secs(86_400),
..Default::default()
},
Arc::new(handler),
diff --git a/rust/personhog-router/README.md b/rust/personhog-router/README.md
index cc5373ac5f14..07b7b70c34d9 100644
--- a/rust/personhog-router/README.md
+++ b/rust/personhog-router/README.md
@@ -54,13 +54,25 @@ phases and replaying them once the handoff completes:
still being collected). Subsequent writes for that partition are
parked on a `oneshot` instead of being forwarded.
-- **Drain** (on `Complete`): the router replays the parked writes to the
- new owner via `LeaderBackend::update_person_properties_no_stash`,
- bypassing the stash hook so each replayed request actually reaches
- the leader. New requests that arrive during drain land on the same
- queue and are picked up by the next loop iteration — drain only
- evicts the partition from the stash table when it observes the queue
- empty under the lock, preserving FIFO ordering across the cutover.
+- **Drain** (on `Complete` — including the reaffirm-Complete a
+ cancellation resolves to): the router replays each parked request to
+ the method it arrived on via the raw forward path, bypassing the
+ stash hook so each replayed request actually reaches the leader. New
+ requests that arrive during drain land on the same queue and are
+ picked up by the next loop iteration — drain only evicts the
+ partition from the stash table when it observes the queue empty
+ under the lock, preserving FIFO ordering across the cutover. Drains
+ run off the coordination watch loop in per-partition lanes: a
+ drain's duration is data-plane work and must never gate freeze acks
+ or routing updates for other partitions. A drain toward a different
+ target supersedes the one in flight — the old drain yields at a
+ batch boundary, leaving unprocessed queue contents parked for its
+ successor — while a request toward the same target is absorbed by
+ the running drain. Handoff deletion events trigger nothing:
+ cancellation is a record replacement, so a deletion only ever means
+ post-Complete cleanup. The periodic reconcile pass re-derives stash,
+ table, and drain state from a fresh snapshot, draining any stash
+ whose partition has no handoff to the assignment owner.
Two policies layer on the raw mechanism:
@@ -85,6 +97,12 @@ Two policies layer on the raw mechanism:
drain remaps it to `UNAVAILABLE` so callers retry, consistent with
the deadline and bounds contracts above.
+4. **Cooperative cancellation**: a superseded drain stops at the next
+ batch or chunk boundary. Unprocessed queue contents stay parked for
+ the successor drain, while requests already taken off the queue get
+ a definitive `UNAVAILABLE` so their clients retry — never a silent
+ drop.
+
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/backend/leader.rs b/rust/personhog-router/src/backend/leader.rs
index 469ff4b1418e..c957091862c2 100644
--- a/rust/personhog-router/src/backend/leader.rs
+++ b/rust/personhog-router/src/backend/leader.rs
@@ -116,9 +116,14 @@ impl LeaderBackend {
return Ok(channel.clone());
}
+ // The connect deadline matters independently of the request
+ // timeout: dialing a pod whose IP has been unassigned black-holes
+ // at TCP connect (no RST ever arrives), and the request timeout
+ // only starts once a connection exists.
let channel = Channel::from_shared(address.clone())
.map_err(|e| Status::internal(format!("invalid leader address: {e}")))?
.timeout(self.config.timeout)
+ .connect_timeout(self.config.timeout)
.tcp_nodelay(true)
.connect_lazy();
self.channels.insert(address, channel.clone());
diff --git a/rust/personhog-router/src/backend/stash.rs b/rust/personhog-router/src/backend/stash.rs
index d239340698b8..7d86f76fe41a 100644
--- a/rust/personhog-router/src/backend/stash.rs
+++ b/rust/personhog-router/src/backend/stash.rs
@@ -25,6 +25,7 @@ use bytes::Bytes;
use dashmap::DashMap;
use http::HeaderMap;
use tokio::sync::{oneshot, Mutex};
+use tokio_util::sync::CancellationToken;
use tonic::body::BoxBody;
/// Fixed per-request overhead estimate that approximates the bookkeeping
@@ -150,6 +151,14 @@ impl StashTable {
}
}
+ /// Whether the partition currently has a stash entry — a live
+ /// window, or backlog a yielded drain left parked. The entry only
+ /// disappears through drain's settle-and-evict, so its existence is
+ /// exactly "the stash lifecycle for this partition is not closed".
+ pub fn has_entry(&self, partition: u32) -> bool {
+ self.inner.contains_key(&partition)
+ }
+
fn get_or_create(&self, partition: u32) -> Arc<PartitionStash> {
self.inner
.entry(partition)
@@ -276,8 +285,17 @@ impl StashTable {
/// continues. Per-request bounded latency is the caller's
/// responsibility (e.g. a deadline check inside `forward_batch`
/// that fail-fasts past-deadline requests with `UNAVAILABLE`).
- pub async fn drain<F, Fut>(&self, partition: u32, mut forward_batch: F)
- where
+ ///
+ /// `cancel` stops the loop at the next batch boundary, leaving the
+ /// queue and its entry live: a cancelled drain has been superseded
+ /// (or the router is shutting down), and whatever remains parked
+ /// belongs to the successor drain.
+ pub async fn drain<F, Fut>(
+ &self,
+ partition: u32,
+ cancel: &CancellationToken,
+ mut forward_batch: F,
+ ) where
F: FnMut(Vec<StashedRequest>) -> Fut,
Fut: std::future::Future<Output = ()>,
{
@@ -287,6 +305,9 @@ impl StashTable {
};
loop {
+ if cancel.is_cancelled() {
+ return;
+ }
let batch = {
let mut guard = stash.queue.lock().await;
let Some(q) = guard.as_mut() else {
@@ -335,7 +356,7 @@ mod tests {
let collected = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let sink = std::sync::Arc::clone(&collected);
table
- .drain(partition, move |batch| {
+ .drain(partition, &CancellationToken::new(), move |batch| {
let sink = std::sync::Arc::clone(&sink);
async move {
sink.lock().unwrap().extend(batch);
@@ -442,6 +463,41 @@ mod tests {
);
}
+ /// A cancelled drain yields at the batch boundary without touching
+ /// the entry: whatever is parked belongs to the successor drain, and
+ /// new requests must keep stashing in the meantime. Evicting on
+ /// cancel instead would let requests bypass the stash and race ahead
+ /// of the parked backlog.
+ #[tokio::test]
+ async fn cancelled_drain_leaves_queue_live_for_successor() {
+ let table = StashTable::with_bounds(usize::MAX, usize::MAX);
+ table.begin_stash(0).await;
+ let _rx = match enqueue(&table, 0, 1).await {
+ StashDecision::Stashed(rx) => rx,
+ _ => panic!("expected Stashed"),
+ };
+
+ let cancelled = CancellationToken::new();
+ cancelled.cancel();
+ table.drain(0, &cancelled, |_batch| async {}).await;
+ assert!(
+ table.inner.contains_key(&0),
+ "cancelled drain must leave the entry live"
+ );
+
+ // Requests keep parking, and a successor drain collects everything.
+ let _rx2 = match enqueue(&table, 0, 2).await {
+ StashDecision::Stashed(rx) => rx,
+ _ => panic!("expected Stashed while entry is live"),
+ };
+ let drained = drain_to_vec(&table, 0).await;
+ assert_eq!(
+ drained.len(),
+ 2,
+ "successor drain must see the full backlog"
+ );
+ }
+
/// Back-to-back handoffs: drain → begin_stash for the same partition
/// must produce a fresh empty queue, not preserve stale state.
#[tokio::test]
@@ -672,7 +728,9 @@ mod tests {
// subsequent enqueue sees it and parks.
let drain_table = table.clone();
let drain_handle = tokio::spawn(async move {
- drain_table.drain(0, |_batch| async {}).await;
+ drain_table
+ .drain(0, &CancellationToken::new(), |_batch| async {})
+ .await;
});
let begin_table = table.clone();
let begin_handle = tokio::spawn(async move { begin_table.begin_stash(0).await });
diff --git a/rust/personhog-router/src/config.rs b/rust/personhog-router/src/config.rs
index 1f327a357e73..a7ced2642ffd 100644
--- a/rust/personhog-router/src/config.rs
+++ b/rust/personhog-router/src/config.rs
@@ -174,6 +174,36 @@ pub struct Config {
#[envconfig(default = "3")]
pub heartbeat_interval_secs: u64,
+ /// Fail the coordination run when the handoff watch loop makes no
+ /// progress for this long, so the router deregisters and restarts as
+ /// a healthy participant instead of wedging freeze quorums while its
+ /// lease stays alive. `0` disables the watchdog.
+ #[envconfig(default = "60")]
+ pub router_participant_stall_secs: u64,
+
+ /// How often the routing table re-derives stash, table, and drain
+ /// state from a fresh etcd snapshot, independent of watch events.
+ #[envconfig(default = "5")]
+ pub router_reconcile_secs: u64,
+
+ /// How many consecutive reconcile-pass failures the routing table
+ /// tolerates before failing the run. A failed pass only means the
+ /// router stays as stale as the previous tick — the watch-driven
+ /// steady state — so brief etcd blips must not be fatal; sustained
+ /// outage is already handled by lease self-fencing. The budget
+ /// bounds the partial-failure mode where snapshot reads fail while
+ /// the lease stays healthy, which would otherwise silently degrade
+ /// the liveness the reconcile provides.
+ #[envconfig(default = "12")]
+ pub router_reconcile_failure_budget: u32,
+
+ /// How long a handoff may sit in Warming before the coordinator
+ /// cancels it by replacement. Warming replays the partition's
+ /// changelog, so its budget is far above the general handoff
+ /// deadline; `0` disables it.
+ #[envconfig(default = "1800")]
+ pub coordinator_warming_deadline_secs: u64,
+
/// Maximum number of stashed write requests held per partition while
/// a handoff is in progress. Excess requests return UNAVAILABLE and
/// rely on caller-side retries.
@@ -454,6 +484,19 @@ impl Config {
Duration::from_secs(self.coordinator_handoff_deadline_secs)
}
+ pub fn router_reconcile_interval(&self) -> Duration {
+ Duration::from_secs(self.router_reconcile_secs)
+ }
+
+ pub fn coordinator_warming_deadline(&self) -> Duration {
+ Duration::from_secs(self.coordinator_warming_deadline_secs)
+ }
+
+ pub fn participant_stall_threshold(&self) -> Option<Duration> {
+ (self.router_participant_stall_secs > 0)
+ .then(|| Duration::from_secs(self.router_participant_stall_secs))
+ }
+
pub fn stash_max_wait(&self) -> Duration {
Duration::from_millis(self.stash_max_wait_ms)
}
diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rs
index 1a36abcc3be6..b7965ff88ed8 100644
--- a/rust/personhog-router/src/main.rs
+++ b/rust/personhog-router/src/main.rs
@@ -290,6 +290,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
router_name: config.pod_name.clone(),
lease_ttl: config.lease_ttl,
heartbeat_interval: config.heartbeat_interval(),
+ participant_stall_threshold: config.participant_stall_threshold(),
+ reconcile_failure_budget: config.router_reconcile_failure_budget,
+ reconcile_interval: config.router_reconcile_interval(),
};
let coordination_routing_table =
@@ -376,6 +379,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
rebalance_debounce_interval: config.coordinator_rebalance_debounce_interval(),
reconcile_interval: config.coordinator_reconcile_interval(),
handoff_deadline: config.coordinator_handoff_deadline(),
+ warming_deadline: config.coordinator_warming_deadline(),
},
Arc::new(StickyBalancedStrategy),
k8s_awareness,
diff --git a/rust/personhog-router/src/stash_handler.rs b/rust/personhog-router/src/stash_handler.rs
index 58505405b454..9aff3fe6a96b 100644
--- a/rust/personhog-router/src/stash_handler.rs
+++ b/rust/personhog-router/src/stash_handler.rs
@@ -1,4 +1,5 @@
use std::collections::HashMap;
+use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -6,6 +7,7 @@ use async_trait::async_trait;
use futures::future::join_all;
use personhog_coordination::error::Result as CoordResult;
use personhog_coordination::routing_table::StashHandler;
+use tokio_util::sync::CancellationToken;
use tonic::Code;
use crate::backend::{LeaderBackend, StashedRequest};
@@ -47,6 +49,11 @@ use crate::grpc_http::{grpc_error_response, grpc_status_code, is_grpc_error_resp
/// This shrinks drain wall-clock duration without breaking
/// ordering guarantees.
///
+/// 3. **Cooperative cancellation.** A superseded drain stops at the next
+/// batch or chunk boundary: unprocessed queue contents stay parked
+/// for the successor drain, while requests already taken off the
+/// queue get a definitive `UNAVAILABLE` so their clients retry.
+///
/// We also clear the cached gRPC client for the new owner so the first
/// post-handoff request opens a fresh connection to the new leader pod.
pub struct RouterStashHandler {
@@ -132,9 +139,9 @@ 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
+ // ownership is still settling: a reaffirm's drain races the
+ // 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
@@ -185,6 +192,7 @@ async fn forward_batch_by_key(
max_stash_wait: Duration,
concurrency: usize,
partition: u32,
+ cancel: &CancellationToken,
batch: Vec<StashedRequest>,
) {
type Key = (i64, i64);
@@ -195,6 +203,18 @@ async fn forward_batch_by_key(
let mut groups_iter = groups.into_values();
loop {
+ // A superseded drain stops at the next chunk wave — but requests
+ // already taken off the queue must never be dropped silently:
+ // every remaining one gets a definitive UNAVAILABLE so its
+ // client retries through whichever path is now live.
+ if cancel.is_cancelled() {
+ for group in groups_iter {
+ for req in group {
+ fail_superseded(req);
+ }
+ }
+ return;
+ }
let chunk: Vec<Vec<StashedRequest>> = (&mut groups_iter).take(concurrency).collect();
if chunk.is_empty() {
break;
@@ -211,8 +231,26 @@ async fn forward_batch_by_key(
}
}
+/// Reply `UNAVAILABLE` to a stashed request abandoned by a superseded
+/// drain — the same definitive retry contract as the deadline path.
+fn fail_superseded(req: StashedRequest) {
+ let response = grpc_error_response(Code::Unavailable, "stash drain superseded; retry");
+ if req.reply.send(response).is_err() {
+ metrics::counter!("personhog_router_stash_dropped_total").increment(1);
+ }
+ metrics::counter!(
+ "personhog_router_stash_drained_total",
+ "outcome" => "superseded"
+ )
+ .increment(1);
+}
+
#[async_trait]
impl StashHandler for RouterStashHandler {
+ fn stash_pending(&self, partition: u32) -> bool {
+ self.leader_backend.stash_table().has_entry(partition)
+ }
+
async fn begin_stash(&self, partition: u32, new_owner: &str) -> CoordResult<()> {
tracing::info!(
partition,
@@ -226,7 +264,12 @@ impl StashHandler for RouterStashHandler {
Ok(())
}
- async fn drain_stash(&self, partition: u32, new_owner: &str) -> CoordResult<()> {
+ async fn drain_stash(
+ &self,
+ partition: u32,
+ new_owner: &str,
+ cancel: CancellationToken,
+ ) -> CoordResult<()> {
let drain_start = Instant::now();
tracing::info!(partition, new_owner, "draining stash to new owner");
@@ -239,7 +282,7 @@ impl StashHandler for RouterStashHandler {
let leader_backend = Arc::clone(&self.leader_backend);
let max_stash_wait = self.max_stash_wait;
let drain_concurrency = self.drain_concurrency;
- let total_drained = Arc::new(std::sync::atomic::AtomicU64::new(0));
+ let total_drained = Arc::new(AtomicU64::new(0));
let counter = Arc::clone(&total_drained);
let stash_table = self.leader_backend.stash_table();
@@ -248,9 +291,10 @@ impl StashHandler for RouterStashHandler {
// arriving during drain land on the same queue and are
// delivered as a subsequent batch, preserving order.
stash_table
- .drain(partition, |batch| {
+ .drain(partition, &cancel, |batch| {
let leader = Arc::clone(&leader_backend);
let counter = Arc::clone(&counter);
+ let cancel = cancel.clone();
async move {
let batch_size = batch.len() as u64;
forward_batch_by_key(
@@ -258,15 +302,16 @@ impl StashHandler for RouterStashHandler {
max_stash_wait,
drain_concurrency,
partition,
+ &cancel,
batch,
)
.await;
- counter.fetch_add(batch_size, std::sync::atomic::Ordering::Relaxed);
+ counter.fetch_add(batch_size, Ordering::Relaxed);
}
})
.await;
- let total = total_drained.load(std::sync::atomic::Ordering::Relaxed);
+ let total = total_drained.load(Ordering::Relaxed);
metrics::histogram!("personhog_router_stash_drain_batch_size").record(total as f64);
let drain_ms = drain_start.elapsed().as_secs_f64() * 1000.0;
metrics::histogram!("personhog_router_stash_drain_duration_ms").record(drain_ms);
diff --git a/rust/personhog-router/tests/stash_integration.rs b/rust/personhog-router/tests/stash_integration.rs
index 6356e36598d8..b524b6047886 100644
--- a/rust/personhog-router/tests/stash_integration.rs
+++ b/rust/personhog-router/tests/stash_integration.rs
@@ -24,6 +24,7 @@ use personhog_router::config::RetryConfig;
use personhog_router::stash_handler::RouterStashHandler;
use prost::Message;
use tokio::sync::RwLock;
+use tokio_util::sync::CancellationToken;
use tonic::body::BoxBody;
use tonic::Code;
@@ -215,7 +216,7 @@ async fn request_during_stash_completes_after_drain() {
// routing path, awaits the leader's reply, then sends it through the
// oneshot back to the original caller.
handler
- .drain_stash(partition, "leader-new")
+ .drain_stash(partition, "leader-new", CancellationToken::new())
.await
.expect("drain_stash should succeed");
@@ -260,7 +261,10 @@ async fn multiple_stashed_requests_drain_in_fifo() {
assert!(!j.is_finished(), "all three should still be parked");
}
- handler.drain_stash(partition, "leader-new").await.unwrap();
+ handler
+ .drain_stash(partition, "leader-new", CancellationToken::new())
+ .await
+ .unwrap();
// Collect responses in spawn order. The drain forwards in FIFO order,
// so version increments must be monotonic relative to spawn order
@@ -372,7 +376,10 @@ async fn back_to_back_handoffs_use_fresh_queue() {
let backend_a = Arc::clone(&backend);
let pending_a = tokio::spawn(async move { forward(&backend_a, req_a).await });
tokio::time::sleep(Duration::from_millis(20)).await;
- handler.drain_stash(partition, "leader-a").await.unwrap();
+ handler
+ .drain_stash(partition, "leader-a", CancellationToken::new())
+ .await
+ .unwrap();
let raw_a = pending_a.await.unwrap();
decode_response::<UpdatePersonPropertiesResponse>(raw_a)
.await
@@ -390,7 +397,10 @@ async fn back_to_back_handoffs_use_fresh_queue() {
!pending_b.is_finished(),
"second handoff's request must park, not forward"
);
- handler.drain_stash(partition, "leader-b").await.unwrap();
+ handler
+ .drain_stash(partition, "leader-b", CancellationToken::new())
+ .await
+ .unwrap();
let raw_b = pending_b.await.unwrap();
decode_response::<UpdatePersonPropertiesResponse>(raw_b)
.await
@@ -438,7 +448,7 @@ async fn ordering_preserved_when_request_arrives_during_drain() {
let drain_handler = Arc::clone(&handler_for_drain);
let drain_task = tokio::spawn(async move {
drain_handler
- .drain_stash(partition, "leader-new")
+ .drain_stash(partition, "leader-new", CancellationToken::new())
.await
.unwrap();
});
@@ -500,7 +510,10 @@ async fn stash_wait_exceeded_returns_unavailable() {
// Wait long enough that the stashed request is past its deadline.
tokio::time::sleep(Duration::from_millis(100)).await;
- handler.drain_stash(partition, "leader-new").await.unwrap();
+ handler
+ .drain_stash(partition, "leader-new", CancellationToken::new())
+ .await
+ .unwrap();
let raw = pending.await.unwrap();
let code = decode_response::<UpdatePersonPropertiesResponse>(raw)
@@ -544,7 +557,10 @@ async fn fenced_leader_during_drain_returns_unavailable() {
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();
+ handler
+ .drain_stash(partition, "leader-new", CancellationToken::new())
+ .await
+ .unwrap();
let response = pending.await.unwrap();
let code = decode_response::<UpdatePersonPropertiesResponse>(response)
@@ -588,7 +604,10 @@ async fn stashed_strong_read_observes_stashed_write() {
"both must park"
);
- handler.drain_stash(partition, "leader-new").await.unwrap();
+ handler
+ .drain_stash(partition, "leader-new", CancellationToken::new())
+ .await
+ .unwrap();
let write_resp = decode_response::<UpdatePersonPropertiesResponse>(write.await.unwrap())
.await
@@ -626,7 +645,10 @@ async fn stashed_read_past_deadline_returns_unavailable() {
let read = tokio::spawn(async move { forward_read(&backend_r, team_id, person_id).await });
tokio::time::sleep(Duration::from_millis(100)).await;
- handler.drain_stash(partition, "leader-new").await.unwrap();
+ handler
+ .drain_stash(partition, "leader-new", CancellationToken::new())
+ .await
+ .unwrap();
let code = decode_response::<GetPersonResponse>(read.await.unwrap())
.await
@@ -674,7 +696,7 @@ async fn drain_converges_with_concurrent_arrivals() {
let drain_handler = Arc::clone(&handler);
let drain_task = tokio::spawn(async move {
drain_handler
- .drain_stash(partition, "leader-new")
+ .drain_stash(partition, "leader-new", CancellationToken::new())
.await
.unwrap();
});
diff --git a/rust/personhog-stateright/src/main.rs b/rust/personhog-stateright/src/main.rs
index 055e45b93f1b..868a52023169 100644
--- a/rust/personhog-stateright/src/main.rs
+++ b/rust/personhog-stateright/src/main.rs
@@ -50,6 +50,7 @@ fn main() {
rejoins: 0,
router_joins: 0,
zombie_window,
+ cancels: 0,
probes: false,
};
println!("exploring {:?} at http://localhost:3000 …", args.scenario);
diff --git a/rust/personhog-stateright/src/model.rs b/rust/personhog-stateright/src/model.rs
index c8b2e83f2932..889930c791d7 100644
--- a/rust/personhog-stateright/src/model.rs
+++ b/rust/personhog-stateright/src/model.rs
@@ -90,6 +90,8 @@ pub struct HandoffModel {
pub reads: u8,
/// Total failure events (crash-restarts + lease expiries).
pub crashes: u8,
+ /// Total deadline cancellations the checker may inject.
+ pub cancels: u8,
/// Times a dead pod may rejoin under its old name.
pub rejoins: u8,
/// Times a router may (re)join: late slots coming up, or dead
@@ -215,7 +217,14 @@ impl HandoffModel {
/// beyond its warm cutoff and is invisible to it forever.
fn accept_write(&self, state: &mut SystemState, x: PodId, partition: Partition) {
let designated_other = match state.handoffs.get(&partition) {
- Some(h) if h.new_owner != x => state.pods[&h.new_owner].warmed.contains_key(&partition),
+ // A handoff-designated pod's warm hides this write forever
+ // only if that warm will actually be honored — i.e. it was
+ // installed for this handoff. A stale-era warm is released
+ // and rebuilt at Acquiring, which picks the write up.
+ Some(h) if h.new_owner != x => state.pods[&h.new_owner]
+ .warmed
+ .get(&partition)
+ .is_some_and(|w| w.for_handoff == Some(h.id)),
Some(_) => false,
None => match state.assignments.get(&partition) {
Some(owner) if *owner != x => state.pods[owner].warmed.contains_key(&partition),
@@ -238,6 +247,78 @@ impl HandoffModel {
}
}
+ /// Cancel the in-flight handoff at `p` by atomic replacement — the
+ /// single disposition rule production's planner applies on any
+ /// cancellation trigger. The record is swapped, in one guarded
+ /// transaction that also clears the predecessor's acks, for whatever
+ /// resolves the routers' stashes:
+ ///
+ /// * current owner registered → a reaffirm: `Complete` toward that
+ /// owner, `old_owner: None`. Routers drain home through their
+ /// ordinary Complete handling; the owner pod re-derives `Serving`
+ /// and unfences. (`old_owner` must be `None` — naming the owner on
+ /// both sides would match `desired_state`'s old-owner arm first
+ /// and derive `Released`, making the pod drop the partition.)
+ /// * otherwise, a placeable successor → a fresh `Freezing` handoff
+ /// toward the planner's target, new id, new quorum snapshot.
+ /// Routers keep stashing without ever observing a gap.
+ /// * nothing placeable (owner dead, no registered pod) → plain
+ /// delete. Safe because stash disposal is derived from durable
+ /// state (`Observe`'s no-handoff arm drains to the assignment
+ /// owner, fail-closed), not decided on the deletion event.
+ fn cancel_by_replacement(&self, state: &mut SystemState, p: Partition) {
+ if state
+ .routers
+ .values()
+ .any(|r| r.stash.get(&p).is_some_and(|q| !q.is_empty()))
+ {
+ state.cancelled_while_stash_parked = true;
+ }
+
+ state.freeze_acks.retain(|(fp, _), _| fp != &p);
+ state.drained_acks.retain(|(dp, _), _| dp != &p);
+ state.warmed_acks.retain(|(wp, _), _| wp != &p);
+
+ let owner = state.assignments.get(&p).copied();
+ if let Some(owner) = owner.filter(|o| state.pods[o].registered) {
+ let id = state.next_handoff_id;
+ state.next_handoff_id += 1;
+ state.handoffs.insert(
+ p,
+ Handoff {
+ id,
+ old_owner: None,
+ new_owner: owner,
+ phase: Phase::Complete,
+ quorum: BTreeSet::new(),
+ },
+ );
+ state.reaffirmed = true;
+ return;
+ }
+ if let Some(target) = self.target_owner(state, p) {
+ let id = state.next_handoff_id;
+ state.next_handoff_id += 1;
+ let quorum: BTreeSet<RouterId> = self
+ .router_ids()
+ .filter(|r| state.routers[r].registered)
+ .collect();
+ state.handoffs.insert(
+ p,
+ Handoff {
+ id,
+ old_owner: owner,
+ new_owner: target,
+ phase: Phase::Freezing,
+ quorum,
+ },
+ );
+ state.replaced_with_successor = true;
+ return;
+ }
+ state.handoffs.remove(&p);
+ }
+
/// Route one write through router `r` exactly as the raw proxy does:
/// park it if the partition is stashing, otherwise forward to the
/// table entry and let the leader's admission decide.
@@ -331,18 +412,25 @@ impl Model for HandoffModel {
crashes_left: self.crashes,
rejoins_left: self.rejoins,
router_joins_left: self.router_joins,
+ cancels_left: self.cancels,
next_write_id: 0,
reads_served: 0,
lost_acked_write: false,
double_planned_handoff: false,
stale_strong_read: false,
+ reaffirmed: false,
+ replaced_with_successor: false,
+ cancelled_while_stash_parked: false,
}]
}
fn actions(&self, state: &Self::State, actions: &mut Vec<Self::Action>) {
actions.push(Action::Rebalance);
for p in self.partition_ids() {
- actions.push(Action::CleanupStale(p));
+ actions.push(Action::CancelDeadNewOwner(p));
+ if state.cancels_left > 0 {
+ actions.push(Action::Cancel(p));
+ }
actions.push(Action::AdvancePhase(p));
actions.push(Action::CleanupComplete(p));
for pod in self.pod_ids() {
@@ -385,21 +473,37 @@ impl Model for HandoffModel {
let mut state = last.clone();
match action {
// ── coordinator ────────────────────────────────────
- // The cleanup half of `handle_pod_change_static` for one
- // partition. The mod_revision-guarded delete lets the model
- // treat check-and-delete as atomic; scheduling it freely
- // against Rebalance/AdvancePhase/CleanupComplete covers the
+ // The dead-new-owner arm of the coordinator's cleanup, now a
+ // replacement. The mod_revision guard lets the model treat
+ // check-and-replace as atomic; scheduling it freely against
+ // Rebalance/AdvancePhase/CleanupComplete covers the
// concurrency of the pod watch, handoff watch, tick, and an
- // overlapping outgoing coordinator.
- Action::CleanupStale(p) => {
+ // overlapping outgoing coordinator. Complete records are
+ // excluded — they resolve through CleanupComplete and a
+ // later Rebalance, exactly as in production.
+ Action::CancelDeadNewOwner(p) => {
match state.handoffs.get(&p) {
- Some(h) if !state.pods[&h.new_owner].registered => {}
+ Some(h)
+ if h.phase != Phase::Complete && !state.pods[&h.new_owner].registered => {}
_ => return None,
}
- state.handoffs.remove(&p);
- state.freeze_acks.retain(|(fp, _), _| fp != &p);
- state.drained_acks.retain(|(dp, _), _| dp != &p);
- state.warmed_acks.retain(|(wp, _), _| wp != &p);
+ self.cancel_by_replacement(&mut state, p);
+ }
+
+ // Deadline cancellation: any in-flight handoff, any phase
+ // short of Complete, whenever the checker feels like it —
+ // the superset of every production deadline policy. Same
+ // disposition as the dead-new-owner arm.
+ Action::Cancel(p) => {
+ if state.cancels_left == 0 {
+ return None;
+ }
+ match state.handoffs.get(&p) {
+ Some(h) if h.phase != Phase::Complete => {}
+ _ => return None,
+ }
+ state.cancels_left -= 1;
+ self.cancel_by_replacement(&mut state, p);
}
// The rebalance half: create Freezing handoffs for every
@@ -620,6 +724,7 @@ impl Model for HandoffModel {
log.epoch = log.epoch.wrapping_add(1);
}
WarmState {
+ for_handoff: None,
epoch: log.epoch,
cutoff: log.len,
accepted: 0,
@@ -652,13 +757,23 @@ impl Model for HandoffModel {
DesiredState::Acquiring => {
let h_id = state.handoffs[&p].id;
let mut changed = false;
- if !state.pods[&x].warmed.contains_key(&p) {
+ // Mirror of the pod's `WarmProvenance` check: only
+ // a warm installed for this handoff satisfies its
+ // warming — a leftover from an earlier era (the
+ // intervening Released convergence never ran) is
+ // released and rebuilt at the current HWM.
+ let valid = state.pods[&x]
+ .warmed
+ .get(&p)
+ .is_some_and(|w| w.for_handoff == Some(h_id));
+ if !valid {
let warm = {
let log = state.changelogs.get_mut(&p).unwrap();
if self.variant == Variant::EpochFenced {
log.epoch = log.epoch.wrapping_add(1);
}
WarmState {
+ for_handoff: Some(h_id),
epoch: log.epoch,
cutoff: log.len,
accepted: 0,
@@ -1004,6 +1119,20 @@ impl Model for HandoffModel {
// `assert_properties` stays usable across the matrix.
m.reads == 0 || s.reads_served > 0
}),
+ // Replacement-cancellation reachability. Guards make each
+ // probe vacuous outside the configs shaped to reach it, so
+ // `assert_properties` stays usable across the matrix.
+ // A reaffirm needs a move handoff whose old owner is alive —
+ // which takes a crash *and* a rejoin to manufacture.
+ Property::<Self>::sometimes("cancellation_reaffirms", |m, s| {
+ m.cancels == 0 || m.rejoins == 0 || s.reaffirmed
+ }),
+ Property::<Self>::sometimes("cancellation_replaces_with_successor", |m, s| {
+ m.cancels == 0 || s.replaced_with_successor
+ }),
+ Property::<Self>::sometimes("cancellation_races_a_parked_stash", |m, s| {
+ m.cancels == 0 || m.writes == 0 || s.cancelled_while_stash_parked
+ }),
// Liveness: every full run ends quiescent and converged —
// no handoffs in flight, every assignment served by a warm,
// unfenced, registered pod, all routers agreeing, nothing
diff --git a/rust/personhog-stateright/src/types.rs b/rust/personhog-stateright/src/types.rs
index 248e0ad23726..8b22c44dfbc7 100644
--- a/rust/personhog-stateright/src/types.rs
+++ b/rust/personhog-stateright/src/types.rs
@@ -40,6 +40,15 @@ pub struct Handoff {
/// know about one warmed partition.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct WarmState {
+ /// What this warm was installed for (production:
+ /// `WarmProvenance` on the pod handle). `None` is a serving-era warm
+ /// (restart, or the returning old owner of an in-flight handoff);
+ /// `Some(id)` was installed for that handoff's Warming. An Acquiring
+ /// convergence honors a warm only when it carries the current
+ /// handoff's id — anything else is a leftover from an earlier era
+ /// whose cache may predate writes accepted since, and is released
+ /// and rebuilt.
+ pub for_handoff: Option<HandoffId>,
/// The Kafka transactional-producer epoch held (production:
/// `init_transactions` under the `EpochFenced` variant; the broker
/// rejects produces bearing a stale epoch).
@@ -153,6 +162,8 @@ pub struct SystemState {
/// Times a router may (re)join: a late slot coming up for the first
/// time, or a dead router returning as a fresh process.
pub router_joins_left: u8,
+ /// Deadline cancellations the checker may still inject.
+ pub cancels_left: u8,
pub next_write_id: WriteId,
/// Count of strong reads actually served (reachability evidence for
/// the read properties).
@@ -173,6 +184,17 @@ pub struct SystemState {
/// (`cutoff + accepted`) is behind the changelog — the read returned
/// state missing at least one acked write.
pub stale_strong_read: bool,
+
+ // ── reachability flags (probe evidence, history encoding) ──
+ /// A cancellation resolved as a reaffirm-Complete toward the live
+ /// current owner.
+ pub reaffirmed: bool,
+ /// A cancellation resolved as an atomic successor replacement.
+ pub replaced_with_successor: bool,
+ /// A cancellation happened while some router held parked requests
+ /// for the partition — the composition the replacement design must
+ /// keep safe and live.
+ pub cancelled_while_stash_parked: bool,
}
/// Everything that can happen, from every actor, including failures.
@@ -180,15 +202,26 @@ pub struct SystemState {
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Action {
// ── coordinator (pure derivation over etcd state) ──────────
- /// The cleanup half of `handle_pod_change` for one partition:
- /// atomically check-and-delete a handoff whose new owner is
- /// unregistered (the mod_revision guard is what makes modeling this
- /// as atomic faithful). Scheduled independently of `Rebalance` and
- /// `AdvancePhase` — the coordinator's watch handlers and tick run
- /// concurrently in production, and an overlapping outgoing
- /// coordinator is just more interleavings of the same guarded
- /// actions.
- CleanupStale(Partition),
+ /// Cancellation of a handoff whose new owner is unregistered — the
+ /// dead-new-owner arm of the coordinator's cleanup, as a
+ /// mod_revision-guarded atomic *replacement*: the record is swapped
+ /// for whatever resolves its stashes (a reaffirm-Complete toward a
+ /// live current owner, a successor Freezing handoff, or — only when
+ /// nothing is placeable — a plain delete). Scheduled independently
+ /// of `Rebalance` and `AdvancePhase` — the coordinator's watch
+ /// handlers and tick run concurrently in production, and an
+ /// overlapping outgoing coordinator is just more interleavings of
+ /// the same guarded actions.
+ CancelDeadNewOwner(Partition),
+ /// Deadline cancellation of any in-flight handoff, with the same
+ /// replacement disposition. The model has no clock, so the deadline
+ /// trigger is "the checker schedules this whenever it likes" — a
+ /// superset of every timing policy production could apply, which is
+ /// exactly what makes the phase-aware deadline a production-only
+ /// concern. Budgeted (`cancels_left`): an unbounded cancel action
+ /// would let the checker cancel forever and vacuously defeat the
+ /// convergence property.
+ Cancel(Partition),
/// The rebalance half of `handle_pod_change`: when no handoffs are
/// in flight, create Freezing handoffs for every assignment diff in
/// one transaction.
diff --git a/rust/personhog-stateright/tests/model_tests.rs b/rust/personhog-stateright/tests/model_tests.rs
index b87f42f7122d..26f38966414e 100644
--- a/rust/personhog-stateright/tests/model_tests.rs
+++ b/rust/personhog-stateright/tests/model_tests.rs
@@ -41,6 +41,7 @@ fn base() -> HandoffModel {
rejoins: 0,
router_joins: 0,
zombie_window: 0,
+ cancels: 0,
probes: false,
}
}
@@ -559,3 +560,88 @@ fn state_space_report() {
);
}
}
+
+/// Deadline cancellation as atomic replacement, with no failures in the
+/// mix: any in-flight handoff may be cancelled at any moment (the model
+/// has no clock, so this covers every production deadline policy). The
+/// budget of two lets the checker cancel a successor produced by an
+/// earlier cancellation. Every safety property must hold across the
+/// replacement interleavings — including a cancellation racing parked
+/// stash requests — and every full run must still converge with empty
+/// stashes.
+#[test]
+fn deadline_cancellation_by_replacement_is_safe_and_live() {
+ HandoffModel {
+ cancels: 2,
+ ..base()
+ }
+ .checker()
+ .spawn_bfs()
+ .join()
+ .assert_properties();
+}
+
+/// The reaffirm arm: cancelling a move handoff whose old owner is alive
+/// must resolve as a Complete toward that owner — the pod re-derives
+/// Serving and unfences, routers drain home. Manufacturing a move whose
+/// old owner survives takes a crash and a rejoin (a fresh handoff has no
+/// old owner, and a crashed owner is dead): the pod dies, its partition
+/// moves, it rejoins, and the rebalance that moves a partition back is
+/// the reaffirmable handoff. Two partitions so the sticky strategy has a
+/// move to make at rejoin.
+#[test]
+fn cancellation_with_live_owner_reaffirms_and_resumes() {
+ HandoffModel {
+ partitions: 2,
+ crashes: 1,
+ rejoins: 1,
+ cancels: 1,
+ // One write keeps the workload probes reachable while holding
+ // the state space down — this test's subject is the control
+ // plane's reaffirm resolution, not the data path.
+ writes: 1,
+ reads: 0,
+ ..base()
+ }
+ .checker()
+ .spawn_bfs()
+ .join()
+ .assert_properties();
+}
+
+/// The successor arm under failure: the owner dies while its handoff is
+/// in flight, and the cancellation replaces the record with the
+/// successor in one transaction — the stash never observes a gap between
+/// attempts. The dead-new-owner arm is exercised in the same space (a
+/// cancellation's successor can itself target a pod that then dies).
+#[test]
+fn cancellation_with_dead_owner_replaces_atomically() {
+ HandoffModel {
+ crashes: 1,
+ cancels: 1,
+ ..base()
+ }
+ .checker()
+ .spawn_bfs()
+ .join()
+ .assert_properties();
+}
+
+/// Isolation probe for the stale-warm counterexample: the same
+/// crash+rejoin+two-partition space with cancellation disabled. If this
+/// fails too, the loss mechanism predates cancellation-by-replacement.
+#[test]
+fn rejoin_two_partitions_without_cancellation() {
+ HandoffModel {
+ partitions: 2,
+ crashes: 1,
+ rejoins: 1,
+ writes: 1,
+ reads: 0,
+ ..base()
+ }
+ .checker()
+ .spawn_bfs()
+ .join()
+ .assert_properties();
+}