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.

feat(personhog): warm partitions in parallel during handoffs (#74502)

Zach Brown062311347d5b
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index d2a0d26fca12..22aaa845d29e 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -8466,6 +8466,7 @@ dependencies = [
"assignment-coordination",
"async-trait",
"etcd-client",
+ "futures",
"k8s-awareness",
"k8s-openapi",
"kube",
diff --git a/rust/personhog-coordination/Cargo.toml b/rust/personhog-coordination/Cargo.toml
index 7163ec66c8ea..d84705fe9d61 100644
--- a/rust/personhog-coordination/Cargo.toml
+++ b/rust/personhog-coordination/Cargo.toml
@@ -8,6 +8,7 @@ publish = false
assignment-coordination = { path = "../common/assignment-coordination" }
async-trait = { workspace = true }
etcd-client = "0.18"
+futures = { workspace = true }
k8s-awareness = { path = "../common/k8s-awareness" }
metrics = { workspace = true }
serde = { workspace = true }
diff --git a/rust/personhog-coordination/src/pod.rs b/rust/personhog-coordination/src/pod.rs
index 567ef8f0a68e..fd3cdb727cdf 100644
--- a/rust/personhog-coordination/src/pod.rs
+++ b/rust/personhog-coordination/src/pod.rs
@@ -1,11 +1,14 @@
use std::collections::{HashMap, HashSet};
+use std::str::from_utf8;
use std::sync::Arc;
use std::time::{Duration, Instant};
use async_trait::async_trait;
use etcd_client::{EventType, WatchStream};
+use futures::future::BoxFuture;
+use futures::stream::{FuturesUnordered, StreamExt};
use metrics::{counter, gauge, histogram};
-use tokio::sync::{Mutex, Notify};
+use tokio::sync::{Mutex, Notify, Semaphore, SemaphorePermit};
use tokio_util::sync::CancellationToken;
use assignment_coordination::store::parse_watch_value;
@@ -147,10 +150,12 @@ 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.
+ /// How often the watch loop re-derives the involved-partition set
+ /// 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; each pass re-dispatches every involved partition
+ /// through the same single-flight convergence lanes the event path
+ /// uses.
pub reconcile_interval: Duration,
/// How many consecutive reconcile failures to tolerate before
/// failing the run. Same reasoning as the router's budget: a failed
@@ -161,6 +166,13 @@ pub struct PodConfig {
/// `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>,
+ /// Maximum number of partition warms this pod runs concurrently.
+ /// Warming several partitions at once keeps a deploy-burst of
+ /// inbound handoffs from queueing each warm behind the last; the
+ /// bound keeps a cold restart from opening one Kafka replay per
+ /// assigned partition all at once. Only warms queue on this —
+ /// drains, releases, and acks are never held behind warm pressure.
+ pub warm_concurrency: usize,
}
impl Default for PodConfig {
@@ -175,6 +187,7 @@ impl Default for PodConfig {
reconcile_interval: Duration::from_secs(5),
reconcile_failure_budget: 12,
advertise_address: None,
+ warm_concurrency: 4,
}
}
}
@@ -210,6 +223,8 @@ pub struct PodHandle {
fenced_partitions: Mutex<HashSet<u32>>,
/// Signalled when a partition is released, waking `drain()` without polling.
drain_notify: Notify,
+ /// Bounds concurrent `warm_partition` calls to `warm_concurrency`.
+ warm_slots: Semaphore,
/// Optional K8s awareness for departure classification during shutdown.
k8s_awareness: Option<Arc<K8sAwareness>>,
}
@@ -221,6 +236,7 @@ impl PodHandle {
handler: Arc<dyn HandoffHandler>,
k8s_awareness: Option<Arc<K8sAwareness>>,
) -> Self {
+ let warm_slots = Semaphore::new(config.warm_concurrency);
Self {
store,
config,
@@ -228,6 +244,7 @@ impl PodHandle {
warmed_partitions: Mutex::new(HashMap::new()),
fenced_partitions: Mutex::new(HashSet::new()),
drain_notify: Notify::new(),
+ warm_slots,
k8s_awareness,
}
}
@@ -263,14 +280,11 @@ impl PodHandle {
// changes only ever happen atomically with a handoff Complete event,
// so there's no need to watch assignments separately.
//
- // The outer `select!` against the cancel token is what guarantees we
- // exit promptly even when `watch_handoff_loop` is parked inside a
- // `handle_handoff_event` call. The loop's own `select!` only checks
- // the cancel token between iterations; if a phase handler (e.g.
- // `warm_partition`) blocks indefinitely, the inner check is never
- // re-polled. Racing the cancel token at this level drops the
- // in-flight loop future via cancel-by-drop, unwinding any stuck
- // handler and letting the pod proceed to drain + lease revoke.
+ // The outer `select!` against the cancel token is what guarantees a
+ // prompt exit: dropping the loop future also drops every in-flight
+ // convergence it is driving, so even a phase handler (e.g.
+ // `warm_partition`) that blocks indefinitely cannot hold the pod
+ // back from proceeding to drain + lease revoke.
//
// The heartbeat task is raced here too: the coordinator treats
// lease expiry as pod death and hands this pod's partitions to
@@ -282,21 +296,22 @@ impl PodHandle {
let mut lease_lost = false;
let result = tokio::select! {
r = async {
- // Converge every partition this pod is involved in before
- // watching for new events. A pod that crash-restarts within
- // its lease TTL keeps its registration and assignments but
- // loses all in-memory state (cache, fences) — and because
- // nothing about etcd changed, no event will ever arrive to
- // repair the divergence. Re-deriving local state from the
- // durable state at startup closes that structurally: cold
- // assigned partitions re-warm, in-flight handoffs get their
+ // Seed the loop with every partition this pod is involved
+ // in before watching for new events. A pod that
+ // crash-restarts within its lease TTL keeps its
+ // registration and assignments but loses all in-memory
+ // state (cache, fences) — and because nothing about etcd
+ // changed, no event will ever arrive to repair the
+ // divergence. Re-deriving local state from the durable
+ // state at startup closes that structurally: cold assigned
+ // partitions re-warm, in-flight handoffs get their
// drain/warm/ack, completed ones release. The watch is
// anchored to the snapshot's revision, so an event landing
// between the snapshot and the watch attaching is replayed
// rather than lost.
- let snapshot_revision = self.reconcile_all().await?;
+ let (initial, snapshot_revision) = self.involved_partitions().await?;
let stream = self.store.watch_handoffs_from(snapshot_revision + 1).await?;
- self.watch_handoff_loop(stream, cancel.clone()).await
+ self.watch_handoff_loop(stream, cancel.clone(), initial).await
} => r,
r = &mut heartbeat_handle => {
lease_lost = true;
@@ -414,14 +429,14 @@ impl PodHandle {
// otherwise be missed — and anchor the fresh watch to the
// snapshot's revision.
let drain_cancel = CancellationToken::new();
- let snapshot_revision = self.reconcile_all().await?;
+ let (initial, snapshot_revision) = self.involved_partitions().await?;
let stream = self
.store
.watch_handoffs_from(snapshot_revision + 1)
.await?;
tokio::select! {
- r = self.watch_handoff_loop(stream, drain_cancel.clone()) => {
+ r = self.watch_handoff_loop(stream, drain_cancel.clone(), initial) => {
r?;
},
_ = self.wait_for_drain() => {
@@ -466,23 +481,18 @@ impl PodHandle {
}
}
- /// Converge every partition this pod is involved in — assigned to it,
- /// or named in a handoff as old or new owner — from a consistent
- /// snapshot of the durable state. Returns the smaller of the two
- /// snapshot revisions so the caller can anchor the handoff watch: any
- /// change landing between the two reads (or between them and the watch
- /// attaching) is redelivered as an event and re-converged with fresh
- /// reads.
- async fn reconcile_all(&self) -> Result<i64> {
+ /// Derive every partition this pod is involved in — assigned to it,
+ /// named in a handoff as old or new owner, or still held locally —
+ /// from a consistent snapshot of the durable state. Returns the set
+ /// alongside the smaller of the two snapshot revisions so the caller
+ /// can anchor the handoff watch: any change landing between the two
+ /// reads (or between them and the watch attaching) is redelivered as
+ /// an event and re-converged with fresh reads.
+ async fn involved_partitions(&self) -> Result<(HashSet<u32>, i64)> {
let (assignments, rev_a) = self.store.list_assignments_with_revision().await?;
let (handoffs, rev_h) = self.store.list_handoffs_with_revision().await?;
let pod = &self.config.pod_name;
- let assignment_map: std::collections::HashMap<u32, &PartitionAssignment> =
- assignments.iter().map(|a| (a.partition, a)).collect();
- let handoff_map: std::collections::HashMap<u32, &HandoffState> =
- handoffs.iter().map(|h| (h.partition, h)).collect();
-
let mut partitions: HashSet<u32> = HashSet::new();
for a in &assignments {
if a.owner == *pod {
@@ -506,16 +516,8 @@ impl PodHandle {
partitions = partitions.len(),
"reconciling local state against durable state"
);
- for partition in partitions {
- self.apply(
- partition,
- assignment_map.get(&partition).copied(),
- handoff_map.get(&partition).copied(),
- )
- .await?;
- }
- Ok(rev_a.min(rev_h))
+ Ok((partitions, rev_a.min(rev_h)))
}
/// Re-derive and apply the desired state for one partition from fresh
@@ -530,10 +532,21 @@ impl PodHandle {
.await
}
+ /// Bound on concurrent cache warms. Only the two warm sites in
+ /// `apply` queue here; everything else a convergence does (fence,
+ /// drain, release, ack) must stay prompt regardless of warm pressure.
+ async fn acquire_warm_slot(&self) -> Result<SemaphorePermit<'_>> {
+ self.warm_slots
+ .acquire()
+ .await
+ .map_err(|_| Error::invalid_state("warm semaphore closed".to_string()))
+ }
+
/// Drive local state (cache warmth, write fence, acks, held set) to
- /// the desired state. Every transition is idempotent; callers are
- /// serialized (startup reconcile, then the single watch loop), so no
- /// two applications for the same partition ever interleave.
+ /// the desired state. Every transition is idempotent; the watch loop
+ /// runs at most one convergence per partition at a time, so no two
+ /// applications for the same partition ever interleave — applications
+ /// for different partitions may run concurrently.
async fn apply(
&self,
partition: u32,
@@ -547,6 +560,7 @@ impl PodHandle {
DesiredState::Serving => {
if !self.warmed_partitions.lock().await.contains_key(&partition) {
tracing::info!(pod, partition, "converging to Serving: warming");
+ let _warm_slot = self.acquire_warm_slot().await?;
let start = Instant::now();
self.handler.warm_partition(partition).await?;
histogram!("personhog_coordination_partition_warm_ms", "trigger" => "restart")
@@ -627,6 +641,7 @@ impl PodHandle {
self.handler.release_partition(partition).await?;
}
tracing::info!(pod, partition, "converging to Acquiring: warming");
+ let _warm_slot = self.acquire_warm_slot().await?;
let start = Instant::now();
self.handler.warm_partition(partition).await?;
histogram!("personhog_coordination_partition_warm_ms", "trigger" => "handoff")
@@ -674,48 +689,152 @@ impl PodHandle {
&self,
mut stream: WatchStream,
cancel: CancellationToken,
+ initial: HashSet<u32>,
) -> 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.
+ // The truth path: periodically re-derive the involved-partition
+ // set from a fresh snapshot and re-dispatch each member,
+ // repairing whatever the event path failed to deliver. First
+ // pass one interval out — the caller has just seeded `initial`
+ // from the same derivation.
let mut reconcile_tick = tokio::time::interval_at(
tokio::time::Instant::now() + self.config.reconcile_interval,
self.config.reconcile_interval,
);
+
+ // Convergence is single-flight per partition: at most one
+ // `converge` future per partition lives in `lanes` at a time,
+ // preserving the no-interleaving guarantee `apply` relies on,
+ // while different partitions converge concurrently — a deploy
+ // moving several partitions onto this pod warms them in
+ // parallel instead of queueing each behind the last. A signal
+ // arriving for a partition already converging parks in
+ // `pending`; `converge` reads fresh state, so one re-run
+ // absorbs any number of coalesced signals. Dropping this loop
+ // future drops every in-flight convergence with it, so cancel
+ // semantics are unchanged from converging inline.
+ let mut lanes: FuturesUnordered<BoxFuture<'_, (u32, Trigger, Result<()>)>> =
+ FuturesUnordered::new();
+ let mut in_flight: HashSet<u32> = HashSet::new();
+ let mut pending: HashMap<u32, Trigger> = HashMap::new();
+
+ fn dispatch<'s>(
+ handle: &'s PodHandle,
+ partition: u32,
+ trigger: Trigger,
+ in_flight: &mut HashSet<u32>,
+ pending: &mut HashMap<u32, Trigger>,
+ lanes: &mut FuturesUnordered<BoxFuture<'s, (u32, Trigger, Result<()>)>>,
+ ) {
+ if in_flight.contains(&partition) {
+ // Coalesce, keeping the stricter error disposition: a
+ // fatal Event request must not be downgraded by a later
+ // budgeted Reconcile one.
+ let entry = pending.entry(partition).or_insert(trigger);
+ if trigger == Trigger::Event {
+ *entry = Trigger::Event;
+ }
+ return;
+ }
+ in_flight.insert(partition);
+ lanes.push(Box::pin(async move {
+ (partition, trigger, handle.converge(partition).await)
+ }));
+ }
+
+ for partition in initial {
+ // Seed convergence carries Event severity: a pod that cannot
+ // establish its local state at loop start must not serve.
+ dispatch(
+ self,
+ partition,
+ Trigger::Event,
+ &mut in_flight,
+ &mut pending,
+ &mut lanes,
+ );
+ }
+
+ // Reconcile health is judged per tick window, keeping the budget
+ // at the pass granularity it was sized for: a window where any
+ // reconcile-triggered convergence failed — or whose own
+ // durable-state snapshot failed — counts exactly one failure, so
+ // a single partition persistently failing (a bad warm, say)
+ // still exhausts the budget even while its neighbors converge
+ // fine, while one blip failing several things at once cannot
+ // burn the budget faster than real time. A window of only
+ // successes resets the count; a window with no completed
+ // reconcile convergence at all (one still in flight across the
+ // tick) is neutral.
let mut consecutive_reconcile_failures: u32 = 0;
+ let mut window_err: Option<Error> = None;
+ let mut window_ok = false;
+
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,
+ // One budget count per tick at most, no matter how
+ // many things failed inside its window: the budget is
+ // sized in passes, and a single blip failing both a
+ // convergence and the following snapshot is one
+ // failed pass, not two.
+ let mut tick_err: Option<Error> = window_err.take();
+ if tick_err.is_none() && window_ok {
+ consecutive_reconcile_failures = 0;
+ }
+ window_ok = false;
+
+ // List failures are 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.involved_partitions().await {
+ Ok((partitions, _)) => {
+ for partition in partitions {
+ dispatch(
+ self,
+ partition,
+ Trigger::Reconcile,
+ &mut in_flight,
+ &mut pending,
+ &mut lanes,
+ );
+ }
+ }
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);
+ if tick_err.is_none() {
+ tick_err = Some(e);
+ } else {
+ tracing::warn!(
+ pod = %self.config.pod_name,
+ error = %e,
+ "durable-state snapshot failed in an already-failed window"
+ );
}
}
}
+
+ if let Some(e) = tick_err {
+ 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()))?;
@@ -730,19 +849,67 @@ impl PodHandle {
},
EventType::Delete => event
.kv()
- .and_then(|kv| std::str::from_utf8(kv.key()).ok())
+ .and_then(|kv| from_utf8(kv.key()).ok())
.and_then(store::extract_partition_from_key),
};
if let Some(partition) = partition {
- self.converge(partition).await?;
+ dispatch(
+ self,
+ partition,
+ Trigger::Event,
+ &mut in_flight,
+ &mut pending,
+ &mut lanes,
+ );
}
}
}
+ Some((partition, trigger, result)) = lanes.next(), if !lanes.is_empty() => {
+ in_flight.remove(&partition);
+ match result {
+ Ok(()) => {
+ if trigger == Trigger::Reconcile {
+ window_ok = true;
+ }
+ }
+ Err(e) => match trigger {
+ // The pod was told about a specific durable
+ // transition and cannot honor it; serving on
+ // regardless would hold the handoff hostage
+ // with no signal to the coordinator.
+ Trigger::Event => return Err(e),
+ Trigger::Reconcile => {
+ tracing::warn!(
+ pod = %self.config.pod_name,
+ partition,
+ error = %e,
+ "reconcile-triggered convergence failed"
+ );
+ window_err = Some(e);
+ }
+ },
+ }
+ if let Some(next) = pending.remove(&partition) {
+ dispatch(self, partition, next, &mut in_flight, &mut pending, &mut lanes);
+ }
+ }
}
}
}
}
+/// Why a convergence was dispatched — decides what its failure means.
+/// Event-driven convergence (including the seed at loop start) failing is
+/// fatal to the run: the pod cannot honor a specific durable transition
+/// it was told about. Reconcile-tick convergence failing is tolerated
+/// under the reconcile failure budget: the pod is merely as stale as one
+/// tick, and the next pass compensates.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Trigger {
+ Event,
+ Reconcile,
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/rust/personhog-coordination/tests/common/mod.rs b/rust/personhog-coordination/tests/common/mod.rs
index f188396e4983..7b743693dfad 100644
--- a/rust/personhog-coordination/tests/common/mod.rs
+++ b/rust/personhog-coordination/tests/common/mod.rs
@@ -1,11 +1,13 @@
#![allow(dead_code)]
-use std::future::Future;
-use std::sync::Arc;
-use std::time::Duration;
+use std::collections::{HashMap, HashSet};
+use std::future::{pending, Future};
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex as StdMutex, RwLock as StdRwLock};
+use std::time::{Duration, Instant};
use async_trait::async_trait;
-use tokio::sync::Mutex;
+use tokio::sync::{Mutex, Notify, RwLock};
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
@@ -61,7 +63,7 @@ where
F: Fn() -> Fut,
Fut: Future<Output = bool>,
{
- let start = std::time::Instant::now();
+ let start = Instant::now();
while start.elapsed() < timeout {
if f().await {
return;
@@ -261,8 +263,8 @@ pub fn start_pod_slow(
pub struct RouterHandles {
pub events: Arc<Mutex<Vec<CutoverEvent>>>,
- pub addresses: Arc<std::sync::RwLock<std::collections::HashMap<String, String>>>,
- pub table: Arc<tokio::sync::RwLock<std::collections::HashMap<u32, String>>>,
+ pub addresses: Arc<StdRwLock<HashMap<String, String>>>,
+ pub table: Arc<RwLock<HashMap<u32, String>>>,
pub join_handle: Option<JoinHandle<Result<()>>>,
}
@@ -399,7 +401,7 @@ impl HandoffHandler for BlockingHandoffHandler {
async fn warm_partition(&self, _partition: u32) -> Result<()> {
// Block forever — simulates a slow warm that never completes
- std::future::pending().await
+ pending().await
}
async fn release_partition(&self, partition: u32) -> Result<()> {
@@ -419,6 +421,155 @@ impl HandoffHandler for BlockingHandoffHandler {
}
}
+/// Per-partition gates for `GatedWarmHandler`: a warm parks until its
+/// partition's gate opens, giving tests deterministic control over which
+/// warms are in flight at once. A gate stays open once opened.
+#[derive(Clone, Default)]
+pub struct WarmGates {
+ open: Arc<StdMutex<HashSet<u32>>>,
+ notify: Arc<Notify>,
+}
+
+impl WarmGates {
+ pub fn open(&self, partition: u32) {
+ self.open.lock().unwrap().insert(partition);
+ self.notify.notify_waiters();
+ }
+
+ async fn wait_open(&self, partition: u32) {
+ loop {
+ let notified = self.notify.notified();
+ if self.open.lock().unwrap().contains(&partition) {
+ return;
+ }
+ notified.await;
+ }
+ }
+}
+
+/// A handoff handler whose warms park on per-partition gates while
+/// recording how many warms run concurrently — in total and for the same
+/// partition. Drives the convergence-lane tests: the gates prove
+/// cross-partition parallelism and the warm-slot bound, and the
+/// same-partition maximum pins single-flight convergence.
+pub struct GatedWarmHandler {
+ pub events: Arc<Mutex<Vec<HandoffEvent>>>,
+ pub gates: WarmGates,
+ pub warms_in_flight: Arc<StdMutex<HashMap<u32, usize>>>,
+ pub max_concurrent_warms: Arc<AtomicUsize>,
+ pub max_concurrent_same_partition: Arc<AtomicUsize>,
+}
+
+impl GatedWarmHandler {
+ pub fn new() -> Self {
+ Self {
+ events: Arc::new(Mutex::new(Vec::new())),
+ gates: WarmGates::default(),
+ warms_in_flight: Arc::new(StdMutex::new(HashMap::new())),
+ max_concurrent_warms: Arc::new(AtomicUsize::new(0)),
+ max_concurrent_same_partition: Arc::new(AtomicUsize::new(0)),
+ }
+ }
+}
+
+#[async_trait]
+impl HandoffHandler for GatedWarmHandler {
+ async fn drain_partition_inflight(&self, partition: u32) -> Result<()> {
+ self.events
+ .lock()
+ .await
+ .push(HandoffEvent::Drained(partition));
+ Ok(())
+ }
+
+ async fn warm_partition(&self, partition: u32) -> Result<()> {
+ {
+ let mut in_flight = self.warms_in_flight.lock().unwrap();
+ *in_flight.entry(partition).or_insert(0) += 1;
+ let total: usize = in_flight.values().sum();
+ self.max_concurrent_warms.fetch_max(total, Ordering::SeqCst);
+ self.max_concurrent_same_partition
+ .fetch_max(in_flight[&partition], Ordering::SeqCst);
+ }
+ self.gates.wait_open(partition).await;
+ *self
+ .warms_in_flight
+ .lock()
+ .unwrap()
+ .get_mut(&partition)
+ .unwrap() -= 1;
+ self.events
+ .lock()
+ .await
+ .push(HandoffEvent::Warmed(partition));
+ Ok(())
+ }
+
+ async fn release_partition(&self, partition: u32) -> Result<()> {
+ self.events
+ .lock()
+ .await
+ .push(HandoffEvent::Released(partition));
+ Ok(())
+ }
+
+ async fn resume_partition(&self, partition: u32) -> Result<()> {
+ self.events
+ .lock()
+ .await
+ .push(HandoffEvent::Resumed(partition));
+ Ok(())
+ }
+}
+
+pub struct GatedPodHandles {
+ pub events: Arc<Mutex<Vec<HandoffEvent>>>,
+ pub gates: WarmGates,
+ pub warms_in_flight: Arc<StdMutex<HashMap<u32, usize>>>,
+ pub max_concurrent_warms: Arc<AtomicUsize>,
+ pub max_concurrent_same_partition: Arc<AtomicUsize>,
+ pub join_handle: JoinHandle<Result<()>>,
+}
+
+/// Start a pod backed by a `GatedWarmHandler` with the given warm
+/// concurrency bound.
+pub fn start_pod_gated(
+ store: Arc<PersonhogStore>,
+ name: &str,
+ warm_concurrency: usize,
+ cancel: CancellationToken,
+) -> GatedPodHandles {
+ let handler = GatedWarmHandler::new();
+ let events = Arc::clone(&handler.events);
+ let gates = handler.gates.clone();
+ let warms_in_flight = Arc::clone(&handler.warms_in_flight);
+ let max_concurrent_warms = Arc::clone(&handler.max_concurrent_warms);
+ let max_concurrent_same_partition = Arc::clone(&handler.max_concurrent_same_partition);
+ let pod = PodHandle::new(
+ store,
+ PodConfig {
+ pod_name: name.to_string(),
+ warm_concurrency,
+ // 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),
+ None,
+ );
+ let token = cancel.child_token();
+ let join_handle = tokio::spawn(async move { pod.run(token).await });
+ GatedPodHandles {
+ events,
+ gates,
+ warms_in_flight,
+ max_concurrent_warms,
+ max_concurrent_same_partition,
+ join_handle,
+ }
+}
+
/// A handoff handler that adds a configurable delay to warm_partition.
/// Simulates a pod that takes time to warm its cache.
pub struct SlowHandoffHandler {
diff --git a/rust/personhog-coordination/tests/k3s_integration.rs b/rust/personhog-coordination/tests/k3s_integration.rs
index 87ef59359d4c..ab1590e32dca 100644
--- a/rust/personhog-coordination/tests/k3s_integration.rs
+++ b/rust/personhog-coordination/tests/k3s_integration.rs
@@ -682,6 +682,7 @@ async fn statefulset_rollout_pod_skips_drain() {
reconcile_interval: Duration::from_secs(86_400),
reconcile_failure_budget: 12,
advertise_address: None,
+ warm_concurrency: 4,
};
let (_pod_events, pod_handle) = start_pod_k8s(
Arc::clone(&store),
diff --git a/rust/personhog-coordination/tests/protocol_hardening.rs b/rust/personhog-coordination/tests/protocol_hardening.rs
index 2cf74e85e9f4..83756cbe1da7 100644
--- a/rust/personhog-coordination/tests/protocol_hardening.rs
+++ b/rust/personhog-coordination/tests/protocol_hardening.rs
@@ -10,6 +10,8 @@
mod common;
use std::collections::HashMap;
+use std::future::pending;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
@@ -19,7 +21,7 @@ use tokio_util::sync::CancellationToken;
use assignment_coordination::store::parse_watch_value;
use async_trait::async_trait;
use common::{
- revoke_lease_of_key, start_coordinator, start_coordinator_named, start_pod,
+ revoke_lease_of_key, start_coordinator, start_coordinator_named, start_pod, start_pod_gated,
start_pod_with_lease_ttl, start_router_with_lease_ttl, test_store, test_store_with_prefix,
wait_for_condition, CutoverEvent, HandoffEvent, MockCutoverHandler, POLL_INTERVAL,
WAIT_TIMEOUT,
@@ -1518,7 +1520,7 @@ impl StashHandler for BlockedDrainHandler {
partition,
target: target.to_string(),
});
- std::future::pending::<Result<()>>().await
+ pending::<Result<()>>().await
}
}
@@ -1637,7 +1639,7 @@ impl StashHandler for PartitionOneParker {
if partition == 0 {
return Ok(());
}
- std::future::pending::<Result<()>>().await
+ pending::<Result<()>>().await
}
async fn drain_stash(
@@ -1866,13 +1868,13 @@ async fn the_reconcile_pass_reasserts_freeze_acks() {
/// it for every non-terminal handoff before writing the freeze ack.
struct FlakyCutoverHandler {
events: Arc<Mutex<Vec<CutoverEvent>>>,
- fail: Arc<std::sync::atomic::AtomicBool>,
+ fail: Arc<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) {
+ if self.fail.load(Ordering::SeqCst) {
return Err(personhog_coordination::error::Error::invalid_state(
"injected begin_stash failure".to_string(),
));
@@ -1905,7 +1907,7 @@ async fn start_flaky_router(
store: &Arc<PersonhogStore>,
router_name: &str,
budget: u32,
-) -> (Arc<std::sync::atomic::AtomicBool>, CancellationToken) {
+) -> (Arc<AtomicBool>, CancellationToken) {
assert!(store
.create_assignments_and_handoffs(
&[PartitionAssignment {
@@ -1930,7 +1932,7 @@ async fn start_flaky_router(
..RoutingTableConfig::default()
},
);
- let fail = Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let fail = Arc::new(AtomicBool::new(false));
let handler = FlakyCutoverHandler {
events: Arc::new(Mutex::new(Vec::new())),
fail: Arc::clone(&fail),
@@ -1969,7 +1971,7 @@ async fn reconcile_failures_within_budget_are_tolerated_and_heal() {
// 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);
+ fail.store(true, Ordering::SeqCst);
let mut raw = etcd_client::Client::connect(["http://localhost:2379"], None)
.await
.expect("raw client");
@@ -1995,7 +1997,7 @@ async fn reconcile_failures_within_budget_are_tolerated_and_heal() {
);
// Recovery: the next successful pass re-asserts the ack.
- fail.store(false, std::sync::atomic::Ordering::SeqCst);
+ fail.store(false, Ordering::SeqCst);
wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, || {
ack_present(Arc::clone(&store))
})
@@ -2027,7 +2029,7 @@ async fn reconcile_failures_past_the_budget_fail_the_run() {
})
.await;
- fail.store(true, std::sync::atomic::Ordering::SeqCst);
+ fail.store(true, Ordering::SeqCst);
// Three failed passes exhaust the budget; the run's teardown
// deregisters the router.
@@ -2153,3 +2155,202 @@ async fn the_reconcile_pass_skips_drains_for_settled_partitions() {
cancel.cancel();
}
+
+// ============================================================
+// Convergence lanes: partitions converge concurrently,
+// single-flight per partition
+// ============================================================
+//
+// The pod's watch loop runs convergence single-flight per partition but
+// concurrently across partitions. A deploy moving several partitions
+// onto one pod must warm them in parallel — serialized warming is what
+// made stash waits scale with the number of simultaneous inbound
+// handoffs — while two convergences for the same partition must never
+// interleave (concurrent warms for one partition could install a stale
+// cache over a fresh one).
+
+/// Variant of `put_handoff` with an explicit handoff id, for forcing a
+/// re-warm: a warm installed for one handoff id does not satisfy a later
+/// handoff with a different id.
+async fn put_handoff_with_id(
+ store: &PersonhogStore,
+ partition: u32,
+ new_owner: &str,
+ phase: HandoffPhase,
+ handoff_id: &str,
+) {
+ let handoff = HandoffState {
+ partition,
+ old_owner: None,
+ new_owner: new_owner.to_string(),
+ phase,
+ started_at: 0,
+ handoff_id: handoff_id.to_string(),
+ freeze_quorum: None,
+ created_at_ms: 0,
+ phase_entered_at_ms: 0,
+ new_owner_address: None,
+ };
+ store.put_handoff(&handoff).await.expect("write handoff");
+}
+
+/// Wait until the pod has a warmed ack for the partition in etcd.
+async fn wait_for_warmed_ack(store: &Arc<PersonhogStore>, partition: u32, pod: &str) {
+ let check_store = Arc::clone(store);
+ let pod = pod.to_string();
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, move || {
+ let store = Arc::clone(&check_store);
+ let pod = pod.clone();
+ async move {
+ store
+ .list_warmed_acks(partition)
+ .await
+ .map(|acks| acks.iter().any(|a| a.pod_name == pod))
+ .unwrap_or(false)
+ }
+ })
+ .await;
+}
+
+/// With one partition's warm parked, another partition's handoff must
+/// still warm and ack. Serialized convergence would queue the second
+/// warm behind the parked one and its ack would never arrive.
+#[tokio::test]
+async fn concurrent_inbound_handoffs_warm_in_parallel() {
+ let store = test_store("pod-parallel-warm").await;
+ let cancel = CancellationToken::new();
+
+ let pod = start_pod_gated(Arc::clone(&store), "parallel-warm-pod", 4, cancel.clone());
+
+ put_handoff(&store, 0, None, "parallel-warm-pod", HandoffPhase::Warming).await;
+ put_handoff(&store, 1, None, "parallel-warm-pod", HandoffPhase::Warming).await;
+
+ // Partition 0 stays parked; partition 1 must complete regardless.
+ pod.gates.open(1);
+ wait_for_warmed_ack(&store, 1, "parallel-warm-pod").await;
+
+ // The parked warm really is still parked — nothing acked for it.
+ let acks = store.list_warmed_acks(0).await.expect("list acks");
+ assert!(
+ acks.is_empty(),
+ "partition 0's warm is parked; its ack must not exist yet"
+ );
+
+ pod.gates.open(0);
+ wait_for_warmed_ack(&store, 0, "parallel-warm-pod").await;
+
+ cancel.cancel();
+}
+
+/// Two convergences for the same partition must never run concurrently,
+/// even when a new handoff arrives while the partition's warm is parked.
+/// The second handoff (a different id, so it demands its own warm) must
+/// wait for the first convergence to finish, then re-warm.
+#[tokio::test]
+async fn convergences_for_one_partition_never_interleave() {
+ let store = test_store("pod-single-flight").await;
+ let cancel = CancellationToken::new();
+
+ let pod = start_pod_gated(Arc::clone(&store), "single-flight-pod", 4, cancel.clone());
+
+ put_handoff_with_id(
+ &store,
+ 0,
+ "single-flight-pod",
+ HandoffPhase::Warming,
+ "era-a",
+ )
+ .await;
+
+ // Wait until the first warm is parked inside the handler.
+ let in_flight = Arc::clone(&pod.warms_in_flight);
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, move || {
+ let in_flight = Arc::clone(&in_flight);
+ async move { in_flight.lock().unwrap().get(&0).copied() == Some(1) }
+ })
+ .await;
+
+ // A new era for the same partition while the warm is parked. The
+ // convergence for it must coalesce behind the in-flight one, not
+ // start a second concurrent warm.
+ put_handoff_with_id(
+ &store,
+ 0,
+ "single-flight-pod",
+ HandoffPhase::Warming,
+ "era-b",
+ )
+ .await;
+
+ pod.gates.open(0);
+
+ // The era-b convergence releases the era-a warm and re-warms; two
+ // Warmed events mark both warms having completed.
+ let events = Arc::clone(&pod.events);
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, move || {
+ let events = Arc::clone(&events);
+ async move {
+ events
+ .lock()
+ .await
+ .iter()
+ .filter(|e| **e == HandoffEvent::Warmed(0))
+ .count()
+ == 2
+ }
+ })
+ .await;
+
+ assert_eq!(
+ pod.max_concurrent_same_partition.load(Ordering::SeqCst),
+ 1,
+ "convergences for one partition must never overlap"
+ );
+
+ cancel.cancel();
+}
+
+/// Concurrent warms are bounded by `warm_concurrency`: with the bound at
+/// 2 and four inbound handoffs parked, exactly two warms enter the
+/// handler; the rest queue on the semaphore until a slot frees.
+#[tokio::test]
+async fn concurrent_warms_are_bounded_by_warm_concurrency() {
+ let store = test_store("pod-warm-bound").await;
+ let cancel = CancellationToken::new();
+
+ let pod = start_pod_gated(Arc::clone(&store), "warm-bound-pod", 2, cancel.clone());
+
+ for partition in 0..4 {
+ put_handoff(
+ &store,
+ partition,
+ None,
+ "warm-bound-pod",
+ HandoffPhase::Warming,
+ )
+ .await;
+ }
+
+ // Both slots fill and park; the other two handoffs wait on the bound.
+ let in_flight = Arc::clone(&pod.warms_in_flight);
+ wait_for_condition(WAIT_TIMEOUT, POLL_INTERVAL, move || {
+ let in_flight = Arc::clone(&in_flight);
+ async move { in_flight.lock().unwrap().values().sum::<usize>() == 2 }
+ })
+ .await;
+
+ for partition in 0..4 {
+ pod.gates.open(partition);
+ }
+ for partition in 0..4 {
+ wait_for_warmed_ack(&store, partition, "warm-bound-pod").await;
+ }
+
+ assert_eq!(
+ pod.max_concurrent_warms.load(Ordering::SeqCst),
+ 2,
+ "warms in the handler at once must equal the configured bound"
+ );
+
+ cancel.cancel();
+}