: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(personhog): stash retries (#74325)
Zach Brown3e307fabec42
diff --git a/.agents/skills/adding-personhog-rpc/SKILL.md b/.agents/skills/adding-personhog-rpc/SKILL.mdindex 33e9cd59c841..b3b3009dc3b9 100644--- a/.agents/skills/adding-personhog-rpc/SKILL.md+++ b/.agents/skills/adding-personhog-rpc/SKILL.md@@ -59,6 +59,19 @@ See [references/proto-conventions.md](references/proto-conventions.md) for messaThe service and replica protos must both declare the RPC with identical signature.The router delegates from service → replica (or leader) transparently.+### Leader RPCs must be safe under at-least-once delivery++A leader-path request can be delivered more than once: clients retry `UNAVAILABLE` after ambiguous failures,+and the router internally replays fence- and transport-bounced requests.+Every leader RPC must therefore converge under redelivery —+read-only lookups, merges that re-apply to the same state, tombstone-style deletes, max-merge version floors —+or carry explicit operation identity so duplicates can be detected.+Note the precise contract: a convergent merge still loses to interleaving+(a replay can clobber a same-field write another caller made in between);+that residual is accepted today and closes with operation identity (see `personhog-leader`'s README).+An RPC that neither converges nor carries identity (an unguarded increment, an append) must not be added.+If the operation you need fits neither shape, redesign it to carry an idempotency key before defining the proto.+## Step 2: generate client stubs### Python@@ -140,6 +153,7 @@ cargo test -p personhog-router- [ ] Query uses an existing index (no seq scans)- [ ] Proto messages added to `types/v1/<domain>.proto`- [ ] RPC added to both `service.proto` and `replica.proto` (and `leader.proto` if needed)+- [ ] Leader RPCs only: operation is safe under at-least-once delivery (convergent under redelivery — read-only, re-appliable merge, tombstone, max-merge — or carries explicit operation identity)- [ ] Python stubs generated, `proto/__init__.py` updated, `client.py` method added, `fake_client.py` updated- [ ] Node.js stubs generated, `client.test.ts` SERVICE_DEFAULTS updated- [ ] Rust storage trait + postgres impl + service handler + router wiring all implementeddiff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 595da6b1352c..845f3c573174 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -6606,6 +6606,13 @@ dependencies = ["uuid",]+[[package]]+name = "keyed-stash"+version = "0.1.0"+dependencies = [+ "proptest",+]+[[package]]name = "kube"version = "0.98.0"@@ -8589,6 +8596,7 @@ dependencies = ["http-body 1.0.1","http-body-util","k8s-awareness",+ "keyed-stash","kube","lifecycle","metrics",diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex a89bb7ac17cd..7f5f64bd8721 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -14,6 +14,7 @@ members = ["common/alloc","common/assignment-coordination","common/k8s-awareness",+ "common/keyed-stash","common/cache","common/cookieless","common/database",diff --git a/rust/common/keyed-stash/Cargo.toml b/rust/common/keyed-stash/Cargo.tomlnew file mode 100644index 000000000000..41f164ea4285--- /dev/null+++ b/rust/common/keyed-stash/Cargo.toml@@ -0,0 +1,11 @@+[package]+name = "keyed-stash"+version = "0.1.0"+edition = "2021"+publish = false++[dev-dependencies]+proptest = "1"++[lints]+workspace = truediff --git a/rust/common/keyed-stash/src/lib.rs b/rust/common/keyed-stash/src/lib.rsnew file mode 100644index 000000000000..ff3b12f9b70f--- /dev/null+++ b/rust/common/keyed-stash/src/lib.rs@@ -0,0 +1,285 @@+//! Per-key ordered deferral, extracted from the shape proven in+//! `ingestion-consumer`'s stash and adopted by the personhog router's.+//!+//! Both services face the same problem one layer apart: work is pinned to+//! a key-sticky target (a worker, an owner pod) that is temporarily+//! unroutable, and per-key ordering must survive the outage — including+//! across *failed delivery attempts*. The queue makes that survivable by+//! construction rather than by choreography:+//!+//! - Every entry is stamped with a monotonic sequence at admission, so an+//! entry's position is a property of the entry, not of queue physics. A+//! failed attempt cannot corrupt order because putting an entry back+//! restores it to its sequence position.+//! - Entries leave only through [`KeyedStash::complete`] — a+//! definitive outcome. An attempt that cannot finish puts its entries+//! back and they will be re-attempted first, in order.+//! - [`KeyedStash::is_deferring`] is the outstanding gate: while a+//! key has queued or in-attempt entries, new work for that key must be+//! deferred behind them — never sent directly — or it would race ahead+//! of the backlog.+//!+//! Deliberately single-owner (`&mut self`) and free of I/O, locking, and+//! policy: callers wrap it in their own concurrency envelope and layer+//! their own admission bounds, batch accounting, or reply plumbing on+//! top, exactly as the two existing stashes do.++use std::collections::{HashMap, VecDeque};+use std::hash::Hash;++/// One deferred entry: the caller's item plus the admission-order stamp+/// that fixes its position among its key's entries forever.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Entry<T> {+ pub seq: u64,+ pub item: T,+}++/// A per-key ordered deferral queue. See the crate docs for the contract.+#[derive(Debug)]+pub struct KeyedStash<K, T> {+ queues: HashMap<K, VecDeque<Entry<T>>>,+ /// Per key: entries taken for an attempt and not yet completed or put+ /// back. Counted so `is_deferring` covers in-flight work, not just+ /// queued work.+ in_attempt: HashMap<K, usize>,+ next_seq: u64,+ len: usize,+}++impl<K, T> Default for KeyedStash<K, T> {+ fn default() -> Self {+ Self {+ queues: HashMap::new(),+ in_attempt: HashMap::new(),+ next_seq: 0,+ len: 0,+ }+ }+}++impl<K: Eq + Hash + Clone, T> KeyedStash<K, T> {+ pub fn new() -> Self {+ Self::default()+ }++ /// Defer `item` behind everything already deferred for `key`.+ /// Returns the entry's sequence stamp.+ pub fn push(&mut self, key: K, item: T) -> u64 {+ let seq = self.next_seq;+ self.next_seq += 1;+ self.queues+ .entry(key)+ .or_default()+ .push_back(Entry { seq, item });+ self.len += 1;+ seq+ }++ /// Whether new work for `key` must be deferred: the key has queued+ /// entries, or entries taken for an attempt whose outcome is not yet+ /// known. Sending new work directly while this holds would let it+ /// race ahead of the key's backlog.+ pub fn is_deferring(&self, key: &K) -> bool {+ self.in_attempt.get(key).is_some_and(|n| *n > 0)+ || self.queues.get(key).is_some_and(|q| !q.is_empty())+ }++ /// Take up to `max` entries from the front of `key`'s queue for a+ /// delivery attempt. The entries count as in-attempt until each is+ /// either [`complete`](Self::complete)d or returned via+ /// [`put_back`](Self::put_back); dropping them instead loses items+ /// and permanently latches `is_deferring` for the key.+ pub fn take_front(&mut self, key: &K, max: usize) -> Vec<Entry<T>> {+ let Some(queue) = self.queues.get_mut(key) else {+ return Vec::new();+ };+ let n = max.min(queue.len());+ let taken: Vec<Entry<T>> = queue.drain(..n).collect();+ if queue.is_empty() {+ self.queues.remove(key);+ }+ if !taken.is_empty() {+ *self.in_attempt.entry(key.clone()).or_default() += taken.len();+ self.len -= taken.len();+ }+ taken+ }++ /// Record a definitive outcome for one in-attempt entry of `key` —+ /// delivered, or failed in a way that was reported to its origin.+ /// The entry is gone; its successors may now be attempted.+ pub fn complete(&mut self, key: &K) {+ let count = self+ .in_attempt+ .get_mut(key)+ .expect("complete() without a matching take_front()");+ *count -= 1;+ if *count == 0 {+ self.in_attempt.remove(key);+ }+ }++ /// Return entries whose attempt was aborted before any outcome+ /// existed (supersession, a target that became unroutable). They+ /// re-enter at their sequence positions — ahead of everything+ /// admitted after them — so the next attempt sees them first, in+ /// order.+ pub fn put_back(&mut self, key: &K, entries: Vec<Entry<T>>) {+ if entries.is_empty() {+ return;+ }+ let count = self+ .in_attempt+ .get_mut(key)+ .expect("put_back() without a matching take_front()");+ *count -= entries.len();+ if *count == 0 {+ self.in_attempt.remove(key);+ }+ self.len += entries.len();+ let queue = self.queues.entry(key.clone()).or_default();+ // Taken entries always predate everything still queued, so they+ // belong at the front; restoring in reverse preserves their+ // internal order. The debug assertion pins the seq invariant the+ // fast path relies on.+ debug_assert!(+ queue+ .front()+ .is_none_or(|next| entries.last().is_none_or(|e| e.seq < next.seq)),+ "put_back entries must predate every queued entry"+ );+ for entry in entries.into_iter().rev() {+ queue.push_front(entry);+ }+ }++ /// Keys that currently have queued entries, in no particular order.+ /// In-attempt-only keys are excluded: their next attempt is decided+ /// by the outcome of the current one.+ pub fn keys_with_backlog(&self) -> impl Iterator<Item = &K> {+ self.queues.keys()+ }++ /// Total queued entries across all keys (in-attempt entries are not+ /// queued).+ pub fn len(&self) -> usize {+ self.len+ }++ pub fn is_empty(&self) -> bool {+ self.len == 0 && self.in_attempt.is_empty()+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use proptest::prelude::*;++ /// The outstanding gate covers both queued and in-attempt work: a key+ /// stays "deferring" from first push until the last outcome, never+ /// dropping out in between — the window where new work could race+ /// ahead of a retry.+ #[test]+ fn the_gate_holds_across_the_attempt_window() {+ let mut q: KeyedStash<u8, u32> = KeyedStash::new();+ assert!(!q.is_deferring(&1));++ q.push(1, 10);+ assert!(q.is_deferring(&1));++ let taken = q.take_front(&1, 8);+ assert_eq!(taken.len(), 1);+ assert!(q.is_deferring(&1), "in-attempt work must keep the gate up");++ q.put_back(&1, taken);+ assert!(q.is_deferring(&1));++ let taken = q.take_front(&1, 8);+ q.complete(&1);+ assert!(!q.is_deferring(&1));+ drop(taken);+ }++ /// Put-back restores aborted entries ahead of work admitted after+ /// them — the leapfrog case: a retry must never be overtaken by a+ /// newer same-key item.+ #[test]+ fn put_back_precedes_later_admissions() {+ let mut q: KeyedStash<u8, &str> = KeyedStash::new();+ q.push(1, "a");+ q.push(1, "b");+ let taken = q.take_front(&1, 2);+ q.push(1, "c");+ q.put_back(&1, taken);++ let order: Vec<&str> = q.take_front(&1, 8).into_iter().map(|e| e.item).collect();+ assert_eq!(order, vec!["a", "b", "c"]);+ }++ /// Model-based property check: against an arbitrary interleaving of+ /// push / take / complete / put_back across several keys, delivery+ /// order per key equals admission order per key (completions observe+ /// strictly increasing seqs), and every admitted item is exactly once+ /// delivered or still held. This is the invariant that makes internal+ /// retry safe to build on top.+ #[derive(Debug, Clone)]+ enum Op {+ Push { key: u8 },+ AttemptDeliver { key: u8, max: u8 },+ AttemptAbort { key: u8, max: u8 },+ }++ fn op_strategy() -> impl Strategy<Value = Op> {+ prop_oneof![+ (0u8..4).prop_map(|key| Op::Push { key }),+ (0u8..4, 1u8..5).prop_map(|(key, max)| Op::AttemptDeliver { key, max }),+ (0u8..4, 1u8..5).prop_map(|(key, max)| Op::AttemptAbort { key, max }),+ ]+ }++ proptest! {+ #[test]+ fn per_key_order_and_conservation_hold(ops in proptest::collection::vec(op_strategy(), 1..120)) {+ let mut q: KeyedStash<u8, u64> = KeyedStash::new();+ let mut admitted: HashMap<u8, u64> = HashMap::new();+ let mut delivered: HashMap<u8, Vec<u64>> = HashMap::new();+ let mut admitted_total = 0u64;++ for op in ops {+ match op {+ Op::Push { key } => {+ let n = admitted.entry(key).or_default();+ q.push(key, *n);+ *n += 1;+ admitted_total += 1;+ }+ Op::AttemptDeliver { key, max } => {+ let taken = q.take_front(&key, max as usize);+ let mut last_seq = None;+ for entry in taken {+ prop_assert!(last_seq.is_none_or(|s| s < entry.seq));+ last_seq = Some(entry.seq);+ delivered.entry(key).or_default().push(entry.item);+ q.complete(&key);+ }+ }+ Op::AttemptAbort { key, max } => {+ let taken = q.take_front(&key, max as usize);+ q.put_back(&key, taken);+ }+ }+ }++ // Per-key delivery order == admission order.+ for (key, items) in &delivered {+ let expected: Vec<u64> = (0..items.len() as u64).collect();+ prop_assert_eq!(items, &expected, "key {} delivered out of order", key);+ }+ // Conservation: everything admitted is delivered or still queued.+ let delivered_total: usize = delivered.values().map(Vec::len).sum();+ prop_assert_eq!(delivered_total + q.len(), admitted_total as usize);+ }+ }+}diff --git a/rust/personhog-coordination/README.md b/rust/personhog-coordination/README.mdindex 4f25ef2de07a..ba2f9bbed659 100644--- a/rust/personhog-coordination/README.md+++ b/rust/personhog-coordination/README.md@@ -98,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. 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. |+| `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; observing a non-terminal phase pauses the lane, and an interrupted drain puts its in-flight requests back rather than failing them); 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/routing_table.rs b/rust/personhog-coordination/src/routing_table.rsindex 0a198dcd6c84..52c7fb3e2241 100644--- a/rust/personhog-coordination/src/routing_table.rs+++ b/rust/personhog-coordination/src/routing_table.rs@@ -29,8 +29,10 @@ pub trait StashHandler: Send + Sync {/// Drain stashed writes to the given target and resume normal routing./// `cancel` requests a cooperative stop: implementations yield at a- /// batch boundary, leaving any remaining stash intact for a successor- /// drain.+ /// request boundary, putting anything they had taken back so the full+ /// remaining stash stays parked, in order, for a successor drain.+ /// Cancellation is a routing decision, never a request outcome — no+ /// client-visible failure may result from it.async fn drain_stash(&self,partition: u32,@@ -68,9 +70,13 @@ pub trait StashHandler: Send + Sync {/// 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+/// drain, whose loop already covers later arrivals. Observing a+/// non-terminal handoff phase pauses the lane: the running drain is+/// cancelled with no successor, so the partition stops forwarding until+/// the next `Complete` names a target — the ownership state, not the+/// drain, decides where parked requests go. 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@@ -107,12 +113,10 @@ impl DrainLanes {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.+ // this request would: its loop keeps taking runs until it observes+ // the queue fully settled, including arrivals after this point.+ // Restarting it would only churn — cancel, put back, re-take the+ // same backlog — for no coverage gain.if let Some(prev) = lanes.get(&partition) {if prev.target == target && !prev.token.is_cancelled() && !prev.handle.is_finished() {return;@@ -147,6 +151,38 @@ impl DrainLanes {},);}++ /// Pause the drain for `partition`, if one is running: cancel its+ /// token without starting a successor. The drain puts anything it+ /// had taken back and exits, leaving the stash parked. Called when a+ /// non-terminal handoff phase is observed — the partition is+ /// (re-)entering a stash window, and nothing may be forwarded until+ /// the next `Complete` names the target. Idempotent; a later+ /// `request` supersedes the paused lane.+ fn pause(&self, partition: u32) {+ let lanes = self.lanes.lock().expect("drain lanes lock poisoned");+ if let Some(lane) = lanes.get(&partition) {+ lane.token.cancel();+ }+ }++ /// Cancel every lane and await the drains' termination. Runs during+ /// teardown, after the watch loop (the only source of new requests)+ /// has stopped and before the router's lease is revoked: the lease+ /// must outlive the last forward. Joining is quick — cancellation+ /// stops each drain within one in-flight request — and joining the+ /// newest handle per partition transitively joins its predecessors,+ /// which each successor task awaits before starting.+ async fn shutdown(&self) {+ self.cancel.cancel();+ let handles: Vec<JoinHandle<()>> = {+ let mut lanes = self.lanes.lock().expect("drain lanes lock poisoned");+ lanes.drain().map(|(_, lane)| lane.handle).collect()+ };+ for handle in handles {+ drop(handle.await);+ }+ }}/// Configuration for the routing table.@@ -371,12 +407,13 @@ 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();+ // Drain lanes get their own token, torn down 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. The+ // handle is held here, not just inside the watch loop, so the+ // teardown can join the lane tasks rather than merely signal them.+ let lanes = Arc::new(DrainLanes::new(cancel.child_token()));{let store = Arc::clone(&self.store);@@ -384,7 +421,7 @@ impl RoutingTable {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 lanes = Arc::clone(&lanes);let last_progress = Arc::clone(&last_progress);let reconcile_interval = self.config.reconcile_interval;let reconcile_failure_budget = self.config.reconcile_failure_budget;@@ -416,10 +453,19 @@ impl RoutingTable {}};- // Abort and await all remaining tasks for clean shutdown, and stop- // any in-flight drains at their next batch boundary.+ // Abort and await all remaining tasks first — the watch loop is+ // the only source of new drain requests, so once it is gone the+ // lane set is final and can be joined.tasks.shutdown().await;- lanes_cancel.cancel();++ // Cancel and JOIN every drain before touching the lease: the+ // lease must outlive the last forward, so anything a drain+ // delivered happened while this router was still a legitimately+ // registered participant. Signalling without joining would let+ // drains keep forwarding past deregistration, stretching the+ // zombie-router window beyond the lease bound the protocol's+ // residual analysis relies on.+ lanes.shutdown().await;// Deregister so freeze quorums stop counting this router// immediately. Left to lease expiry, every handoff frozen in the@@ -734,6 +780,7 @@ impl RoutingTable {constrained.insert(handoff.partition);match handoff.phase {HandoffPhase::Freezing | HandoffPhase::Draining | HandoffPhase::Warming => {+ lanes.pause(handoff.partition);handler.begin_stash(handoff.partition, &handoff.new_owner).await?;@@ -834,6 +881,13 @@ impl RoutingTable {phase = ?handoff.phase,"beginning stash");+ // A drain still running from the previous ownership era+ // must stop before this partition re-enters the stash+ // window: pausing the lane makes the running drain put+ // its in-flight entries back, so they park behind+ // nothing and drain to whatever owner the next+ // `Complete` names.+ lanes.pause(handoff.partition);handler.begin_stash(handoff.partition, &handoff.new_owner).await?;@@ -980,10 +1034,10 @@ mod tests {}/// 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.+ /// the drain: the running loop covers all arrivals — including the+ /// routine post-`Complete` cleanup deletion that drains back to the+ /// same owner the table just flipped to — and restarting it would+ /// only churn the same backlog.#[tokio::test]async fn a_same_target_request_does_not_supersede_the_running_drain() {let (lanes, handler, mut rx) = parking_lanes();@@ -1000,4 +1054,52 @@ mod tests {assert_eq!(rx.recv().await.unwrap(), "stop:a");assert_eq!(rx.recv().await.unwrap(), "start:b");}++ /// Teardown must JOIN drains, not merely signal them: `shutdown`+ /// returns only after every lane task has observed cancellation and+ /// exited, so the caller can revoke the router's lease knowing no+ /// forward happens after it. Signalling without joining would leave+ /// detached drains forwarding for a deregistered router.+ #[tokio::test]+ async fn shutdown_joins_running_drains_before_returning() {+ let (lanes, handler, mut rx) = parking_lanes();++ lanes.request(Arc::clone(&handler), "r".into(), 0, "a".into());+ lanes.request(handler, "r".into(), 1, "b".into());+ let starts = [rx.recv().await.unwrap(), rx.recv().await.unwrap()];+ assert!(starts.contains(&"start:a".to_string()));+ assert!(starts.contains(&"start:b".to_string()));++ lanes.shutdown().await;++ // Both drains exited before shutdown returned — their stop+ // events must already be in the channel, no further waiting.+ let mut stops = [rx.try_recv().unwrap(), rx.try_recv().unwrap()];+ stops.sort();+ assert_eq!(stops, ["stop:a".to_string(), "stop:b".to_string()]);+ }++ /// Observing a non-terminal handoff phase pauses the lane: the+ /// running drain is cancelled with no successor, so nothing forwards+ /// while the partition re-enters its stash window. Only the next+ /// `Complete`'s request may start a fresh drain, toward whatever+ /// owner it names.+ #[tokio::test]+ async fn a_pause_stops_the_drain_without_starting_a_successor() {+ 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.pause(0);+ assert_eq!(rx.recv().await.unwrap(), "stop:a");+ assert!(+ rx.try_recv().is_err(),+ "pause must not start a successor drain"+ );++ // The next Complete re-requests; the paused lane is superseded.+ lanes.request(handler, "r".into(), 0, "b".into());+ assert_eq!(rx.recv().await.unwrap(), "start:b");+ }}diff --git a/rust/personhog-leader/README.md b/rust/personhog-leader/README.mdindex 7351bfea43db..74d76dea48e1 100644--- a/rust/personhog-leader/README.md+++ b/rust/personhog-leader/README.md@@ -9,6 +9,36 @@- pods can scale up and down without service disruptions or inconsistent writes- crashed pods can be recovered from with minimal downtime+### API contract: every RPC must be safe under at-least-once delivery++A leader-path request can be delivered more than once: clients retry+`UNAVAILABLE` after ambiguous failures, and the router internally+replays fence- and transport-bounced requests. Neither layer can know+whether an ambiguous first delivery applied, so the safety burden sits+here, on the RPC's semantics — not in any retry policy.++Be precise about what "safe" means today. Reads are pure.+`UpdatePersonProperties` is a merge command with no request-level+identity: re-applying the same merge converges to the same state+*unless a different caller wrote the same field between the original+apply and the replay*, in which case the replay clobbers the newer+write. That interleaved case is the accepted at-least-once residual —+the exposure is identical under client-driven retries, which the+platform has always had — and its planned closure is operation+identity: the router stamps each logical request with an op id, the+leader keeps a short ring of recently applied ids on the cached person+entry, and the id rides the produced record so warming rebuilds the+ring on a new owner (scoped with the epoch-fencing work; the stamp and+the ring land together).++Future RPCs must clear the same bar: convergent under redelivery+(tombstone-style deletes, max-merge version floors, re-appliable+merges), or carrying explicit operation identity. An RPC that is+neither (an unguarded increment, an append) is broken in this+architecture regardless of router behavior and must not be added; this+is a review requirement for new leader RPCs (see the+`adding-personhog-rpc` skill).+### To Implement### Known Implementation Detailsdiff --git a/rust/personhog-router/Cargo.toml b/rust/personhog-router/Cargo.tomlindex 862bee654f79..27321465542b 100644--- a/rust/personhog-router/Cargo.toml+++ b/rust/personhog-router/Cargo.toml@@ -12,6 +12,7 @@ personhog-proto = { path = "../personhog-proto" }assignment-coordination = { path = "../common/assignment-coordination" }k8s-awareness = { path = "../common/k8s-awareness" }common-alloc = { path = "../common/alloc" }+keyed-stash = { path = "../common/keyed-stash" }metrics-exporter-prometheus = { workspace = true }lifecycle = { path = "../common/lifecycle" }kube = { version = "0.98", features = ["client", "runtime"] }diff --git a/rust/personhog-router/README.md b/rust/personhog-router/README.mdindex 07b7b70c34d9..b9b0a0c9bc30 100644--- a/rust/personhog-router/README.md+++ b/rust/personhog-router/README.md@@ -41,6 +41,30 @@ router holds a per-partition routing table fed by `personhog-coordination`'shandoff watch — the table flips to the new owner atomically with the handoffreaching `Complete`.+Every leader forward is a single classified attempt+(`LeaderBackend::forward_classified` — the one shared reading of leader+responses): a response the leader produced is *delivered* (success or error,+it's a real outcome, and an error like `UNAVAILABLE` is also the leader's+backpressure signal), while a fence rejection (`FAILED_PRECONDITION` — always+a routing race, never a client error), an unroutable partition (no assignment+or address known yet — nothing sent), or a transport failure *bounces* with no+outcome. There is no blind inner retry layer; retry policy lives in exactly+two places, both of which re-check routing state between attempts:++- **Live path** (`forward_or_stash`): a bounced request is held in its handler+ task and the loop re-enters from the stash check after a short backoff — so+ by the re-attempt it parks if a handoff opened a stash window, re-resolves+ if the table flipped, or re-sends if nothing changed. After a few+ consecutive bounces it fails with a definitive `UNAVAILABLE` (a router with+ a dead watch must not hold requests forever — the client's own retry can+ reach a healthier router). A transport bounce marks the request+ possibly-applied; any further forward of it is an at-least-once replay,+ counted by `personhog_router_stash_replayed_total` and covered by the+ redelivery contract in `personhog-leader`'s README. Clients never see+ `FAILED_PRECONDITION` from the leader path.+- **Drain path**: the wave loop described below, with put-back for position+ and the reconcile pass as its outer driver.+#### Stash and drain during partition handoffsPartition handoffs go through `Freezing → Draining → Warming → Complete`@@ -52,56 +76,78 @@ phases and replaying them once the handoff completes:the router registers the partition in its `StashTable` and writes a`RouterFreezeAck` (only during `Freezing`, when the freeze quorum isstill being collected). Subsequent writes for that partition are- parked on a `oneshot` instead of being forwarded.+ parked on a `oneshot` instead of being forwarded. Observing a+ non-terminal phase also pauses any drain still running for the+ partition from a previous ownership era: the drain puts what it had+ taken back and exits, so parked requests wait for whatever owner the+ next `Complete` names rather than draining toward a stale target.- **Drain** (on `Complete` — including the reaffirm-Complete acancellation resolves to): the router replays each parked request tothe 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:+ stash hook so each replayed request actually reaches the leader.+ Each partition's stash is a per-key deferral queue (the shared+ `keyed-stash` crate) keyed by `(team_id, person_id)`: entries are+ seq-stamped at admission and leave only through a definitive outcome+ delivered to their client; an attempt that cannot finish puts its+ entries back at their sequence positions, so a retry can never be+ overtaken by newer same-key work. New requests that arrive during+ drain land on the same queue and are picked up by a later take — the+ drain only evicts the partition from the stash table when it+ observes the queue fully settled (no queued and no in-attempt+ entries) under the lock, preserving per-key admission order 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 puts its in-flight entries back and stops, leaving the+ full backlog parked in order 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.++Every stashed request therefore ends in exactly one of two ways: a+definitive outcome delivered to its client, or a put-back that re-parks+it for a later attempt — a drain attempt failing to finish is never a+client-visible error. The policies layered on the mechanism:1. **Per-request deadline** (`STASH_MAX_WAIT_MS`, default 10 s): if astashed request waits longer than this, drain returns `UNAVAILABLE`to the original caller without forwarding. This caps client-perceivedlatency during long drains and gives clients a definitive retryable- error code instead of an ambiguous gRPC timeout.+ error code instead of an ambiguous gRPC timeout. This deadline is+ the only client-visible latency bound; pauses, bounces, and+ supersessions below never surface to callers.2. **Per-key concurrent forwarding** (`STASH_DRAIN_CONCURRENCY`,- default 32): each drain batch is grouped by `(team_id, person_id)`- and forwarded with up to that many keys in parallel. Within a key- the requests forward sequentially to preserve per-key ordering at- the leader; across keys the drain fans out to shrink wall-clock- drain duration.--3. **Fenced-leader remap**: a `FAILED_PRECONDITION` from the leader- during drain means the drain raced the target's write fence — the- old owner resuming after a cancelled handoff, or the new owner's- cutover — a transient coordination state, not a caller error.- Because `FAILED_PRECONDITION` reads as "do not retry" to clients,- drain remaps it to `UNAVAILABLE` so callers retry, consistent with- the deadline and bounds contracts above.--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.+ default 32): each drain wave takes up to that many keys' front runs+ and forwards them in parallel. Within a key the requests forward+ sequentially to preserve per-key ordering at the leader; across+ keys the drain fans out to shrink wall-clock drain duration.++3. **Bounce and retry**: a classified attempt that concludes no outcome+ exists — a `FAILED_PRECONDITION` (the drain raced the target's write+ fence: the owner resuming after a reaffirm, or the new owner's+ cutover), an unroutable target, or a transport failure (a pod+ mid-restart or briefly unreachable) — puts the bounced request and+ the rest of its key run back, backs off briefly, and retries; after+ a few consecutive bounced waves the drain yields its lane and the+ reconcile pass re-requests it on the next tick. Clients never see a+ bounce — their requests stay parked until the condition clears or+ the per-request deadline expires. A transport bounce marks the+ request possibly-applied: re-forwarding it is an at-least-once+ replay, counted by `personhog_router_stash_replayed_total` and+ covered by the redelivery contract in `personhog-leader`'s README+ (clients retrying `UNAVAILABLE` already impose the same+ requirement).++4. **Cooperative cancellation**: a paused or superseded drain stops at+ the next request boundary and puts everything it took back, in+ order, for the successor drain. Cancellation is a routing decision,+ not a request outcome — it is invisible to clients.Bounds are configurable per partition (`STASH_MAX_MESSAGES_PER_PARTITION`,`STASH_MAX_BYTES_PER_PARTITION`); requests that would exceed either bounddiff --git a/rust/personhog-router/src/backend/leader.rs b/rust/personhog-router/src/backend/leader.rsindex c957091862c2..80d31bf9da8f 100644--- a/rust/personhog-router/src/backend/leader.rs+++ b/rust/personhog-router/src/backend/leader.rs@@ -6,7 +6,7 @@ use bytes::Bytes;use dashmap::DashMap;use http::{HeaderMap, HeaderValue, Method, Uri, Version};use http_body_util::{BodyExt, Full};-use metrics::histogram;+use metrics::{counter, histogram};use tokio::sync::RwLock;use tonic::body::BoxBody;use tonic::transport::Channel;@@ -16,10 +16,8 @@ use tower::{Service, ServiceExt};use personhog_common::grpc::current_client_name;use personhog_common::partitioning::partition_for_person;-use super::retry::with_retry;use super::stash::{StashDecision, StashTable};-use crate::config::RetryConfig;-use crate::grpc_http::grpc_error_response;+use crate::grpc_http::{grpc_error_response, grpc_status_code};pub type AddressResolver = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;@@ -27,12 +25,69 @@ pub type AddressResolver = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;/// `{LEADER_PREFIX}{method}`.const LEADER_PREFIX: &str = "/personhog.leader.v1.PersonHogLeader/";+/// How long to wait after a bounced forward attempt before the next one.+/// Both bounce conditions clear on their own — a fence in+/// watch-propagation time, a transport failure as the target pod comes+/// up — so the cadence only needs to outpace the caller's latency bound,+/// not be aggressive. Shared by the live path's re-entrant retry loop+/// and the drain's wave loop so the two paths settle at the same rate.+pub(crate) const BOUNCE_BACKOFF: Duration = Duration::from_millis(150);++/// Consecutive bounces after which a retry loop gives up — the live path+/// returns a definitive `UNAVAILABLE` (the client's own retry may reach+/// a healthier router), the drain yields its lane to the reconcile pass.+pub(crate) const MAX_CONSECUTIVE_BOUNCES: u32 = 4;++/// Why a forward attempt produced no outcome, and what that implies for+/// the request's delivery state. All reasons share retry mechanics; they+/// are distinguished because they sit at different points on the+/// replay-safety spectrum, and only `Transport` leaves the delivery+/// state ambiguous.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum BounceReason {+ /// The partition could not be routed at all — no assignment in the+ /// table, or no address for the owner — so nothing was sent.+ /// Definitively not applied; transiently normal at startup and+ /// during ownership gaps.+ Unrouted,+ /// The target refused the request at admission — a write fence or a+ /// not-owned partition — before any work. Definitively not applied.+ Fenced,+ /// The transport failed with no response after the request may have+ /// been sent — the leader might have applied it. The next attempt+ /// is an at-least-once replay.+ Transport,+}++impl BounceReason {+ pub fn label(self) -> &'static str {+ match self {+ BounceReason::Unrouted => "unrouted",+ BounceReason::Fenced => "fenced",+ BounceReason::Transport => "transport",+ }+ }+}++/// What one classified forward attempt concluded. `Delivered` covers+/// every response the leader actually produced — success or error, it is+/// a real outcome the caller must hand to the client (an error status+/// like `UNAVAILABLE` is also the leader's backpressure signal, which+/// retrying would invert). `Bounced` means no outcome exists and the+/// caller's retry mechanism decides what happens next.+pub enum ForwardDecision {+ Delivered {+ response: http::Response<BoxBody>,+ call_ms: f64,+ },+ Bounced(BounceReason),+}+/// Static configuration for `LeaderBackend`. Bundles the knobs that come/// from `Config` so the constructor stays narrow as we add fields.pub struct LeaderBackendConfig {pub num_partitions: u32,pub timeout: Duration,- pub retry_config: RetryConfig,}/// Backend that routes person writes and strong reads to leader pods@@ -130,16 +185,24 @@ impl LeaderBackend {Ok(channel)}- /// Forward a raw gRPC request frame to the leader pod owning- /// `partition`, retrying transient channel failures. The partition- /// travels in the `x-partition` header the leader reads in place of a- /// body field; the client's own headers (`x-client-name`,- /// `x-caller-tag`, etc.) are forwarded verbatim. A leader response that- /// carries a gRPC error is returned as `Ok` — only transport failures- /// retry and surface as `Err`. On success also returns the channel+ /// Send a raw gRPC request frame over an already-resolved channel —+ /// a single delivery attempt, no internal retries. The partition+ /// travels in the `x-partition` header the leader reads in place of+ /// a body field; the client's own headers (`x-client-name`,+ /// `x-caller-tag`, etc.) are forwarded verbatim. A leader response+ /// that carries a gRPC error is returned as `Ok` — only transport+ /// failures surface as `Err`. On success also returns the channel/// round-trip time, used by the read path's network-overhead metric.- pub async fn forward_raw(+ ///+ /// Retry policy lives with the callers of `forward_classified`, both+ /// of which re-check routing state between attempts: the live path's+ /// re-entrant loop in `forward_or_stash` and the drain's wave loop.+ /// A blind retry here would re-send without seeing a stash window+ /// that opened during the backoff, so this layer deliberately stays+ /// single-attempt.+ async fn send_frame(&self,+ mut channel: Channel,method: &'static str,partition: u32,headers: &HeaderMap,@@ -149,68 +212,117 @@ impl LeaderBackend {let partition_header = HeaderValue::from(partition);let client = current_client_name();- with_retry(&self.config.retry_config, method, || {- let channel_fut = self.resolve_leader_channel(partition);- let headers = headers.clone();- let frame = frame.clone();- let path = path.clone();- let partition_header = partition_header.clone();- let client = client.clone();- async move {- let mut channel = channel_fut.await?;-- let ready_start = Instant::now();- let ready_result = channel.ready().await;- let ready_outcome = if ready_result.is_ok() { "ok" } else { "error" };- histogram!(- "personhog_router_channel_ready_wait_ms",- "method" => method,- "client" => client.clone(),- "outcome" => ready_outcome,- )- .record(ready_start.elapsed().as_secs_f64() * 1000.0);- let ready = ready_result- .map_err(|e| Status::unavailable(format!("leader channel not ready: {e}")))?;-- let body = BoxBody::new(Full::new(frame).map_err(|never| match never {}));- let mut req = http::Request::new(body);- *req.method_mut() = Method::POST;- *req.uri_mut() = Uri::builder()- .path_and_query(path)- .build()- .expect("leader path is a valid URI");- *req.version_mut() = Version::HTTP_2;- *req.headers_mut() = headers;- req.headers_mut().insert("x-partition", partition_header);-- let call_start = Instant::now();- let call_result = ready.call(req).await;- let call_ms = call_start.elapsed().as_secs_f64() * 1000.0;- let call_outcome = if call_result.is_ok() { "ok" } else { "error" };- histogram!(- "personhog_router_channel_call_ms",- "method" => method,- "client" => client,- "outcome" => call_outcome,- )- .record(call_ms);- let response = call_result- .map_err(|e| Status::unavailable(format!("leader backend error: {e}")))?;- Ok((response, call_ms))+ let ready_start = Instant::now();+ let ready_result = channel.ready().await;+ let ready_outcome = if ready_result.is_ok() { "ok" } else { "error" };+ histogram!(+ "personhog_router_channel_ready_wait_ms",+ "method" => method,+ "client" => client.clone(),+ "outcome" => ready_outcome,+ )+ .record(ready_start.elapsed().as_secs_f64() * 1000.0);+ let ready = ready_result+ .map_err(|e| Status::unavailable(format!("leader channel not ready: {e}")))?;++ let body = BoxBody::new(Full::new(frame.clone()).map_err(|never| match never {}));+ let mut req = http::Request::new(body);+ *req.method_mut() = Method::POST;+ *req.uri_mut() = Uri::builder()+ .path_and_query(path)+ .build()+ .expect("leader path is a valid URI");+ *req.version_mut() = Version::HTTP_2;+ *req.headers_mut() = headers.clone();+ req.headers_mut().insert("x-partition", partition_header);++ let call_start = Instant::now();+ let call_result = ready.call(req).await;+ let call_ms = call_start.elapsed().as_secs_f64() * 1000.0;+ let call_outcome = if call_result.is_ok() { "ok" } else { "error" };+ histogram!(+ "personhog_router_channel_call_ms",+ "method" => method,+ "client" => client,+ "outcome" => call_outcome,+ )+ .record(call_ms);+ let response =+ call_result.map_err(|e| Status::unavailable(format!("leader backend error: {e}")))?;+ Ok((response, call_ms))+ }++ /// One classified forward attempt: resolve the target, send the+ /// frame, and decide what the result means. This is the single+ /// shared reading of leader responses — the live path's retry loop+ /// and the drain's wave loop both build on it, so the two paths can+ /// never drift in how they interpret the same response.+ ///+ /// Resolution happens here, before the send, so its failures+ /// classify as `Unrouted` — nothing touched the wire, and the+ /// request's delivery state is not ambiguous the way a mid-send+ /// transport failure's is.+ pub async fn forward_classified(+ &self,+ method: &'static str,+ partition: u32,+ headers: &HeaderMap,+ frame: &Bytes,+ ) -> ForwardDecision {+ let channel = match self.resolve_leader_channel(partition).await {+ Ok(channel) => channel,+ Err(_status) => return ForwardDecision::Bounced(BounceReason::Unrouted),+ };+ match self+ .send_frame(channel, method, partition, headers, frame)+ .await+ {+ // Every leader use of FailedPrecondition is a routing-race+ // rejection at admission ("fenced for handoff", "partition+ // not owned") — never a semantic client error — so it+ // classifies as a bounce rather than an outcome.+ Ok((response, _call_ms))+ if grpc_status_code(&response) == Some(Code::FailedPrecondition as i32) =>+ {+ ForwardDecision::Bounced(BounceReason::Fenced)}- })- .await+ Ok((response, call_ms)) => ForwardDecision::Delivered { response, call_ms },+ Err(_status) => ForwardDecision::Bounced(BounceReason::Transport),+ }}- /// Forward a write to the leader, honoring the per-partition stash.- /// While a handoff for this partition is in a non-terminal phase the- /// stash is open and the request parks until drain replays it to the- /// new owner (or its deadline expires); otherwise it forwards- /// immediately. Returns the final gRPC response — the leader's, or a- /// router-generated error when the stash is full or dropped — plus the- /// channel round-trip time when the request forwarded directly- /// (`None` for stashed requests, whose latency is dominated by the- /// handoff wait and tracked by the stash-wait histogram instead).+ /// Forward a leader-path request, honoring the per-partition stash+ /// and retrying bounced attempts. While a handoff for this partition+ /// is in a non-terminal phase the stash is open and the request+ /// parks until drain replays it to the new owner (or its deadline+ /// expires); otherwise it forwards. Returns the final gRPC response+ /// — the leader's, or a router-generated error when the stash is+ /// full or dropped — plus the channel round-trip time when the+ /// request forwarded directly (`None` for stashed requests, whose+ /// latency is dominated by the handoff wait and tracked by the+ /// stash-wait histogram instead).+ ///+ /// A bounced attempt (fence rejection or transport failure — see+ /// [`ForwardDecision`]) does not surface to the client. The request+ /// is held in this task, the loop backs off briefly, and the next+ /// iteration starts from the stash check — not a blind re-send —+ /// because a bounce usually means the router's routing view is+ /// stale and the backoff gives the watch time to deliver what the+ /// leader already knew. By the re-attempt, one of three worlds+ /// holds: a stash window opened (the request parks and rides the+ /// handoff — the race becomes the normal path), the table flipped+ /// (the re-resolve targets the new owner), or nothing changed yet+ /// (re-send, possibly bounce again). After `MAX_CONSECUTIVE_BOUNCES`+ /// the request fails with a definitive `UNAVAILABLE`, so a router+ /// whose view never updates (a dead watch) can't hold requests+ /// forever — the client's own retry may land on a healthy router.+ ///+ /// A transport bounce marks the request possibly-applied: the leader+ /// may have processed it without us seeing the response, so any+ /// further forward — here or by the drain if it parks — is an+ /// at-least-once replay, counted by+ /// `personhog_router_stash_replayed_total` and covered by the+ /// redelivery contract in `personhog-leader`'s README.pub async fn forward_or_stash(&self,method: &'static str,@@ -219,35 +331,69 @@ impl LeaderBackend {headers: HeaderMap,frame: Bytes,) -> (http::Response<BoxBody>, Option<f64>) {- // The stash module emits its own enqueued/rejected counters at the- // source; we don't double-count here. It borrows the frame and- // headers, cloning only when the request actually parks, so the- // steady-state forward path copies nothing.- match self- .stash- .enqueue_or_forward(partition, method, &frame, &headers, key)- .await- {- StashDecision::Stashed(rx) => {- let response = rx.await.unwrap_or_else(|_| {- grpc_error_response(- Code::Unavailable,- "router stash dropped before handoff completed",- )- });- (response, None)+ let mut consecutive_bounces = 0u32;+ let mut possibly_applied = false;+ loop {+ // The stash module emits its own enqueued/rejected counters+ // at the source; we don't double-count here. It borrows the+ // frame and headers, cloning only when the request actually+ // parks, so the steady-state forward path copies nothing.+ match self+ .stash+ .enqueue_or_forward(partition, method, &frame, &headers, key, possibly_applied)+ .await+ {+ StashDecision::Stashed(rx) => {+ let response = rx.await.unwrap_or_else(|_| {+ grpc_error_response(+ Code::Unavailable,+ "router stash dropped before handoff completed",+ )+ });+ return (response, None);+ }+ StashDecision::Rejected => {+ return (+ grpc_error_response(+ Code::Unavailable,+ &format!("router stash full for partition {partition}"),+ ),+ None,+ );+ }+ StashDecision::Forward => {}+ }++ if possibly_applied {+ counter!("personhog_router_stash_replayed_total").increment(1);}- StashDecision::Rejected => (- grpc_error_response(- Code::Unavailable,- &format!("router stash full for partition {partition}"),- ),- None,- ),- StashDecision::Forward => {- match self.forward_raw(method, partition, &headers, &frame).await {- Ok((response, call_ms)) => (response, Some(call_ms)),- Err(status) => (grpc_error_response(status.code(), status.message()), None),+ match self+ .forward_classified(method, partition, &headers, &frame)+ .await+ {+ ForwardDecision::Delivered { response, call_ms } => {+ return (response, Some(call_ms));+ }+ ForwardDecision::Bounced(reason) => {+ if reason == BounceReason::Transport {+ possibly_applied = true;+ }+ counter!(+ "personhog_router_forward_bounced_total",+ "reason" => reason.label()+ )+ .increment(1);+ consecutive_bounces += 1;+ if consecutive_bounces >= MAX_CONSECUTIVE_BOUNCES {+ return (+ grpc_error_response(+ Code::Unavailable,+ "leader unreachable or transitioning; retry",+ ),+ None,+ );+ }+ tokio::time::sleep(BOUNCE_BACKOFF).await;}}}@@ -262,11 +408,6 @@ mod tests {LeaderBackendConfig {num_partitions,timeout: Duration::from_secs(5),- retry_config: RetryConfig {- max_retries: 0,- initial_backoff_ms: 1,- max_backoff_ms: 1,- },}}@@ -287,6 +428,39 @@ mod tests {assert_eq!(result.unwrap_err().code(), tonic::Code::Unavailable);}+ /// An unroutable partition (empty table at startup, an ownership+ /// gap) rides the bounce budget — giving the routing view time to+ /// arrive, or a stash window time to open — and then fails with a+ /// definitive retryable `UNAVAILABLE`, never hanging and never a+ /// non-retryable code.+ #[tokio::test]+ async fn an_unrouted_partition_bounces_then_fails_unavailable() {+ let routing_table = Arc::new(RwLock::new(HashMap::new()));+ let resolver: AddressResolver = Arc::new(|_| Some("http://localhost:50053".to_string()));+ let backend = LeaderBackend::new(+ routing_table,+ resolver,+ test_config(8),+ StashTable::with_bounds(usize::MAX, usize::MAX),+ );++ let partition = backend.partition_for_person(1, 42);+ let (response, call_ms) = backend+ .forward_or_stash(+ "UpdatePersonProperties",+ partition,+ (1, 42),+ HeaderMap::new(),+ Bytes::from_static(b"x"),+ )+ .await;+ assert!(call_ms.is_none());+ assert_eq!(+ crate::grpc_http::grpc_status_code(&response),+ Some(Code::Unavailable as i32)+ );+ }+#[tokio::test]async fn resolve_leader_returns_unavailable_when_address_unresolvable() {let routing_table = Arc::new(RwLock::new(HashMap::new()));diff --git a/rust/personhog-router/src/backend/mod.rs b/rust/personhog-router/src/backend/mod.rsindex 79c3afc4cfcd..8a24abd0cc75 100644--- a/rust/personhog-router/src/backend/mod.rs+++ b/rust/personhog-router/src/backend/mod.rs@@ -1,9 +1,11 @@pub mod discovery;mod leader;mod replica;-mod retry;mod stash;-pub use leader::{AddressResolver, LeaderBackend, LeaderBackendConfig};+pub use leader::{+ AddressResolver, BounceReason, ForwardDecision, LeaderBackend, LeaderBackendConfig,+};+pub(crate) use leader::{BOUNCE_BACKOFF, MAX_CONSECUTIVE_BOUNCES};pub use replica::{ReplicaBackend, ReplicaDnsConfig};-pub use stash::{StashDecision, StashTable, StashedRequest};+pub use stash::{DrainSession, StashDecision, StashKey, StashTable, StashedRequest, TakenKeyRun};diff --git a/rust/personhog-router/src/backend/retry.rs b/rust/personhog-router/src/backend/retry.rsdeleted file mode 100644index cdda6c02cef6..000000000000--- a/rust/personhog-router/src/backend/retry.rs+++ /dev/null@@ -1,189 +0,0 @@-use std::future::Future;-use std::time::Duration;--use metrics::counter;-use personhog_common::grpc::{code_as_str, current_client_name};-use rand::Rng;-use tonic::{Code, Status};-use tracing::warn;--use crate::config::RetryConfig;--fn is_retryable(code: Code) -> bool {- matches!(code, Code::Unavailable | Code::DeadlineExceeded)-}--/// Executes an async operation with exponential backoff and jitter on transient gRPC errors.-///-/// Only retries on `Unavailable` and `DeadlineExceeded` status codes.-/// All other errors (e.g. `Internal`, `InvalidArgument`, `NotFound`) are returned immediately.-pub async fn with_retry<F, Fut, T>(- config: &RetryConfig,- method: &'static str,- mut make_call: F,-) -> Result<T, Status>-where- F: FnMut() -> Fut,- Fut: Future<Output = Result<T, Status>>,-{- let mut delay_ms = config.initial_backoff_ms;-- for attempt in 0..=config.max_retries {- match make_call().await {- Ok(value) => return Ok(value),- Err(status) if attempt < config.max_retries && is_retryable(status.code()) => {- let code_str = code_as_str(status.code());- let client = current_client_name();-- counter!(- "personhog_router_backend_retries_total",- "method" => method,- "status_code" => code_str,- "client" => client.clone()- )- .increment(1);-- warn!(- method = method,- attempt = attempt + 1,- max_retries = config.max_retries,- status_code = code_str,- "retrying after transient error"- );-- let base = delay_ms / 2;- let jittered_ms = base + rand::thread_rng().gen_range(0..=base);- tokio::time::sleep(Duration::from_millis(jittered_ms)).await;- delay_ms = (delay_ms * 2).min(config.max_backoff_ms);- }- Err(status) => return Err(status),- }- }-- unreachable!("loop runs max_retries + 1 times and always returns")-}--#[cfg(test)]-mod tests {- use std::sync::atomic::{AtomicU32, Ordering};-- use super::*;-- fn test_config() -> RetryConfig {- RetryConfig {- max_retries: 3,- initial_backoff_ms: 1,- max_backoff_ms: 10,- }- }-- #[tokio::test]- async fn succeeds_on_first_attempt() {- let calls = AtomicU32::new(0);- let result = with_retry(&test_config(), "test", || {- calls.fetch_add(1, Ordering::SeqCst);- async { Ok::<_, Status>("ok") }- })- .await;-- assert_eq!(result.unwrap(), "ok");- assert_eq!(calls.load(Ordering::SeqCst), 1);- }-- #[tokio::test]- async fn retries_transient_then_succeeds() {- let transient_codes = vec![Code::Unavailable, Code::DeadlineExceeded];- for code in transient_codes {- let calls = AtomicU32::new(0);- let result = with_retry(&test_config(), "test", || {- let attempt = calls.fetch_add(1, Ordering::SeqCst);- let status = Status::new(code, "transient");- async move {- if attempt < 2 {- Err(status)- } else {- Ok("recovered")- }- }- })- .await;-- assert_eq!(result.unwrap(), "recovered", "should recover from {code:?}");- assert_eq!(- calls.load(Ordering::SeqCst),- 3,- "should take 3 attempts for {code:?}"- );- }- }-- #[tokio::test]- async fn does_not_retry_permanent_errors() {- let calls = AtomicU32::new(0);- let result = with_retry(&test_config(), "test", || {- calls.fetch_add(1, Ordering::SeqCst);- async { Err::<&str, _>(Status::invalid_argument("bad request")) }- })- .await;-- assert_eq!(result.unwrap_err().code(), Code::InvalidArgument);- assert_eq!(calls.load(Ordering::SeqCst), 1);- }-- #[tokio::test]- async fn exhausts_retries_on_persistent_transient_error() {- let calls = AtomicU32::new(0);- let result = with_retry(&test_config(), "test", || {- calls.fetch_add(1, Ordering::SeqCst);- async { Err::<&str, _>(Status::unavailable("still down")) }- })- .await;-- assert_eq!(result.unwrap_err().code(), Code::Unavailable);- // 1 initial + 3 retries = 4 total attempts- assert_eq!(calls.load(Ordering::SeqCst), 4);- }-- #[tokio::test]- async fn no_retries_when_max_retries_is_zero() {- let config = RetryConfig {- max_retries: 0,- initial_backoff_ms: 1,- max_backoff_ms: 10,- };- let calls = AtomicU32::new(0);- let result = with_retry(&config, "test", || {- calls.fetch_add(1, Ordering::SeqCst);- async { Err::<&str, _>(Status::unavailable("down")) }- })- .await;-- assert_eq!(result.unwrap_err().code(), Code::Unavailable);- assert_eq!(calls.load(Ordering::SeqCst), 1);- }-- #[tokio::test]- async fn retries_all_transient_codes() {- let cases = vec![- (Code::Unavailable, "unavailable"),- (Code::DeadlineExceeded, "deadline_exceeded"),- ];- for (code, msg) in cases {- let calls = AtomicU32::new(0);- let config = RetryConfig {- max_retries: 1,- initial_backoff_ms: 1,- max_backoff_ms: 1,- };- let result = with_retry(&config, "test", || {- calls.fetch_add(1, Ordering::SeqCst);- let status = Status::new(code, msg);- async move { Err::<&str, _>(status) }- })- .await;-- assert_eq!(result.unwrap_err().code(), code);- assert_eq!(calls.load(Ordering::SeqCst), 2, "should retry {code:?}");- }- }-}diff --git a/rust/personhog-router/src/backend/stash.rs b/rust/personhog-router/src/backend/stash.rsindex 7d86f76fe41a..fbfa0b84becb 100644--- a/rust/personhog-router/src/backend/stash.rs+++ b/rust/personhog-router/src/backend/stash.rs@@ -1,33 +1,45 @@-//! Per-partition stash queue for the leader path.+//! Per-partition stash for the leader path.//!//! During a partition handoff, the coordinator advances the handoff state//! through `Freezing → Draining → Warming → Complete`. From the moment//! the handoff is created (in `Freezing`) and until the routing table//! flips at `Complete`, routers buffer (stash) incoming leader-path//! requests — writes and strong reads alike — for that partition here.-//! When `Complete` arrives the stashed requests are drained in arrival-//! order to the new owner.+//! When `Complete` arrives the stashed requests are drained to the new+//! owner in per-key admission order.//!//! Stashing both request kinds gives the protocol two guarantees at once://! no split-brain writes, and strong reads that stay read-your-write//! through the handoff — a read queued behind the write it must observe//! (per-key FIFO) drains after it, instead of racing ahead to the old-//! owner's frozen cache. Every request that hits the router during the-//! handoff window is either delivered in arrival order or fails fast with-//! `UNAVAILABLE` once its per-request deadline expires (see-//! `RouterStashHandler`).+//! owner's frozen cache.+//!+//! Internally each partition holds a [`KeyedStash`] keyed by+//! `(team_id, person_id)` — the leader's per-person serialization+//! boundary. Entries are seq-stamped at admission and leave the stash+//! only through a definitive outcome (delivered, or failed in a way the+//! client was told about); an attempt that cannot finish — the target+//! bounced it, the drain was paused or superseded — puts its entries+//! back at their sequence positions, so a retry can never be overtaken+//! by newer same-key work. Draining runs through a [`DrainSession`],+//! which owns the take → complete/put-back lifecycle and the+//! empty-queue eviction handshake.-use std::collections::VecDeque;use std::sync::Arc;use std::time::Instant;use bytes::Bytes;use dashmap::DashMap;use http::HeaderMap;+use keyed_stash::{Entry, KeyedStash};use tokio::sync::{oneshot, Mutex};-use tokio_util::sync::CancellationToken;use tonic::body::BoxBody;+/// The leader's per-person serialization key: `(team_id, person_id)`.+/// Per-key ordering is preserved from admission through drain; distinct+/// keys carry no ordering relationship and may drain in parallel.+pub type StashKey = (i64, i64);+/// Fixed per-request overhead estimate that approximates the bookkeeping/// cost of holding a request in the queue (struct fields, oneshot/// channel, etc.). Combined with the variable payload size below, this@@ -71,27 +83,50 @@ pub struct StashedRequest {/// The client's request headers, forwarded verbatim (the router stamps/// `x-partition` at forward time).pub headers: HeaderMap,- /// `(team_id, person_id)` — the leader's per-person serialization key,- /// used to preserve per-key ordering during drain.- pub key: (i64, i64),+ /// The leader's per-person serialization key, used to preserve+ /// per-key ordering during drain.+ pub key: StashKey,pub reply: oneshot::Sender<http::Response<BoxBody>>,- /// Wall-clock time the request was enqueued. Used to record stash-wait- /// histograms when drain forwards the request, giving operators- /// visibility into how long callers spent parked during a handoff.+ /// Wall-clock time the request was enqueued. Used to enforce the+ /// per-request drain deadline and to record stash-wait histograms,+ /// giving operators visibility into how long callers spent parked+ /// during a handoff.pub enqueued_at: Instant,+ /// Set when a delivery attempt failed at the transport layer after+ /// the request may already have been sent: the leader might have+ /// applied it without us seeing the response. Re-forwarding such a+ /// request is an at-least-once replay — covered by the redelivery+ /// contract in `personhog-leader`'s README — and is counted so+ /// operators can see how often it happens.+ pub possibly_applied: bool,+}++impl StashedRequest {+ /// The size this request counts against the byte bound. Callers+ /// recording a definitive outcome pass this back to+ /// [`DrainSession::complete`] so the bound releases exactly what+ /// admission charged.+ pub fn approximate_size(&self) -> usize {+ approximate_size(&self.frame)+ }}-/// Inner queue plus running byte total. Tracked together so the byte-/// count stays consistent with the queue contents.+/// Inner keyed queue plus running admission totals. `messages` and+/// `bytes` count entries from admission until a definitive outcome —+/// including entries taken for an in-flight attempt, which still hold+/// their memory — so the bounds reflect what the router is actually+/// holding, not just what is queued.struct StashQueue {- requests: VecDeque<StashedRequest>,+ queue: KeyedStash<StashKey, StashedRequest>,+ messages: usize,bytes: usize,}impl StashQueue {fn new() -> Self {Self {- requests: VecDeque::new(),+ queue: KeyedStash::new(),+ messages: 0,bytes: 0,}}@@ -100,13 +135,13 @@ impl StashQueue {struct PartitionStash {max_messages: usize,max_bytes: usize,- /// `Some(queue)` while alive; `None` once `drain` has both taken- /// the queue contents and evicted this entry from the dashmap —- /// both inside the same critical section. The `None` state therefore- /// doubles as a tombstone: a concurrent `begin_stash` that races- /// `drain` and observes `None` knows the dashmap entry is already- /// gone and that the next `get_or_create` will produce a fresh- /// entry rather than re-grab this doomed `Arc`.+ /// `Some(queue)` while alive; `None` once a drain session has both+ /// observed the queue fully settled and evicted this entry from the+ /// dashmap — both inside the same critical section. The `None` state+ /// therefore doubles as a tombstone: a concurrent `begin_stash` that+ /// races the eviction and observes `None` knows the dashmap entry is+ /// already gone and that the next `get_or_create` will produce a+ /// fresh entry rather than re-grab this doomed `Arc`.queue: Mutex<Option<StashQueue>>,}@@ -134,6 +169,14 @@ pub enum StashDecision {Rejected,}+/// One key's front run taken for a delivery attempt: every entry queued+/// for the key at take time, in admission order. Entries are in-attempt+/// until each is completed or put back through the session.+pub struct TakenKeyRun {+ pub key: StashKey,+ pub entries: Vec<Entry<StashedRequest>>,+}+/// Shared stash table. Cheap to clone (holds an `Arc`).#[derive(Clone)]pub struct StashTable {@@ -171,20 +214,20 @@ impl StashTable {////// Each iteration is a single attempt to bind to a live dashmap/// entry. The loop terminates because the only way to observe- /// `None` is to race a `drain` that evicted the entry inside its- /// queue lock — meaning the next `get_or_create` will create a- /// fresh entry rather than re-grab the doomed `Arc`. In production- /// the routing-table layer awaits `drain` before issuing the next- /// `begin_stash` for the same partition, so this loop runs at most- /// twice.+ /// `None` is to race a drain session's eviction, which removes the+ /// entry inside its queue lock — meaning the next `get_or_create`+ /// will create a fresh entry rather than re-grab the doomed `Arc`.+ /// In production the routing-table layer awaits the drain before+ /// issuing the next `begin_stash` for the same partition, so this+ /// loop runs at most twice.pub async fn begin_stash(&self, partition: u32) {while !self.try_acquire_alive_entry(partition).await {}}/// One attempt to bind to the live dashmap entry for `partition`./// Returns `true` if we successfully observed a `Some` queue (the- /// entry is alive and ready for enqueues); `false` if we raced a- /// `drain` that left a tombstoned `None`, in which case the caller+ /// entry is alive and ready for enqueues); `false` if we raced an+ /// eviction that left a tombstoned `None`, in which case the caller/// should retry to pick up the fresh entry.async fn try_acquire_alive_entry(&self, partition: u32) -> bool {let stash = self.get_or_create(partition);@@ -198,21 +241,27 @@ impl StashTable {/// the request actually parks — the steady state (no handoff in/// progress) returns `Forward` from the dashmap miss without copying/// anything.+ ///+ /// `possibly_applied` carries the live path's transport-failure mark+ /// into the parked entry: a request that bounced at the transport+ /// layer before parking may already have reached the leader, and the+ /// drain's eventual re-forward of it must count as a replay.pub async fn enqueue_or_forward(&self,partition: u32,method: &'static str,frame: &Bytes,headers: &HeaderMap,- key: (i64, i64),+ key: StashKey,+ possibly_applied: bool,) -> StashDecision {let stash = match self.inner.get(&partition) {Some(entry) => Arc::clone(entry.value()),None => return StashDecision::Forward,};let mut guard = stash.queue.lock().await;- // `None` here means a concurrent `drain` already took this stash's- // queue and removed the dashmap entry. We arrived holding an Arc to+ // `None` here means a drain session already settled this stash+ // and removed the dashmap entry. We arrived holding an Arc to// the orphaned PartitionStash. Returning Forward routes via the// normal path; the partition is no longer stashing.let Some(queue) = guard.as_mut() else {@@ -221,7 +270,7 @@ impl StashTable {let request_size = approximate_size(frame);- if queue.requests.len() >= stash.max_messages {+ if queue.messages >= stash.max_messages {metrics::counter!("personhog_router_stash_rejected_total","cause" => RejectCause::MaxMessages.label()@@ -239,101 +288,157 @@ impl StashTable {}let (tx, rx) = oneshot::channel();- queue.requests.push_back(StashedRequest {- method,- frame: frame.clone(),- headers: headers.clone(),+ queue.queue.push(key,- reply: tx,- enqueued_at: Instant::now(),- });+ StashedRequest {+ method,+ frame: frame.clone(),+ headers: headers.clone(),+ key,+ reply: tx,+ enqueued_at: Instant::now(),+ possibly_applied,+ },+ );+ queue.messages += 1;queue.bytes += request_size;metrics::counter!("personhog_router_stash_enqueued_total").increment(1);StashDecision::Stashed(rx)}- /// Drain stashed requests for `partition` by applying `forward_batch`- /// to each batch the loop dequeues, in FIFO order. Loops until the- /// queue is empty under the lock, then evicts the dashmap entry.- ///- /// Each iteration takes the current queue contents into a local- /// batch under the lock and releases the lock before applying- /// `forward_batch`. Requests that arrive *during* a forward- /// iteration land on the same queue (the dashmap entry is still- /// present, so `enqueue_or_forward` enqueues them as usual). The- /// next loop iteration picks them up. The drain only exits when- /// it observes an empty queue under the lock — at which point no- /// further arrival can sneak in before the dashmap eviction in- /// the same critical section.+ /// Open a drain session for `partition`, or `None` when nothing is+ /// stashed. The session pins the partition's stash so every take,+ /// complete, and put-back lands on the same queue the entries came+ /// from, even across the eviction handshake.///- /// This preserves arrival order across the cutover: any request- /// stashed before drain finishes is forwarded before drain- /// returns. Without this loop pattern, drain would take a single- /// snapshot, evict the dashmap entry, and let new requests bypass- /// the stash via the live routing path — letting them race ahead- /// of older requests still being replayed and corrupting per-key- /// ordering at the leader.- ///- /// Yielding whole batches (rather than one request at a time)- /// gives callers the freedom to forward in parallel within a- /// batch — for example, by grouping by leader-side serialization- /// key and fanning out across keys. Sequential within a key is- /// still required to preserve per-key ordering at the leader.- ///- /// Convergence is workload-dependent: under sustained- /// arrival-rate ≥ forward-rate the loop runs as long as load- /// 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`).- ///- /// `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 = ()>,- {- let stash = match self.inner.get(&partition) {- Some(entry) => Arc::clone(entry.value()),- None => return,+ /// The drain-lane layer serializes drains per partition, so at most+ /// one session is active for a partition at a time; the session API+ /// relies on that for its eviction reasoning but tolerates a racing+ /// `begin_stash` (see [`DrainSession::finish_if_settled`]).+ pub fn drain_session(&self, partition: u32) -> Option<DrainSession> {+ let stash = Arc::clone(self.inner.get(&partition)?.value());+ Some(DrainSession {+ inner: Arc::clone(&self.inner),+ partition,+ stash,+ })+ }+}++/// The take → complete/put-back lifecycle for one partition's drain.+///+/// A drain repeatedly takes per-key front runs, attempts delivery, and+/// records exactly one of two outcomes per entry:+///+/// * [`complete`](Self::complete) — the entry's client got a definitive+/// answer (the forwarded response, or a terminal error). The entry is+/// gone and its admission charge is released.+/// * [`put_back`](Self::put_back) — the attempt was aborted before any+/// outcome existed (the target bounced it, the drain was paused or+/// superseded). The entries re-enter at their sequence positions,+/// ahead of everything admitted after them.+///+/// When a take finds no backlog, [`finish_if_settled`](Self::finish_if_settled)+/// closes the drain: if the queue is fully settled it tombstones the+/// queue and evicts the dashmap entry in one critical section, so any+/// racing `enqueue_or_forward` either pushes before the settle check+/// (forcing the caller through another take) or observes the entry+/// already gone and forwards live.+///+/// Requests that arrive *during* a session land on the same queue (the+/// dashmap entry stays present until the settle eviction) and are picked+/// up by a later take, preserving per-key admission order across the+/// cutover.+pub struct DrainSession {+ inner: Arc<DashMap<u32, Arc<PartitionStash>>>,+ partition: u32,+ stash: Arc<PartitionStash>,+}++impl DrainSession {+ /// Take the front run of up to `max_keys` keys for a delivery+ /// attempt. Returns an empty vec when no backlog is queued. Every+ /// returned entry is in-attempt until completed or put back;+ /// dropping entries instead would lose their clients' replies and+ /// permanently block the queue from settling.+ pub async fn take_for_attempt(&self, max_keys: usize) -> Vec<TakenKeyRun> {+ let mut guard = self.stash.queue.lock().await;+ let Some(q) = guard.as_mut() else {+ return Vec::new();};+ let keys: Vec<StashKey> = q+ .queue+ .keys_with_backlog()+ .take(max_keys)+ .copied()+ .collect();+ keys.into_iter()+ .map(|key| TakenKeyRun {+ entries: q.queue.take_front(&key, usize::MAX),+ key,+ })+ .collect()+ }- loop {- if cancel.is_cancelled() {- return;- }- let batch = {- let mut guard = stash.queue.lock().await;- let Some(q) = guard.as_mut() else {- // Already drained — the dashmap entry was removed- // by a concurrent caller. Nothing to do.- return;- };- if q.requests.is_empty() {- // Queue is empty under the lock. Atomically- // tombstone the queue and evict the dashmap entry- // — both inside this critical section — so any- // racing `enqueue_or_forward` either pushes- // before our lock acquire (forcing us through one- // more loop iteration) or observes the entry- // already gone afterwards.- *guard = None;- self.inner.remove(&partition);- return;- }- let taken: Vec<StashedRequest> =- std::mem::take(&mut q.requests).into_iter().collect();- q.bytes = 0;- taken- };+ /// Record a definitive outcome for one in-attempt entry of `key`,+ /// releasing `size` bytes (the entry's `approximate_size`) from the+ /// admission bounds.+ pub async fn complete(&self, key: StashKey, size: usize) {+ let mut guard = self.stash.queue.lock().await;+ // In-attempt entries block the settle eviction and this session+ // is the only writer of outcomes, so the queue cannot have been+ // tombstoned while an attempt was outstanding.+ let Some(q) = guard.as_mut() else {+ debug_assert!(false, "complete() on a tombstoned stash");+ return;+ };+ q.queue.complete(&key);+ q.messages -= 1;+ q.bytes = q.bytes.saturating_sub(size);+ }- forward_batch(batch).await;+ /// Return in-attempt entries whose delivery was aborted before any+ /// outcome existed. They re-enter at their sequence positions and+ /// keep their admission charges; the next attempt sees them first,+ /// in order.+ pub async fn put_back(&self, key: StashKey, entries: Vec<Entry<StashedRequest>>) {+ if entries.is_empty() {+ return;+ }+ let mut guard = self.stash.queue.lock().await;+ // Same reasoning as `complete`: outstanding in-attempt entries+ // make the tombstone unreachable.+ let Some(q) = guard.as_mut() else {+ debug_assert!(false, "put_back() on a tombstoned stash");+ return;+ };+ q.queue.put_back(&key, entries);+ }++ /// Close the session if the queue is fully settled — no queued+ /// entries and no in-attempt entries. On success the queue is+ /// tombstoned and the dashmap entry evicted inside the same critical+ /// section, and `true` is returned: the partition has left the stash+ /// path and new requests forward live. Returns `false` when an+ /// arrival raced in since the last take; the caller should take+ /// again.+ ///+ /// The eviction removes the entry only if it still holds this+ /// session's stash, so a `begin_stash` that already replaced a+ /// tombstoned entry with a fresh one can never have its new queue+ /// evicted from under it.+ pub async fn finish_if_settled(&self) -> bool {+ let mut guard = self.stash.queue.lock().await;+ match guard.as_ref() {+ // Already tombstoned — a prior settle got there first.+ None => true,+ Some(q) if q.queue.is_empty() => {+ *guard = None;+ self.inner+ .remove_if(&self.partition, |_, v| Arc::ptr_eq(v, &self.stash));+ true+ }+ Some(_) => false,}}}@@ -344,30 +449,31 @@ mod tests {use http::HeaderValue;use http_body_util::{BodyExt, Empty};- /// Collect drained requests into a `Vec` via the forward-batch- /// closure. Mirrors the original return-VecDeque API for tests- /// that just want to inspect what was drained without exercising- /// the per-batch fan-out semantics.- ///- /// The outer closure is `move` so the Arc clone it owns is- /// dropped when drain returns; otherwise it would survive past- /// `try_unwrap` and inflate the refcount.+ /// Drain everything with a trivial always-succeeds forwarder,+ /// collecting the requests in delivery order. Mirrors the handler's+ /// session loop: take, complete each entry, settle when no backlog+ /// remains.async fn drain_to_vec(table: &StashTable, partition: u32) -> Vec<StashedRequest> {- let collected = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));- let sink = std::sync::Arc::clone(&collected);- table- .drain(partition, &CancellationToken::new(), move |batch| {- let sink = std::sync::Arc::clone(&sink);- async move {- sink.lock().unwrap().extend(batch);+ let Some(session) = table.drain_session(partition) else {+ return Vec::new();+ };+ let mut out = Vec::new();+ loop {+ let taken = session.take_for_attempt(usize::MAX).await;+ if taken.is_empty() {+ if session.finish_if_settled().await {+ return out;}- })- .await;- std::sync::Arc::try_unwrap(collected)- .ok()- .expect("drain finished — outer closure should have dropped its sink clone")- .into_inner()- .unwrap()+ continue;+ }+ for run in taken {+ for entry in run.entries {+ let size = entry.item.approximate_size();+ out.push(entry.item);+ session.complete(run.key, size).await;+ }+ }+ }}/// Enqueue a minimal stashed write for `(team_id = 1, person_id)`.@@ -379,6 +485,7 @@ mod tests {&Bytes::from_static(b"x"),&HeaderMap::new(),(1, person_id),+ false,).await}@@ -398,6 +505,7 @@ mod tests {&Bytes::from(vec![0u8; payload]),&HeaderMap::new(),(1, person_id),+ false,).await}@@ -419,23 +527,26 @@ mod tests {}#[tokio::test]- async fn begin_then_enqueue_then_drain_preserves_fifo() {+ async fn begin_then_enqueue_then_drain_preserves_per_key_order() {let table = StashTable::with_bounds(usize::MAX, usize::MAX);table.begin_stash(0).await;- let _rx1 = match enqueue(&table, 0, 1).await {+ // Same key, distinguishable frames — ordering is a per-key+ // contract, so the assertion must not depend on cross-key+ // iteration order.+ let _rx1 = match enqueue_sized(&table, 0, 1, 1).await {StashDecision::Stashed(rx) => rx,_ => panic!("expected Stashed"),};- let _rx2 = match enqueue(&table, 0, 2).await {+ let _rx2 = match enqueue_sized(&table, 0, 1, 2).await {StashDecision::Stashed(rx) => rx,_ => panic!("expected Stashed"),};let drained = drain_to_vec(&table, 0).await;assert_eq!(drained.len(), 2);- let ids: Vec<i64> = drained.iter().map(|s| s.key.1).collect();- assert_eq!(ids, vec![1, 2]);+ let frame_lens: Vec<usize> = drained.iter().map(|s| s.frame.len()).collect();+ assert_eq!(frame_lens, vec![1, 2]);// After drain, new requests forward.match enqueue(&table, 0, 3).await {@@ -444,10 +555,10 @@ mod tests {}}- /// Drain must remove the dashmap entry so subsequent steady-state- /// requests for that partition can short-circuit on `dashmap.get`- /// returning `None`, avoiding the per-request Mutex lock that- /// `enqueue_or_forward` would otherwise take.+ /// A settled drain must remove the dashmap entry so subsequent+ /// steady-state requests for that partition can short-circuit on+ /// `dashmap.get` returning `None`, avoiding the per-request Mutex+ /// lock that `enqueue_or_forward` would otherwise take.#[tokio::test]async fn drain_removes_dashmap_entry() {let table = StashTable::with_bounds(usize::MAX, usize::MAX);@@ -459,17 +570,17 @@ mod tests {drain_to_vec(&table, 0).await;assert!(!table.inner.contains_key(&0),- "drain must remove the entry so future requests skip the lock path"+ "settle must remove the entry so future requests skip the lock path");}- /// 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.+ /// An aborted attempt puts its entries back and leaves the entry+ /// live: whatever is parked belongs to the successor drain, and new+ /// requests must keep stashing in the meantime. Evicting 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() {+ async fn put_back_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 {@@ -477,12 +588,17 @@ mod tests {_ => panic!("expected Stashed"),};- let cancelled = CancellationToken::new();- cancelled.cancel();- table.drain(0, &cancelled, |_batch| async {}).await;+ // An attempt starts, then aborts (pause/supersession/bounce) and+ // puts everything back without settling.+ let session = table.drain_session(0).expect("entry must be live");+ let mut taken = session.take_for_attempt(usize::MAX).await;+ assert_eq!(taken.len(), 1);+ let run = taken.remove(0);+ session.put_back(run.key, run.entries).await;+ drop(session);assert!(table.inner.contains_key(&0),- "cancelled drain must leave the entry live"+ "aborted drain must leave the entry live");// Requests keep parking, and a successor drain collects everything.@@ -498,6 +614,37 @@ mod tests {);}+ /// In-attempt entries must block the settle eviction: the queue can+ /// look empty (backlog fully taken) while outcomes are still+ /// outstanding, and settling then would orphan the eventual put-back+ /// into a tombstoned queue, dropping the clients' replies.+ #[tokio::test]+ async fn in_attempt_entries_block_settle() {+ 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 session = table.drain_session(0).expect("entry must be live");+ let mut taken = session.take_for_attempt(usize::MAX).await;+ let run = taken.remove(0);+ assert!(+ !session.finish_if_settled().await,+ "settle must refuse while an attempt is outstanding"+ );++ let entry = run.entries.into_iter().next().unwrap();+ let size = entry.item.approximate_size();+ session.complete(run.key, size).await;+ assert!(+ session.finish_if_settled().await,+ "settle must succeed once every outcome is recorded"+ );+ assert!(!table.inner.contains_key(&0));+ }+/// Back-to-back handoffs: drain → begin_stash for the same partition/// must produce a fresh empty queue, not preserve stale state.#[tokio::test]@@ -578,6 +725,38 @@ mod tests {));}+ /// The admission bounds must release on definitive outcomes, not on+ /// takes: an entry taken for an attempt still holds its memory, and+ /// releasing at take time would let a slow drain admit unbounded+ /// backlog behind it.+ #[tokio::test]+ async fn bounds_release_on_complete_not_on_take() {+ let table = StashTable::with_bounds(1, usize::MAX);+ table.begin_stash(0).await;+ assert!(matches!(+ enqueue(&table, 0, 1).await,+ StashDecision::Stashed(_)+ ));++ let session = table.drain_session(0).expect("entry must be live");+ let mut taken = session.take_for_attempt(usize::MAX).await;+ let run = taken.remove(0);+ // Taken but not completed — still counted against the bound.+ assert!(matches!(+ enqueue(&table, 0, 2).await,+ StashDecision::Rejected+ ));++ let entry = run.entries.into_iter().next().unwrap();+ let size = entry.item.approximate_size();+ session.complete(run.key, size).await;+ // Outcome recorded — capacity is released.+ assert!(matches!(+ enqueue(&table, 0, 3).await,+ StashDecision::Stashed(_)+ ));+ }+#[tokio::test]async fn partitions_are_independent() {let table = StashTable::with_bounds(usize::MAX, usize::MAX);@@ -596,11 +775,11 @@ mod tests {/// Race between concurrent enqueue and drain. The `Arc<PartitionStash>`/// + `Option<StashQueue>` design exists so that an enqueue that has- /// already cloned the Arc when drain runs sees `None` after drain- /// takes the queue, and returns `Forward` rather than pushing into a- /// dead queue. With many iterations this drives the race window- /// repeatedly; the invariant is that every request must end up either- /// in the drained batch or forwarded — never lost, never duplicated.+ /// already cloned the Arc when the settle eviction runs sees `None`,+ /// and returns `Forward` rather than pushing into a dead queue. With+ /// many iterations this drives the race window repeatedly; the+ /// invariant is that every request must end up either in the drained+ /// batch or forwarded — never lost, never duplicated.#[tokio::test(flavor = "multi_thread", worker_threads = 4)]async fn enqueue_and_drain_race() {for iteration in 0..200 {@@ -633,11 +812,9 @@ mod tests {}}- // With the loop-drain, every Stashed request is forwarded- // through `drain` regardless of when it arrived (concurrent- // arrivals during forwarding are caught by the next loop- // iteration). The previous "stashed count == drained count"- // assertion still holds because no request can be lost.+ // The session loop only settles after observing no backlog,+ // so every Stashed request is delivered regardless of when it+ // arrived (concurrent arrivals are caught by a later take).assert_eq!(drained.len() + forwarded_count,ENQUEUERS,@@ -703,15 +880,15 @@ mod tests {}/// Regression for the structural race the `drained` tombstone closes:- /// a `begin_stash` that observes the post-`take` `None` queue between- /// `drain` releasing the queue lock and `drain` evicting the dashmap- /// entry must not initialize a new queue on the doomed `Arc`. With- /// the tombstone, `begin_stash` sees `drained=true`, drops the lock,- /// and retries via `get_or_create` — which produces a fresh dashmap- /// entry once `drain` finishes its `inner.remove`.+ /// a `begin_stash` that observes the post-settle `None` queue between+ /// the settle tombstoning the queue and evicting the dashmap entry+ /// must not initialize a new queue on the doomed `Arc`. With the+ /// tombstone, `begin_stash` sees `None`, drops the lock, and retries+ /// via `get_or_create` — which produces a fresh dashmap entry once+ /// the eviction finishes.////// The race window is microseconds; we run many iterations to- /// exercise it. The protocol awaits `drain` before issuing the next+ /// exercise it. The protocol awaits the drain before issuing the next/// `begin_stash` for a partition today, so this race cannot trigger/// in production — the test guards against future callers that/// might break that ordering.@@ -728,9 +905,7 @@ mod tests {// subsequent enqueue sees it and parks.let drain_table = table.clone();let drain_handle = tokio::spawn(async move {- drain_table- .drain(0, &CancellationToken::new(), |_batch| async {})- .await;+ drain_to_vec(&drain_table, 0).await;});let begin_table = table.clone();let begin_handle = tokio::spawn(async move { begin_table.begin_stash(0).await });@@ -739,10 +914,10 @@ mod tests {begin_handle.await.unwrap();// Only meaningful to assert when begin_stash logically ran- // *after* drain (drain.remove evicted, begin_stash created- // a fresh entry). If begin_stash logically ran first+ // *after* the settle (eviction removed the entry, begin_stash+ // created a fresh one). If begin_stash logically ran first// (observed the prior `Some` queue, was idempotent), then- // drain legitimately drained that prior queue and a+ // the drain legitimately drained that prior queue and a// subsequent enqueue forwards via the live path — that's a// protocol-violation scenario, not a stash-module bug, and// the routing-table layer prevents it. We accept either@@ -756,7 +931,7 @@ mod tests {}StashDecision::Forward => {// Begin_stash logically ran first and was idempotent;- // drain emptied the prior queue. No orphaned Arc.+ // the drain emptied the prior queue. No orphaned Arc.}StashDecision::Rejected => {panic!("unexpected Rejected on iteration {iteration}");diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rsindex b7965ff88ed8..eac69e08d2a1 100644--- a/rust/personhog-router/src/main.rs+++ b/rust/personhog-router/src/main.rs@@ -317,7 +317,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {LeaderBackendConfig {num_partitions,timeout: config.backend_timeout(),- retry_config: config.retry_config(),},StashTable::with_bounds(config.stash_max_messages_per_partition,diff --git a/rust/personhog-router/src/stash_handler.rs b/rust/personhog-router/src/stash_handler.rsindex 9aff3fe6a96b..32d0758fa26f 100644--- a/rust/personhog-router/src/stash_handler.rs+++ b/rust/personhog-router/src/stash_handler.rs@@ -1,35 +1,43 @@-use std::collections::HashMap;-use std::sync::atomic::{AtomicU64, Ordering};use std::sync::Arc;use std::time::{Duration, Instant};+use std::vec::IntoIter;use async_trait::async_trait;use futures::future::join_all;+use keyed_stash::Entry;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};-use crate::grpc_http::{grpc_error_response, grpc_status_code, is_grpc_error_response};+use crate::backend::{+ BounceReason, DrainSession, ForwardDecision, LeaderBackend, StashKey, StashedRequest,+ TakenKeyRun, BOUNCE_BACKOFF, MAX_CONSECUTIVE_BOUNCES,+};+use crate::grpc_http::{grpc_error_response, is_grpc_error_response};/// Stash handler for the router. Reacts to handoff phase transitions:////// * `Freezing` / `Draining` / `Warming` → `begin_stash`: start (or/// re-confirm) buffering leader-path requests — writes and strong-/// reads — for the partition in the shared `StashTable`. The routing-table layer calls `begin_stash` on-/// every non-terminal phase the router observes, so the call must-/// be idempotent — `StashTable::begin_stash` no-ops if the entry is-/// already live. New leader-path requests park in a per-partition-/// queue while the handoff progresses through-/// `Freezing → Draining → Warming`.+/// reads — for the partition in the shared `StashTable`. The+/// routing-table layer calls `begin_stash` on every non-terminal phase+/// the router observes, so the call must be idempotent —+/// `StashTable::begin_stash` no-ops if the entry is already live. New+/// leader-path requests park in per-key queues while the handoff+/// progresses through `Freezing → Draining → Warming`./// * `Complete` → `drain_stash`: forward the buffered requests to the-/// new owner, each to the method it arrived on. The drain runs as a loop over the queue; any request-/// that arrives during drain (the dashmap entry is still live until-/// drain observes the queue empty under the lock) is picked up by-/// the next iteration, preserving FIFO ordering across the cutover.+/// new owner, each to the method it arrived on, through a+/// `DrainSession`. The drain loops taking per-key front runs until it+/// observes the queue fully settled; any request that arrives during+/// the drain lands on the same queue and is picked up by a later take.///-/// Two policies layer on top of the raw drain mechanism:+/// Every stashed request ends in exactly one of two ways: a definitive+/// outcome delivered to its client (the forwarded response, an expiry+/// `UNAVAILABLE`, or a terminal error), or a put-back that re-parks it+/// at its admission position for a later attempt. Nothing is failed+/// merely because a particular drain attempt could not finish. The+/// policies layered on the session:////// 1. **Per-request deadline.** Each stashed request carries an/// `enqueued_at` timestamp; if its wait exceeds `max_stash_wait` we@@ -40,19 +48,41 @@ use crate::grpc_http::{grpc_error_response, grpc_status_code, is_grpc_error_resp/// the outcome and may double-write on retry). With router-side/// fail-fast under `UNAVAILABLE`, the client retries definitively.///-/// 2. **Per-key concurrent forwarding.** Each drain batch is partitioned-/// by the leader's per-key serialization boundary-/// (`(team_id, person_id)`, the same key the leader's per-person-/// mutex uses). Requests for distinct keys forward in parallel-/// without affecting per-key ordering at the leader; requests for-/// the same key forward sequentially within a per-key sub-task.-/// This shrinks drain wall-clock duration without breaking-/// ordering guarantees.+/// 2. **Per-key concurrent forwarding.** Each wave takes up to+/// `drain_concurrency` keys' front runs — the leader's per-key+/// serialization boundary (`(team_id, person_id)`, the same key the+/// leader's per-person mutex uses) — and forwards them in parallel,+/// sequential within each key. This shrinks drain wall-clock duration+/// without breaking per-key ordering at the leader.///-/// 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.+/// 3. **Bounce and retry.** A classified forward attempt (see+/// `LeaderBackend::forward_classified`, the single reading of leader+/// responses shared with the live path) can conclude no outcome+/// exists: a `FailedPrecondition` from the target (its fence or+/// ownership is still settling — a reaffirm's drain racing the+/// owner's resume, or a completion's drain racing the new owner's+/// cutover), an unroutable target (a table or address gap the+/// reconcile pass will heal), or a transport failure (the target pod+/// restarting or briefly unreachable). The bounced request and the rest of its key+/// run are put back, the drain backs off `BOUNCE_BACKOFF` and+/// retries; after `MAX_CONSECUTIVE_BOUNCES` bounced waves it yields+/// the lane and lets the reconcile pass re-request the drain.+/// Clients never see a bounce — their requests simply stay parked+/// until the condition clears or their deadline expires. A transport+/// bounce marks the request `possibly_applied` (the leader may have+/// processed it without us seeing the response); re-forwarding it is+/// an at-least-once replay, counted by+/// `personhog_router_stash_replayed_total` and covered by the+/// redelivery contract in `personhog-leader`'s README. A+/// response the leader actually produced is never bounced — even an+/// error status is a real outcome, and `UNAVAILABLE` from the leader+/// is its backpressure signal, which parking would invert.+///+/// 4. **Cooperative cancellation.** A paused or superseded drain stops+/// at the next request boundary and puts everything it took back:+/// unprocessed entries stay parked, in order, for the successor+/// drain. Cancellation is a routing decision, not a request outcome,+/// so it is invisible to clients.////// 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.@@ -61,7 +91,7 @@ pub struct RouterStashHandler {/// Per-request deadline for stashed writes. Past-deadline requests/// fail fast with `UNAVAILABLE` during drain instead of forwarding.max_stash_wait: Duration,- /// Maximum keys forwarded in parallel within a single drain batch.+ /// Maximum keys forwarded in parallel within a single drain wave./// Per-key ordering is preserved (sequential within a key); across/// keys we fan out up to this many at once.drain_concurrency: usize,@@ -85,164 +115,143 @@ impl RouterStashHandler {}}-/// Forward one stashed request, applying the per-request deadline. If-/// the request has been waiting longer than `max_stash_wait`, send back-/// `UNAVAILABLE` without forwarding so the client retries with a fresh-/// request. Otherwise forward via the unified routing path and pipe the-/// result through the oneshot. Tracks metrics for the five observable-/// outcomes (expired, success, fenced, error, dropped) so operators can-/// see stash-driven latency, drains racing a leader's fence or cutover,-/// leader failures during drain, and cases where the original caller-/// disconnected before the reply.+/// What a single drain forward attempt decided.+enum Disposition {+ /// The request has a definitive outcome: reply to the client with+ /// this response and complete the entry under the given label.+ Reply {+ response: http::Response<tonic::body::BoxBody>,+ outcome: &'static str,+ },+ /// No outcome exists; the entry (and the rest of its key run) must+ /// be put back for a later attempt.+ Bounce(BounceReason),+}++/// Attempt one stashed request without consuming it. Applies the+/// per-request deadline first: a past-deadline request gets a definitive+/// `UNAVAILABLE` so the client retries with a fresh request rather than+/// waiting out a response that may exceed its gRPC timeout. Otherwise+/// the attempt is one classified forward — the same shared reading of+/// leader responses the live path uses (see+/// `LeaderBackend::forward_classified`), so the two paths cannot drift+/// in what counts as an outcome versus a bounce.async fn forward_one(leader_backend: &LeaderBackend,max_stash_wait: Duration,partition: u32,- stashed_req: StashedRequest,-) {- let waited = stashed_req.enqueued_at.elapsed();- metrics::histogram!("personhog_router_stash_wait_duration_ms")- .record(waited.as_secs_f64() * 1000.0);-- if waited > max_stash_wait {- // Past deadline — return a definitive UNAVAILABLE so the- // client knows it must retry, instead of leaving them waiting- // for a leader response that may exceed their gRPC timeout.- let response = grpc_error_response(- Code::Unavailable,- "stash wait exceeded; retry through new owner",- );- if stashed_req.reply.send(response).is_err() {- metrics::counter!("personhog_router_stash_dropped_total").increment(1);- }- metrics::counter!(- "personhog_router_stash_drained_total",- "outcome" => "expired"- )- .increment(1);- return;+ req: &StashedRequest,+) -> Disposition {+ if req.enqueued_at.elapsed() > max_stash_wait {+ return Disposition::Reply {+ response: grpc_error_response(+ Code::Unavailable,+ "stash wait exceeded; retry through new owner",+ ),+ outcome: "expired",+ };+ }+ if req.possibly_applied {+ metrics::counter!("personhog_router_stash_replayed_total").increment(1);}// Forward the buffered frame straight to the new owner. The router// stamps `x-partition` and the leader serializes per key, so replaying- // here preserves arrival order without re-entering the stash. The- // outcome label counts both transport failures and leader-returned- // gRPC errors (trailers-only responses carry their status in the- // headers, so no body poll is needed to classify them).- let (response, outcome) = match leader_backend- .forward_raw(- stashed_req.method,- partition,- &stashed_req.headers,- &stashed_req.frame,- )+ // here preserves arrival order without re-entering the stash.+ match leader_backend+ .forward_classified(req.method, partition, &req.headers, &req.frame).await{- // A FailedPrecondition during drain means the target's fence or- // 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- // acked.- Ok((response, _call_ms))- if grpc_status_code(&response) == Some(Code::FailedPrecondition as i32) =>- {- (- grpc_error_response(- Code::Unavailable,- "leader transitioning during stash drain; retry",- ),- "fenced",- )- }- Ok((response, _call_ms)) => {+ ForwardDecision::Delivered { response, .. } => {let outcome = if is_grpc_error_response(&response) {"error"} else {"success"};- (response, outcome)+ Disposition::Reply { response, outcome }}- Err(status) => (- grpc_error_response(status.code(), status.message()),- "error",- ),- };+ ForwardDecision::Bounced(reason) => Disposition::Bounce(reason),+ }+}++/// What one key run's attempt produced, aggregated per wave to drive the+/// bounce backoff.+struct KeyRunOutcome {+ completed: u64,+ bounced: bool,+}++/// Put an interrupted key run's remainder back at its admission+/// positions: the entry whose attempt was cut short plus everything not+/// yet attempted.+async fn put_back_rest(+ session: &DrainSession,+ key: StashKey,+ head: Entry<StashedRequest>,+ rest: IntoIter<Entry<StashedRequest>>,+ reason: &'static str,+) {+ let mut entries = vec![head];+ entries.extend(rest);metrics::counter!(- "personhog_router_stash_drained_total",- "outcome" => outcome+ "personhog_router_stash_put_back_total",+ "reason" => reason)- .increment(1);- if stashed_req.reply.send(response).is_err() {- metrics::counter!("personhog_router_stash_dropped_total").increment(1);- }+ .increment(entries.len() as u64);+ session.put_back(key, entries).await;}-/// Forward a single drain batch, fanning out across leader-side-/// serialization keys. Requests for the same `(team_id, person_id)`-/// forward sequentially in arrival order so the leader's per-person-/// lock processes them in the order routers received them; requests-/// for distinct keys forward in parallel, up to `concurrency` keys at-/// once. Returns when every request in the batch has been forwarded-/// (or fail-fasted by the deadline).-async fn forward_batch_by_key(- leader_backend: Arc<LeaderBackend>,+/// Forward one key's front run sequentially, recording a definitive+/// outcome per delivered entry. Stops early on cancellation or a+/// bounce, putting the remainder back in order.+async fn forward_key_run(+ leader_backend: &LeaderBackend,+ session: &DrainSession,max_stash_wait: Duration,- concurrency: usize,partition: u32,cancel: &CancellationToken,- batch: Vec<StashedRequest>,-) {- type Key = (i64, i64);- let mut groups: HashMap<Key, Vec<StashedRequest>> = HashMap::new();- for req in batch {- groups.entry(req.key).or_default().push(req);- }-- 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.+ run: TakenKeyRun,+) -> KeyRunOutcome {+ let mut outcome = KeyRunOutcome {+ completed: 0,+ bounced: false,+ };+ let mut entries = run.entries.into_iter();+ while let Some(mut entry) = entries.next() {if cancel.is_cancelled() {- for group in groups_iter {- for req in group {- fail_superseded(req);+ put_back_rest(session, run.key, entry, entries, "cancelled").await;+ return outcome;+ }+ match forward_one(leader_backend, max_stash_wait, partition, &entry.item).await {+ Disposition::Reply {+ response,+ outcome: label,+ } => {+ let size = entry.item.approximate_size();+ metrics::histogram!("personhog_router_stash_wait_duration_ms")+ .record(entry.item.enqueued_at.elapsed().as_secs_f64() * 1000.0);+ if entry.item.reply.send(response).is_err() {+ metrics::counter!("personhog_router_stash_dropped_total").increment(1);}+ metrics::counter!(+ "personhog_router_stash_drained_total",+ "outcome" => label+ )+ .increment(1);+ session.complete(run.key, size).await;+ outcome.completed += 1;}- return;- }- let chunk: Vec<Vec<StashedRequest>> = (&mut groups_iter).take(concurrency).collect();- if chunk.is_empty() {- break;- }- let futures = chunk.into_iter().map(|group| {- let leader = Arc::clone(&leader_backend);- async move {- for req in group {- forward_one(leader.as_ref(), max_stash_wait, partition, req).await;+ Disposition::Bounce(reason) => {+ if matches!(reason, BounceReason::Transport) {+ entry.item.possibly_applied = true;}+ put_back_rest(session, run.key, entry, entries, reason.label()).await;+ outcome.bounced = true;+ return outcome;}- });- join_all(futures).await;- }-}--/// 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);+ outcome}#[async_trait]@@ -270,57 +279,83 @@ impl StashHandler for RouterStashHandler {new_owner: &str,cancel: CancellationToken,) -> CoordResult<()> {+ let stash_table = self.leader_backend.stash_table();+ let Some(session) = stash_table.drain_session(partition) else {+ // Nothing stashed — the partition never froze, or a prior+ // drain already settled it.+ return Ok(());+ };let drain_start = Instant::now();tracing::info!(partition, new_owner, "draining stash to new owner");// Drop the cached gRPC client for the new owner so the first// post-handoff request opens a fresh connection. The old- // owner's client entry will simply age out — the routing table- // no longer points at it, so it's never reused.+ // owner's entry stays in the cache unused — the routing table+ // no longer points at it — and is reclaimed only if that+ // address is ever resolved again; the cache has no eviction.self.leader_backend.clear_client_cache(new_owner);- 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(AtomicU64::new(0));- let counter = Arc::clone(&total_drained);- let stash_table = self.leader_backend.stash_table();+ let mut completed_total: u64 = 0;+ let mut bounced_waves: u32 = 0;+ loop {+ if cancel.is_cancelled() {+ // Paused or superseded between waves: nothing is in+ // flight, the backlog stays parked for the successor.+ break;+ }+ let taken = session.take_for_attempt(self.drain_concurrency).await;+ if taken.is_empty() {+ if session.finish_if_settled().await {+ break;+ }+ // An arrival raced the settle check; take again.+ continue;+ }++ let outcomes = join_all(taken.into_iter().map(|run| {+ forward_key_run(+ &self.leader_backend,+ &session,+ self.max_stash_wait,+ partition,+ &cancel,+ run,+ )+ }))+ .await;+ completed_total += outcomes.iter().map(|o| o.completed).sum::<u64>();- // Drain loop: each batch the underlying `StashTable::drain`- // hands us is forwarded with per-key fan-out. New requests- // arriving during drain land on the same queue and are- // delivered as a subsequent batch, preserving order.- stash_table- .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(- leader,- max_stash_wait,- drain_concurrency,+ if outcomes.iter().any(|o| o.bounced) {+ bounced_waves += 1;+ if bounced_waves >= MAX_CONSECUTIVE_BOUNCES {+ tracing::info!(partition,- &cancel,- batch,- )- .await;- counter.fetch_add(batch_size, Ordering::Relaxed);+ new_owner,+ waves = bounced_waves,+ "target still bouncing after repeated waves; \+ yielding drain lane to the reconcile pass"+ );+ break;}- })- .await;+ tokio::select! {+ _ = cancel.cancelled() => break,+ _ = tokio::time::sleep(BOUNCE_BACKOFF) => {}+ }+ } else {+ bounced_waves = 0;+ }+ }- let total = total_drained.load(Ordering::Relaxed);- metrics::histogram!("personhog_router_stash_drain_batch_size").record(total as f64);+ metrics::histogram!("personhog_router_stash_drain_batch_size")+ .record(completed_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);tracing::info!(partition,new_owner,- stashed_count = total,+ stashed_count = completed_total,drain_ms,- "drain complete"+ "drain finished");Ok(())}diff --git a/rust/personhog-router/tests/common/mod.rs b/rust/personhog-router/tests/common/mod.rsindex 48dddb92d3c3..ed84e5892c14 100644--- a/rust/personhog-router/tests/common/mod.rs+++ b/rust/personhog-router/tests/common/mod.rs@@ -2,6 +2,7 @@use std::collections::HashMap;use std::net::SocketAddr;+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Arc;use std::time::Duration;@@ -646,16 +647,18 @@ pub fn create_test_person() -> Person {/// stamps the header, not just that the body arrives intact.pub struct TestLeaderService {persons: DashMap<(i64, i64), Person>,- /// When true, writes are rejected with FailedPrecondition, mimicking- /// a leader whose partition is write-fenced for a handoff.- fenced: bool,+ /// While true, writes are rejected with FailedPrecondition, mimicking+ /// a leader whose partition is write-fenced for a handoff. Shared and+ /// runtime-toggleable so tests can clear the fence mid-drain, the way+ /// a real fence clears in watch-propagation time.+ fenced: Arc<AtomicBool>,}impl TestLeaderService {pub fn new() -> Self {Self {persons: DashMap::new(),- fenced: false,+ fenced: Arc::new(AtomicBool::new(false)),}}@@ -664,10 +667,16 @@ impl TestLeaderService {self}- pub fn fenced(mut self) -> Self {- self.fenced = true;+ pub fn fenced(self) -> Self {+ self.fenced.store(true, Ordering::SeqCst);self}++ /// Handle for flipping the fence after the service has been moved+ /// into the server.+ pub fn fence_flag(&self) -> Arc<AtomicBool> {+ Arc::clone(&self.fenced)+ }}/// Extract the routing partition from `x-partition` metadata, matching the@@ -712,7 +721,7 @@ impl PersonHogLeader for TestLeaderService {) -> Result<Response<UpdatePersonPropertiesResponse>, Status> {require_partition_metadata(&request)?;let req = request.into_inner();- if self.fenced {+ if self.fenced.load(Ordering::SeqCst) {return Err(Status::failed_precondition("partition is fenced for handoff; writes are rejected",));@@ -759,7 +768,23 @@ impl PersonHogLeader for TestLeaderService {pub async fn start_test_leader(service: TestLeaderService) -> SocketAddr {let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();let addr = listener.local_addr().unwrap();+ serve_test_leader(listener, service);+ tokio::time::sleep(Duration::from_millis(10)).await;+ addr+}++/// Start the test leader on a specific address. Used by tests that+/// reserve an address up front so the backend can dial it — and fail at+/// the transport layer — before the leader exists.+pub async fn start_test_leader_at(addr: SocketAddr, service: TestLeaderService) {+ let listener = TcpListener::bind(addr)+ .await+ .expect("reserved leader address must be bindable");+ serve_test_leader(listener, service);+ tokio::time::sleep(Duration::from_millis(10)).await;+}+fn serve_test_leader(listener: TcpListener, service: TestLeaderService) {tokio::spawn(async move {Server::builder().add_service(@@ -769,10 +794,6 @@ pub async fn start_test_leader(service: TestLeaderService) -> SocketAddr {.await.unwrap();});-- tokio::time::sleep(Duration::from_millis(10)).await;-- addr}// ============================================================@@ -796,11 +817,6 @@ fn make_replica_backend(replica_addr: SocketAddr) -> Arc<ReplicaBackend> {}fn make_leader_backend(leader_addr: SocketAddr, num_partitions: u32) -> Arc<LeaderBackend> {- let retry_config = RetryConfig {- max_retries: 1,- initial_backoff_ms: 1,- max_backoff_ms: 1,- };let mut routing = HashMap::new();for p in 0..num_partitions {routing.insert(p, "leader-0".to_string());@@ -815,7 +831,6 @@ fn make_leader_backend(leader_addr: SocketAddr, num_partitions: u32) -> Arc<LeadLeaderBackendConfig {num_partitions,timeout: Duration::from_secs(5),- retry_config,},StashTable::with_bounds(usize::MAX, usize::MAX),))diff --git a/rust/personhog-router/tests/stash_integration.rs b/rust/personhog-router/tests/stash_integration.rsindex b524b6047886..23ecb2ee7499 100644--- a/rust/personhog-router/tests/stash_integration.rs+++ b/rust/personhog-router/tests/stash_integration.rs@@ -7,11 +7,12 @@mod common;use std::collections::HashMap;+use std::sync::atomic::Ordering;use std::sync::Arc;use std::time::Duration;use bytes::Bytes;-use common::{create_test_person, start_test_leader, TestLeaderService};+use common::{create_test_person, start_test_leader, start_test_leader_at, TestLeaderService};use http::HeaderMap;use http_body_util::BodyExt;use personhog_coordination::routing_table::StashHandler;@@ -20,7 +21,6 @@ use personhog_proto::personhog::types::v1::{UpdatePersonPropertiesResponse,};use personhog_router::backend::{LeaderBackend, LeaderBackendConfig, StashTable};-use personhog_router::config::RetryConfig;use personhog_router::stash_handler::RouterStashHandler;use prost::Message;use tokio::sync::RwLock;@@ -30,14 +30,6 @@ use tonic::Code;const NUM_PARTITIONS: u32 = 8;-fn retry_config() -> RetryConfig {- RetryConfig {- max_retries: 0,- initial_backoff_ms: 1,- max_backoff_ms: 1,- }-}-/// Generous default deadline for tests — long enough that no normal/// drain hits it, so tests of the success path don't accidentally/// expire requests. The `stash_full_…` and `stash_wait_exceeded_…`@@ -73,7 +65,6 @@ async fn make_backend(leader_addr: std::net::SocketAddr, stash: StashTable) -> ALeaderBackendConfig {num_partitions: NUM_PARTITIONS,timeout: Duration::from_secs(5),- retry_config: retry_config(),},stash,))@@ -526,27 +517,27 @@ async fn stash_wait_exceeded_returns_unavailable() {);}-/// A drain that races the target leader's fence (a cancellation's-/// drain-back arriving before the old owner's resume, or a completion's-/// drain hitting a pod mid-cutover) gets FailedPrecondition from the-/// leader — but the condition clears in watch-propagation time, so the-/// client must see the same definitive-retry UNAVAILABLE contract as the-/// deadline path, not a "do not retry" error for a write that was never-/// acked.+/// A drain that races the target leader's fence (a reaffirm's drain-back+/// arriving before the owner's resume, or a completion's drain hitting a+/// pod mid-cutover) gets FailedPrecondition from the leader — a+/// condition that clears in watch-propagation time. The bounce must be+/// invisible to the client: the request stays parked (no error escapes),+/// the drain eventually yields its lane, and a later drain — the+/// reconcile pass re-requests one every tick — delivers the write once+/// the fence clears.#[tokio::test]-async fn fenced_leader_during_drain_returns_unavailable() {+async fn fence_bounce_parks_requests_until_a_later_drain_delivers() {let person = create_test_person();- let leader_addr = start_test_leader(- TestLeaderService::new()- .with_person(person.clone())- .fenced(),- )- .await;+ let service = TestLeaderService::new()+ .with_person(person.clone())+ .fenced();+ let fence = service.fence_flag();+ let leader_addr = start_test_leader(service).await;let stash = StashTable::with_bounds(usize::MAX, usize::MAX);let backend = make_backend(leader_addr, stash.clone()).await;- // Generous deadline so only the fence-remap path can produce the- // UNAVAILABLE, never the deadline path.+ // Generous deadline so the deadline path can never produce a client+ // error and mask a bounce that wrongly surfaced one.let handler = RouterStashHandler::new(Arc::clone(&backend), Duration::from_secs(60), 4);let partition = backend.partition_for_person(person.team_id, person.id);@@ -555,24 +546,207 @@ async fn fenced_leader_during_drain_returns_unavailable() {let req = mk_request(person.team_id, person.id, "[email protected]");let backend_for_call = Arc::clone(&backend);let pending = tokio::spawn(async move { forward(&backend_for_call, req).await });+ // Let the request park before draining, so the drain can't settle an+ // empty queue and evict the entry before the request arrives.+ tokio::time::sleep(Duration::from_millis(50)).await;++ // First drain: every wave bounces, so the drain backs off, retries,+ // and yields its lane with the request still parked.+ handler+ .drain_stash(partition, "leader-new", CancellationToken::new())+ .await+ .unwrap();+ assert!(+ !pending.is_finished(),+ "a fence bounce must not surface any outcome to the client"+ );++ // The fence clears; the next requested drain (the reconcile pass+ // re-requests one every tick in production) delivers the write.+ fence.store(false, Ordering::SeqCst);+ handler+ .drain_stash(partition, "leader-new", CancellationToken::new())+ .await+ .unwrap();++ let response = pending.await.unwrap();+ decode_response::<UpdatePersonPropertiesResponse>(response)+ .await+ .expect("the post-fence drain must deliver the parked write");+}++/// A transport failure during drain — the target unreachable once the+/// backend's own transient retries are exhausted — must bounce, not+/// fail the client: the request may or may not have reached the leader,+/// and the idempotency contract makes replaying it safe, while erroring+/// would push that ambiguity onto the client. The drain yields with the+/// request parked; once the target is dialable, a later drain replays+/// and delivers it.+#[tokio::test]+async fn transport_failure_parks_requests_until_a_later_drain_delivers() {+ let person = create_test_person();+ // Reserve an address with nothing listening on it, so dials fail at+ // the transport layer (connection refused) until the leader starts.+ let reserved = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let leader_addr = reserved.local_addr().unwrap();+ drop(reserved);++ let stash = StashTable::with_bounds(usize::MAX, usize::MAX);+ let backend = make_backend(leader_addr, stash.clone()).await;+ // Generous deadline so the deadline path can never produce a client+ // error and mask a bounce that wrongly surfaced one.+ let handler = RouterStashHandler::new(Arc::clone(&backend), Duration::from_secs(60), 4);++ let partition = backend.partition_for_person(person.team_id, person.id);+ handler.begin_stash(partition, "leader-new").await.unwrap();++ let req = mk_request(person.team_id, person.id, "[email protected]");+ let backend_for_call = Arc::clone(&backend);+ let pending = tokio::spawn(async move { forward(&backend_for_call, req).await });+ // Let the request park before draining, so the drain can't settle an+ // empty queue and evict the entry before the request arrives.tokio::time::sleep(Duration::from_millis(50)).await;+ // First drain: every wave fails at the transport layer, so the+ // drain bounces, backs off, and yields with the request parked.+ handler+ .drain_stash(partition, "leader-new", CancellationToken::new())+ .await+ .unwrap();+ assert!(+ !pending.is_finished(),+ "a transport bounce must not surface any outcome to the client"+ );++ // The leader comes up on the reserved address; the next requested+ // drain (the reconcile pass re-requests one every tick in+ // production) replays and delivers.+ start_test_leader_at(+ leader_addr,+ TestLeaderService::new().with_person(person.clone()),+ )+ .await;handler.drain_stash(partition, "leader-new", CancellationToken::new()).await.unwrap();let response = pending.await.unwrap();+ decode_response::<UpdatePersonPropertiesResponse>(response)+ .await+ .expect("the post-recovery drain must deliver the parked write");+}++/// The live path's re-entrant retry: a write that races a fence — no+/// stash open, the leader still settling — is held by the router and+/// re-attempted, so the client sees a slow success instead of a+/// `FAILED_PRECONDITION` it would not retry.+#[tokio::test]+async fn a_live_write_rides_out_a_fence_via_router_retry() {+ let person = create_test_person();+ let service = TestLeaderService::new()+ .with_person(person.clone())+ .fenced();+ let fence = service.fence_flag();+ let leader_addr = start_test_leader(service).await;++ let stash = StashTable::with_bounds(usize::MAX, usize::MAX);+ let backend = make_backend(leader_addr, stash.clone()).await;++ // The fence clears mid-retry, as it does in production once the+ // pod's watch delivers the phase change.+ tokio::spawn({+ let fence = Arc::clone(&fence);+ async move {+ tokio::time::sleep(Duration::from_millis(200)).await;+ fence.store(false, Ordering::SeqCst);+ }+ });++ let req = mk_request(person.team_id, person.id, "[email protected]");+ let response = forward(&backend, req).await;+ decode_response::<UpdatePersonPropertiesResponse>(response)+ .await+ .expect("the router's retry must absorb the fence and deliver the write");+}++/// A router whose view never updates (the fence never clears from its+/// perspective) must not hold requests forever: the bounce budget runs+/// out and the client gets a retryable `UNAVAILABLE` — never the+/// `FAILED_PRECONDITION` the leader actually answered with, which+/// clients read as "do not retry".+#[tokio::test]+async fn a_live_write_past_the_bounce_budget_fails_unavailable() {+ let person = create_test_person();+ let leader_addr = start_test_leader(+ TestLeaderService::new()+ .with_person(person.clone())+ .fenced(),+ )+ .await;++ let stash = StashTable::with_bounds(usize::MAX, usize::MAX);+ let backend = make_backend(leader_addr, stash.clone()).await;++ let req = mk_request(person.team_id, person.id, "[email protected]");+ let response = forward(&backend, req).await;let code = decode_response::<UpdatePersonPropertiesResponse>(response).await- .expect_err("fenced leader must reject the drained write");+ .expect_err("a persistently fenced target must fail the write");assert_eq!(code,Code::Unavailable,- "fence rejections during drain must surface as retryable UNAVAILABLE"+ "bounce-budget exhaustion must surface as retryable UNAVAILABLE, never FAILED_PRECONDITION");}+/// The unified loop's marquee behavior: a live write bouncing off an+/// unreachable leader parks as soon as a handoff opens the stash —+/// because each retry re-enters the stash check — and is then delivered+/// by the drain to the recovered target. The client sees one slow+/// success; the pod failure and the handoff are both invisible.+#[tokio::test]+async fn a_bouncing_live_write_parks_once_the_stash_opens() {+ let person = create_test_person();+ // Reserve an address with nothing listening on it, so live forwards+ // fail at the transport layer until the leader starts.+ let reserved = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let leader_addr = reserved.local_addr().unwrap();+ drop(reserved);++ let stash = StashTable::with_bounds(usize::MAX, usize::MAX);+ let backend = make_backend(leader_addr, stash.clone()).await;+ let handler = RouterStashHandler::new(Arc::clone(&backend), Duration::from_secs(60), 4);++ let partition = backend.partition_for_person(person.team_id, person.id);+ let req = mk_request(person.team_id, person.id, "[email protected]");+ let backend_for_call = Arc::clone(&backend);+ let pending = tokio::spawn(async move { forward(&backend_for_call, req).await });++ // A handoff opens the stash while the write is bouncing; its next+ // re-entry parks it.+ tokio::time::sleep(Duration::from_millis(50)).await;+ handler.begin_stash(partition, "leader-new").await.unwrap();+ tokio::time::sleep(Duration::from_millis(200)).await;++ // The replacement leader comes up and the handoff completes; the+ // drain delivers the parked write.+ start_test_leader_at(+ leader_addr,+ TestLeaderService::new().with_person(person.clone()),+ )+ .await;+ handler+ .drain_stash(partition, "leader-new", CancellationToken::new())+ .await+ .unwrap();++ let response = pending.await.unwrap();+ decode_response::<UpdatePersonPropertiesResponse>(response)+ .await+ .expect("the drain must deliver the write that parked mid-retry");+}+/// The reason strong reads stash at all: a write parked in the stash is/// invisible everywhere until drain, so a strong read that raced ahead to/// the (frozen) old owner would violate read-your-write for the whole