From 85062d7259a8ec79918376501533084124d80646 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 09:42:53 -0600 Subject: [PATCH 1/3] Add spill pool failover planning model --- pkgs/id/crates/id-worlds/src/world/mod.rs | 10 +- .../crates/id-worlds/src/world/spill_pool.rs | 550 ++++++++++++++++++ 2 files changed, 559 insertions(+), 1 deletion(-) create mode 100644 pkgs/id/crates/id-worlds/src/world/spill_pool.rs diff --git a/pkgs/id/crates/id-worlds/src/world/mod.rs b/pkgs/id/crates/id-worlds/src/world/mod.rs index 84f7234129..f9ec7a0f03 100644 --- a/pkgs/id/crates/id-worlds/src/world/mod.rs +++ b/pkgs/id/crates/id-worlds/src/world/mod.rs @@ -48,6 +48,7 @@ mod replication; mod replication_receiver; pub mod signed; pub mod spill_gate; +pub mod spill_pool; mod upgrade; mod util; @@ -693,7 +694,11 @@ pub const WRITE_LEASE_RENEWAL_INTERVAL_MS: u64 = 10_000; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)] #[serde(rename_all = "snake_case")] pub enum LeaseRejectionReason { - /// The writer is not the current lease holder (or there is none). + /// No holder stands while the authority is fencing and selecting a + /// successor. The caller should retry with backoff against the pool. + #[error("world write rejected: holder_lost (retryable)")] + HolderLost, + /// The writer is not the current lease holder in steady state. #[error("world write rejected: not_holder (retryable)")] NotHolder, /// The writer presented an epoch other than the current one. @@ -872,6 +877,9 @@ impl WriteLease { presented_epoch: u64, now_ms: u64, ) -> Result<(), LeaseRejectionReason> { + if self.holder.is_none() { + return Err(LeaseRejectionReason::HolderLost); + } if self.holder.as_deref() != Some(writer) { return Err(LeaseRejectionReason::NotHolder); } diff --git a/pkgs/id/crates/id-worlds/src/world/spill_pool.rs b/pkgs/id/crates/id-worlds/src/world/spill_pool.rs new file mode 100644 index 0000000000..b0332c4dcb --- /dev/null +++ b/pkgs/id/crates/id-worlds/src/world/spill_pool.rs @@ -0,0 +1,550 @@ +//! Grantor-side eligibility and deterministic successor selection for spill v2. +//! +//! This policy object is deliberately not an authority: pool membership and +//! replica observations can nominate a successor, but only applying the +//! returned lease actions through the world's serialized append actor grants +//! write authority. In particular, a candidate's local state never advances +//! the world's epoch. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use super::{DO_WRITE_LEASE_HOLDER, WriteLease}; + +/// Default continuous reader observation window from design #5787 §2. +pub const READER_OBSERVATION_CYCLES: u8 = 10; + +/// Why a holder is being replaced. Death permits selecting another candidate +/// without stickiness; a recovery after a polite return may prefer the prior +/// holder when all higher-priority properties tie. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FailoverCause { + HolderExpired, + Recovery, +} + +/// The grantor's latest view of one configured pool member. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PoolMember { + /// Authenticated node identity, as established by the host adapter. + pub identity: String, + /// Whether the latest report authenticated as this roster member. + pub authenticated: bool, + /// Whether the host can currently reach the node. + pub reachable: bool, + /// Whether the host considers this node healthy. + pub healthy: bool, + /// Current journal replay watermark reported by the reader. + pub replay_position: u64, + /// Authoritative journal tip observed by the grantor. + pub journal_tip: u64, + /// Number of worlds this host currently holds. + pub holder_count: u32, + /// Consecutive renewal observations made within the catch-up bound. + pub tip_observation_cycles: u8, +} + +impl PoolMember { + /// Construct a configured member before any authenticated observations. + #[must_use] + pub fn configured(identity: impl Into) -> Self { + Self { + identity: identity.into(), + authenticated: false, + reachable: false, + healthy: false, + replay_position: 0, + journal_tip: 0, + holder_count: 0, + tip_observation_cycles: 0, + } + } + + /// Record one observation cycle. The reader-join window resets on an + /// out-of-bound lag, authentication failure, or reachability failure. + pub fn observe( + &mut self, + authenticated: bool, + reachable: bool, + healthy: bool, + replay_position: u64, + journal_tip: u64, + max_catch_up_lag: u64, + holder_count: u32, + ) { + let was_within_bound = self.authenticated + && self.reachable + && self.replay_position <= self.journal_tip + && self.journal_tip.saturating_sub(self.replay_position) <= max_catch_up_lag; + let within_bound = authenticated + && reachable + && replay_position <= journal_tip + && journal_tip.saturating_sub(replay_position) <= max_catch_up_lag; + self.tip_observation_cycles = if within_bound { + if was_within_bound { + self.tip_observation_cycles + .saturating_add(1) + .min(READER_OBSERVATION_CYCLES) + } else { + 1 + } + } else { + 0 + }; + self.authenticated = authenticated; + self.reachable = reachable; + self.healthy = healthy; + self.replay_position = replay_position; + self.journal_tip = journal_tip; + self.holder_count = holder_count; + } + + /// Whether this member can be selected for a grant to `journal_tip`. + #[must_use] + pub fn eligible(&self, journal_tip: u64, max_catch_up_lag: u64) -> bool { + self.authenticated + && self.reachable + && self.journal_tip == journal_tip + && self.replay_position <= journal_tip + && journal_tip.saturating_sub(self.replay_position) <= max_catch_up_lag + && self.tip_observation_cycles >= READER_OBSERVATION_CYCLES + } +} + +/// Grantor-side roster. Only explicitly configured identities can be +/// observed or selected; observations never grant authority by themselves. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpillPool { + members: BTreeMap, +} + +impl SpillPool { + /// Add a member to the grantor's roster. Reconfiguration resets its + /// reader observation window so stale eligibility cannot carry over. + pub fn configure(&mut self, identity: impl Into) -> &PoolMember { + let identity = identity.into(); + self.members + .insert(identity.clone(), PoolMember::configured(identity.clone())); + self.members + .get(&identity) + .expect("configured member inserted") + } + + /// Remove an identity from the roster. This does not change the active + /// lease; an active holder still requires a journaled boundary. + pub fn remove(&mut self, identity: &str) -> Option { + self.members.remove(identity) + } + + /// Record an authenticated host observation for a roster member. + pub fn observe( + &mut self, + identity: &str, + authenticated: bool, + reachable: bool, + healthy: bool, + replay_position: u64, + journal_tip: u64, + max_catch_up_lag: u64, + holder_count: u32, + ) -> bool { + let Some(member) = self.members.get_mut(identity) else { + return false; + }; + member.observe( + authenticated, + reachable, + healthy, + replay_position, + journal_tip, + max_catch_up_lag, + holder_count, + ); + true + } + + /// Inspect a configured member. + #[must_use] + pub fn member(&self, identity: &str) -> Option<&PoolMember> { + self.members.get(identity) + } + + /// Pick a deterministic eligible successor. Ordering follows #5787 §2: + /// exact tip first, healthy first, fewest held worlds, optional stickiness, + /// then lexical identity. + #[must_use] + pub fn select_successor( + &self, + journal_tip: u64, + max_catch_up_lag: u64, + previous_holder: Option<&str>, + cause: FailoverCause, + ) -> Option<&PoolMember> { + self.members + .values() + .filter(|member| member.eligible(journal_tip, max_catch_up_lag)) + .min_by_key(|member| { + ( + member.replay_position != journal_tip, + !member.healthy, + member.holder_count, + cause == FailoverCause::HolderExpired + || Some(member.identity.as_str()) != previous_holder, + member.identity.as_str(), + ) + }) + } + + /// Plan a failover after the authority-clock term expires. The plan + /// includes a revoke whenever a holder still stands and always puts that + /// fence before the grant. With no eligible pool member, the DO is the + /// safe fallback. Applying the plan remains the actor's responsibility. + pub fn plan_failover( + &self, + lease: &WriteLease, + now_ms: u64, + journal_tip: u64, + max_catch_up_lag: u64, + ) -> Result { + if lease.holder.is_some() && !lease.is_expired(now_ms) { + return Err(FailoverPlanError::TermStillLive); + } + + let former_holder = lease.holder.clone(); + let successor = self + .select_successor( + journal_tip, + max_catch_up_lag, + former_holder.as_deref(), + FailoverCause::HolderExpired, + ) + .map_or_else( + || DO_WRITE_LEASE_HOLDER.to_owned(), + |member| member.identity.clone(), + ); + + let mut actions = Vec::with_capacity(if former_holder.is_some() { 2 } else { 1 }); + let grant_epoch = if let Some(former_holder) = former_holder { + let revoke_epoch = lease + .epoch + .checked_add(1) + .ok_or(FailoverPlanError::EpochOverflow)?; + actions.push(LeaseAction::Revoke { + former_holder, + epoch: revoke_epoch, + }); + revoke_epoch + .checked_add(1) + .ok_or(FailoverPlanError::EpochOverflow)? + } else { + lease + .epoch + .checked_add(1) + .ok_or(FailoverPlanError::EpochOverflow)? + }; + actions.push(LeaseAction::Grant { + holder: successor, + epoch: grant_epoch, + }); + + Ok(FailoverPlan { + actions, + journal_tip, + }) + } +} + +/// An ordered, authority-ready lease transition. A grant after a standing +/// holder must be preceded by a revoke action in the same plan. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum LeaseAction { + Revoke { former_holder: String, epoch: u64 }, + Grant { holder: String, epoch: u64 }, +} + +/// Deterministic failover decision. `journal_tip` is the barrier a successor +/// must replay through before the host adapter resumes mutations. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FailoverPlan { + pub actions: Vec, + pub journal_tip: u64, +} + +impl FailoverPlan { + /// Whether the selected successor has replayed through the grant barrier. + #[must_use] + pub const fn barrier_reached(&self, replay_position: u64) -> bool { + replay_position >= self.journal_tip + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum FailoverPlanError { + #[error("write lease term has not expired on the authority clock")] + TermStillLive, + #[error("write lease epoch overflow")] + EpochOverflow, +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::world::{LeaseRejectionReason, LeaseWriteRejection}; + use proptest::prelude::*; + + fn eligible_member(pool: &mut SpillPool, identity: &str, tip: u64, load: u32) { + pool.configure(identity); + for _ in 0..READER_OBSERVATION_CYCLES { + assert!(pool.observe(identity, true, true, true, tip, tip, 0, load)); + } + } + + #[test] + fn reader_join_requires_a_continuous_ten_cycle_tip_window() { + let mut pool = SpillPool::default(); + pool.configure("reader"); + for _ in 0..(READER_OBSERVATION_CYCLES - 1) { + pool.observe("reader", true, true, true, 7, 7, 0, 0); + } + assert!(!pool.member("reader").unwrap().eligible(7, 0)); + pool.observe("reader", true, true, true, 6, 7, 1, 0); + for _ in 0..(READER_OBSERVATION_CYCLES - 1) { + pool.observe("reader", true, true, true, 7, 7, 0, 0); + } + assert!(!pool.member("reader").unwrap().eligible(7, 0)); + pool.observe("reader", true, true, true, 7, 7, 0, 0); + assert!(pool.member("reader").unwrap().eligible(7, 0)); + } + + #[test] + fn selection_prefers_tip_health_load_and_then_identity_deterministically() { + let mut pool = SpillPool::default(); + eligible_member(&mut pool, "lagging", 20, 0); + eligible_member(&mut pool, "z-healthy", 20, 1); + eligible_member(&mut pool, "a-healthy", 20, 1); + eligible_member(&mut pool, "unhealthy", 20, 0); + pool.observe("lagging", true, true, true, 19, 20, 1, 0); + pool.observe("unhealthy", true, true, false, 20, 20, 0, 0); + assert_eq!( + pool.select_successor(20, 1, None, FailoverCause::HolderExpired) + .map(|member| member.identity.as_str()), + Some("a-healthy") + ); + assert_eq!( + pool.select_successor(20, 1, Some("z-healthy"), FailoverCause::Recovery) + .map(|member| member.identity.as_str()), + Some("z-healthy") + ); + } + + #[test] + fn failover_fences_before_grant_and_advances_each_epoch() { + let mut pool = SpillPool::default(); + eligible_member(&mut pool, "successor", 50, 0); + let mut lease = WriteLease::bootstrap(); + lease + .apply_handoff(DO_WRITE_LEASE_HOLDER, "dead", 1, Some(30_000)) + .unwrap(); + + assert_eq!( + pool.plan_failover(&lease, 29_999, 50, 0), + Err(FailoverPlanError::TermStillLive) + ); + let plan = pool.plan_failover(&lease, 30_000, 50, 0).unwrap(); + assert_eq!( + plan.actions, + vec![ + LeaseAction::Revoke { + former_holder: "dead".into(), + epoch: 2, + }, + LeaseAction::Grant { + holder: "successor".into(), + epoch: 3, + }, + ] + ); + assert_eq!(plan.journal_tip, 50); + assert!(!plan.barrier_reached(49)); + assert!(plan.barrier_reached(50)); + lease.apply_revoke("dead", 2, "term expired").unwrap(); + lease.apply_grant("successor", 3, Some(60_000)).unwrap(); + assert_eq!(lease.holder.as_deref(), Some("successor")); + assert_eq!(lease.epoch, 3); + assert!(lease.validate_history().is_ok()); + } + + #[test] + fn no_eligible_successor_falls_back_to_do_after_fencing() { + let pool = SpillPool::default(); + let mut lease = WriteLease::bootstrap(); + lease + .apply_handoff(DO_WRITE_LEASE_HOLDER, "dead", 1, Some(1)) + .unwrap(); + assert_eq!( + pool.plan_failover(&lease, 1, 50, 0).unwrap().actions, + vec![ + LeaseAction::Revoke { + former_holder: "dead".into(), + epoch: 2, + }, + LeaseAction::Grant { + holder: DO_WRITE_LEASE_HOLDER.into(), + epoch: 3, + }, + ] + ); + } + + #[test] + fn no_standing_holder_grants_at_the_next_epoch() { + let pool = SpillPool::default(); + let mut lease = WriteLease::bootstrap(); + lease + .apply_handoff(DO_WRITE_LEASE_HOLDER, "dead", 1, Some(1)) + .unwrap(); + lease.apply_revoke("dead", 2, "term expired").unwrap(); + assert_eq!( + pool.plan_failover(&lease, 1, 50, 0).unwrap().actions, + vec![LeaseAction::Grant { + holder: DO_WRITE_LEASE_HOLDER.into(), + epoch: 3, + }] + ); + } + + #[test] + fn writes_during_the_fence_window_are_retryable_holder_lost() { + let mut lease = WriteLease::bootstrap(); + lease + .apply_handoff(DO_WRITE_LEASE_HOLDER, "old", 1, Some(10)) + .unwrap(); + lease.apply_revoke("old", 2, "term expired").unwrap(); + assert_eq!( + lease.check_writer("old", 1, 10), + Err(LeaseRejectionReason::HolderLost) + ); + } + + #[test] + fn fenced_holder_reconnect_is_rejected_and_auditable() { + let mut lease = WriteLease::bootstrap(); + lease + .apply_handoff(DO_WRITE_LEASE_HOLDER, "old", 1, Some(10)) + .unwrap(); + lease.apply_revoke("old", 2, "term expired").unwrap(); + lease.apply_grant("new", 3, Some(30)).unwrap(); + assert_eq!( + lease.check_writer("old", 1, 11), + Err(LeaseRejectionReason::NotHolder) + ); + lease + .apply_rejection(LeaseWriteRejection { + writer: "old".into(), + presented_epoch: 1, + operation_id: "reconnected-command".into(), + observed_epoch: 3, + reason: LeaseRejectionReason::NotHolder, + received_at_ms: 11, + }) + .unwrap(); + assert_eq!(lease.rejections().count(), 1); + } + + #[test] + fn failover_and_handback_races_have_one_serialized_winner() { + // Handback linearizes before expiry. The resulting DO lease blocks + // automatic failover from the old holder. + let mut handback_first = WriteLease::bootstrap(); + handback_first + .apply_handoff(DO_WRITE_LEASE_HOLDER, "native", 1, Some(30)) + .unwrap(); + assert!(handback_first.check_writer("native", 1, 29).is_ok()); + handback_first + .apply_handoff("native", DO_WRITE_LEASE_HOLDER, 2, None) + .unwrap(); + assert_eq!( + SpillPool::default().plan_failover(&handback_first, 30, 0, 0), + Err(FailoverPlanError::TermStillLive) + ); + + // Expiry linearizes first. The old holder is fenced and cannot hand + // back; automatic recovery uses revoke then grant from that state. + let mut failover_first = WriteLease::bootstrap(); + failover_first + .apply_handoff(DO_WRITE_LEASE_HOLDER, "native", 1, Some(30)) + .unwrap(); + assert_eq!( + failover_first.check_writer("native", 1, 30), + Err(LeaseRejectionReason::Expired) + ); + let plan = SpillPool::default() + .plan_failover(&failover_first, 30, 0, 0) + .unwrap(); + assert!(matches!( + plan.actions[0], + LeaseAction::Revoke { epoch: 2, .. } + )); + assert!(matches!( + plan.actions[1], + LeaseAction::Grant { epoch: 3, .. } + )); + } + + #[test] + fn grant_storm_cannot_regrant_before_the_new_term_expires() { + let pool = SpillPool::default(); + let mut lease = WriteLease::bootstrap(); + lease + .apply_handoff(DO_WRITE_LEASE_HOLDER, "first", 1, Some(10)) + .unwrap(); + lease.apply_revoke("first", 2, "term expired").unwrap(); + lease.apply_grant("second", 3, Some(40)).unwrap(); + assert_eq!( + pool.plan_failover(&lease, 39, 0, 0), + Err(FailoverPlanError::TermStillLive) + ); + let next = pool.plan_failover(&lease, 40, 0, 0).unwrap(); + assert!(matches!( + next.actions[0], + LeaseAction::Revoke { epoch: 4, .. } + )); + assert!(matches!( + next.actions[1], + LeaseAction::Grant { epoch: 5, .. } + )); + lease.validate_history().unwrap(); + } + + proptest! { + #[test] + fn every_failover_plan_fences_and_advances_one_global_epoch_chain(base_epoch in 1_u64..128) { + let mut lease = WriteLease::bootstrap(); + let mut holder = DO_WRITE_LEASE_HOLDER.to_owned(); + for epoch in 1..=base_epoch { + let next_holder = format!("holder-{epoch}"); + lease.apply_handoff(&holder, &next_holder, epoch, Some(1)).unwrap(); + holder = next_holder; + } + + let plan = SpillPool::default().plan_failover(&lease, 1, 0, 0).unwrap(); + prop_assert_eq!(plan.actions.len(), 2); + let LeaseAction::Revoke { former_holder, epoch: revoke_epoch } = &plan.actions[0] else { + prop_assert!(false, "a standing holder must be fenced before grant"); + unreachable!(); + }; + let LeaseAction::Grant { holder: successor, epoch: grant_epoch } = &plan.actions[1] else { + prop_assert!(false, "grant must follow the fence"); + unreachable!(); + }; + prop_assert_eq!(former_holder, &holder); + prop_assert_eq!(*revoke_epoch, base_epoch + 1); + prop_assert_eq!(*grant_epoch, base_epoch + 2); + + lease.apply_revoke(former_holder, *revoke_epoch, "expired").unwrap(); + lease.apply_grant(successor, *grant_epoch, Some(2)).unwrap(); + prop_assert!(lease.validate_history().is_ok()); + } + } +} From 0a02cf03a98336d1153d63a67b6ea1c6061e88de Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 09:49:08 -0600 Subject: [PATCH 2/3] Harden spill successor fencing plan --- .../crates/id-worlds/src/world/spill_pool.rs | 52 +++++++++++++------ 1 file changed, 37 insertions(+), 15 deletions(-) diff --git a/pkgs/id/crates/id-worlds/src/world/spill_pool.rs b/pkgs/id/crates/id-worlds/src/world/spill_pool.rs index b0332c4dcb..285c33a36d 100644 --- a/pkgs/id/crates/id-worlds/src/world/spill_pool.rs +++ b/pkgs/id/crates/id-worlds/src/world/spill_pool.rs @@ -183,7 +183,11 @@ impl SpillPool { ) -> Option<&PoolMember> { self.members .values() - .filter(|member| member.eligible(journal_tip, max_catch_up_lag)) + .filter(|member| { + member.eligible(journal_tip, max_catch_up_lag) + && (cause != FailoverCause::HolderExpired + || Some(member.identity.as_str()) != previous_holder) + }) .min_by_key(|member| { ( member.replay_position != journal_tip, @@ -267,11 +271,24 @@ pub enum LeaseAction { /// must replay through before the host adapter resumes mutations. #[derive(Clone, Debug, PartialEq, Eq)] pub struct FailoverPlan { - pub actions: Vec, - pub journal_tip: u64, + actions: Vec, + journal_tip: u64, } impl FailoverPlan { + /// Ordered authority actions. The list is immutable so callers cannot + /// accidentally move a grant ahead of its predecessor fence. + #[must_use] + pub fn actions(&self) -> &[LeaseAction] { + &self.actions + } + + /// Journal position the selected successor must replay through. + #[must_use] + pub const fn journal_tip(&self) -> u64 { + self.journal_tip + } + /// Whether the selected successor has replayed through the grant barrier. #[must_use] pub const fn barrier_reached(&self, replay_position: u64) -> bool { @@ -308,7 +325,7 @@ mod tests { pool.observe("reader", true, true, true, 7, 7, 0, 0); } assert!(!pool.member("reader").unwrap().eligible(7, 0)); - pool.observe("reader", true, true, true, 6, 7, 1, 0); + pool.observe("reader", true, true, true, 5, 7, 1, 0); for _ in 0..(READER_OBSERVATION_CYCLES - 1) { pool.observe("reader", true, true, true, 7, 7, 0, 0); } @@ -336,6 +353,11 @@ mod tests { .map(|member| member.identity.as_str()), Some("z-healthy") ); + assert_eq!( + pool.select_successor(20, 1, Some("z-healthy"), FailoverCause::HolderExpired) + .map(|member| member.identity.as_str()), + Some("a-healthy") + ); } #[test] @@ -353,7 +375,7 @@ mod tests { ); let plan = pool.plan_failover(&lease, 30_000, 50, 0).unwrap(); assert_eq!( - plan.actions, + plan.actions(), vec![ LeaseAction::Revoke { former_holder: "dead".into(), @@ -365,7 +387,7 @@ mod tests { }, ] ); - assert_eq!(plan.journal_tip, 50); + assert_eq!(plan.journal_tip(), 50); assert!(!plan.barrier_reached(49)); assert!(plan.barrier_reached(50)); lease.apply_revoke("dead", 2, "term expired").unwrap(); @@ -383,7 +405,7 @@ mod tests { .apply_handoff(DO_WRITE_LEASE_HOLDER, "dead", 1, Some(1)) .unwrap(); assert_eq!( - pool.plan_failover(&lease, 1, 50, 0).unwrap().actions, + pool.plan_failover(&lease, 1, 50, 0).unwrap().actions(), vec![ LeaseAction::Revoke { former_holder: "dead".into(), @@ -406,7 +428,7 @@ mod tests { .unwrap(); lease.apply_revoke("dead", 2, "term expired").unwrap(); assert_eq!( - pool.plan_failover(&lease, 1, 50, 0).unwrap().actions, + pool.plan_failover(&lease, 1, 50, 0).unwrap().actions(), vec![LeaseAction::Grant { holder: DO_WRITE_LEASE_HOLDER.into(), epoch: 3, @@ -483,11 +505,11 @@ mod tests { .plan_failover(&failover_first, 30, 0, 0) .unwrap(); assert!(matches!( - plan.actions[0], + plan.actions()[0], LeaseAction::Revoke { epoch: 2, .. } )); assert!(matches!( - plan.actions[1], + plan.actions()[1], LeaseAction::Grant { epoch: 3, .. } )); } @@ -507,11 +529,11 @@ mod tests { ); let next = pool.plan_failover(&lease, 40, 0, 0).unwrap(); assert!(matches!( - next.actions[0], + next.actions()[0], LeaseAction::Revoke { epoch: 4, .. } )); assert!(matches!( - next.actions[1], + next.actions()[1], LeaseAction::Grant { epoch: 5, .. } )); lease.validate_history().unwrap(); @@ -529,12 +551,12 @@ mod tests { } let plan = SpillPool::default().plan_failover(&lease, 1, 0, 0).unwrap(); - prop_assert_eq!(plan.actions.len(), 2); - let LeaseAction::Revoke { former_holder, epoch: revoke_epoch } = &plan.actions[0] else { + prop_assert_eq!(plan.actions().len(), 2); + let LeaseAction::Revoke { former_holder, epoch: revoke_epoch } = &plan.actions()[0] else { prop_assert!(false, "a standing holder must be fenced before grant"); unreachable!(); }; - let LeaseAction::Grant { holder: successor, epoch: grant_epoch } = &plan.actions[1] else { + let LeaseAction::Grant { holder: successor, epoch: grant_epoch } = &plan.actions()[1] else { prop_assert!(false, "grant must follow the fence"); unreachable!(); }; From 252d4c9e9da2a74296da7aa491f9189b2f57f3fc Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 09:59:16 -0600 Subject: [PATCH 3/3] Track distinct spill renewal cycles --- .../crates/id-worlds/src/world/spill_pool.rs | 100 ++++++++++++------ 1 file changed, 65 insertions(+), 35 deletions(-) diff --git a/pkgs/id/crates/id-worlds/src/world/spill_pool.rs b/pkgs/id/crates/id-worlds/src/world/spill_pool.rs index 285c33a36d..0564b5e36c 100644 --- a/pkgs/id/crates/id-worlds/src/world/spill_pool.rs +++ b/pkgs/id/crates/id-worlds/src/world/spill_pool.rs @@ -20,7 +20,9 @@ pub const READER_OBSERVATION_CYCLES: u8 = 10; /// holder when all higher-priority properties tie. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FailoverCause { + /// The previous holder's authority-clock term expired. HolderExpired, + /// Recovery after a non-death transition where stickiness may break ties. Recovery, } @@ -41,6 +43,8 @@ pub struct PoolMember { pub journal_tip: u64, /// Number of worlds this host currently holds. pub holder_count: u32, + /// Last authority renewal-cycle identifier observed for this reader. + pub last_renewal_cycle: Option, /// Consecutive renewal observations made within the catch-up bound. pub tip_observation_cycles: u8, } @@ -57,6 +61,7 @@ impl PoolMember { replay_position: 0, journal_tip: 0, holder_count: 0, + last_renewal_cycle: None, tip_observation_cycles: 0, } } @@ -65,6 +70,7 @@ impl PoolMember { /// out-of-bound lag, authentication failure, or reachability failure. pub fn observe( &mut self, + renewal_cycle: u64, authenticated: bool, reachable: bool, healthy: bool, @@ -81,8 +87,13 @@ impl PoolMember { && reachable && replay_position <= journal_tip && journal_tip.saturating_sub(replay_position) <= max_catch_up_lag; + let next_cycle = + self.last_renewal_cycle.and_then(|last| last.checked_add(1)) == Some(renewal_cycle); + let same_cycle = self.last_renewal_cycle == Some(renewal_cycle); self.tip_observation_cycles = if within_bound { - if was_within_bound { + if same_cycle { + self.tip_observation_cycles + } else if was_within_bound && next_cycle { self.tip_observation_cycles .saturating_add(1) .min(READER_OBSERVATION_CYCLES) @@ -92,6 +103,7 @@ impl PoolMember { } else { 0 }; + self.last_renewal_cycle = Some(renewal_cycle); self.authenticated = authenticated; self.reachable = reachable; self.healthy = healthy; @@ -124,11 +136,15 @@ impl SpillPool { /// reader observation window so stale eligibility cannot carry over. pub fn configure(&mut self, identity: impl Into) -> &PoolMember { let identity = identity.into(); - self.members - .insert(identity.clone(), PoolMember::configured(identity.clone())); - self.members - .get(&identity) - .expect("configured member inserted") + match self.members.entry(identity.clone()) { + std::collections::btree_map::Entry::Occupied(mut entry) => { + entry.insert(PoolMember::configured(identity)); + entry.into_mut() + } + std::collections::btree_map::Entry::Vacant(entry) => { + entry.insert(PoolMember::configured(identity)) + } + } } /// Remove an identity from the roster. This does not change the active @@ -141,6 +157,7 @@ impl SpillPool { pub fn observe( &mut self, identity: &str, + renewal_cycle: u64, authenticated: bool, reachable: bool, healthy: bool, @@ -153,6 +170,7 @@ impl SpillPool { return false; }; member.observe( + renewal_cycle, authenticated, reachable, healthy, @@ -254,7 +272,7 @@ impl SpillPool { Ok(FailoverPlan { actions, - journal_tip, + pre_grant_tip: journal_tip, }) } } @@ -263,16 +281,29 @@ impl SpillPool { /// holder must be preceded by a revoke action in the same plan. #[derive(Clone, Debug, PartialEq, Eq)] pub enum LeaseAction { - Revoke { former_holder: String, epoch: u64 }, - Grant { holder: String, epoch: u64 }, + /// Fence the standing holder at this resulting epoch. + Revoke { + /// Identity whose lease is being fenced. + former_holder: String, + /// Epoch established by the revoke record. + epoch: u64, + }, + /// Grant authority after the predecessor fence is journaled. + Grant { + /// Authenticated identity selected as the next holder. + holder: String, + /// Epoch established by the grant record. + epoch: u64, + }, } -/// Deterministic failover decision. `journal_tip` is the barrier a successor -/// must replay through before the host adapter resumes mutations. +/// Deterministic failover decision. `pre_grant_tip` is the journal tip used to +/// assess the candidate. The actor must capture the actual grant position +/// after appending the grant and use that position as the resume barrier. #[derive(Clone, Debug, PartialEq, Eq)] pub struct FailoverPlan { actions: Vec, - journal_tip: u64, + pre_grant_tip: u64, } impl FailoverPlan { @@ -283,28 +314,26 @@ impl FailoverPlan { &self.actions } - /// Journal position the selected successor must replay through. + /// Journal tip used to assess the successor before appending failover + /// actions. This is not the successor's grant barrier. #[must_use] - pub const fn journal_tip(&self) -> u64 { - self.journal_tip - } - - /// Whether the selected successor has replayed through the grant barrier. - #[must_use] - pub const fn barrier_reached(&self, replay_position: u64) -> bool { - replay_position >= self.journal_tip + pub const fn pre_grant_tip(&self) -> u64 { + self.pre_grant_tip } } #[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] pub enum FailoverPlanError { + /// The current holder has not expired on the authority clock. #[error("write lease term has not expired on the authority clock")] TermStillLive, + /// No next epoch can be represented by the journal format. #[error("write lease epoch overflow")] EpochOverflow, } #[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { use super::*; use crate::world::{LeaseRejectionReason, LeaseWriteRejection}; @@ -312,26 +341,29 @@ mod tests { fn eligible_member(pool: &mut SpillPool, identity: &str, tip: u64, load: u32) { pool.configure(identity); - for _ in 0..READER_OBSERVATION_CYCLES { - assert!(pool.observe(identity, true, true, true, tip, tip, 0, load)); + for cycle in 0..u64::from(READER_OBSERVATION_CYCLES) { + assert!(pool.observe(identity, cycle, true, true, true, tip, tip, 0, load)); } } #[test] - fn reader_join_requires_a_continuous_ten_cycle_tip_window() { + fn reader_join_requires_ten_distinct_consecutive_renewal_cycles() { let mut pool = SpillPool::default(); pool.configure("reader"); - for _ in 0..(READER_OBSERVATION_CYCLES - 1) { - pool.observe("reader", true, true, true, 7, 7, 0, 0); + for cycle in 0..u64::from(READER_OBSERVATION_CYCLES - 1) { + pool.observe("reader", cycle, true, true, true, 7, 7, 0, 0); } + pool.observe("reader", 8, true, true, true, 7, 7, 0, 0); assert!(!pool.member("reader").unwrap().eligible(7, 0)); - pool.observe("reader", true, true, true, 5, 7, 1, 0); - for _ in 0..(READER_OBSERVATION_CYCLES - 1) { - pool.observe("reader", true, true, true, 7, 7, 0, 0); + pool.observe("reader", 9, true, true, true, 5, 7, 1, 0); + for cycle in 10..19 { + pool.observe("reader", cycle, true, true, true, 7, 7, 0, 0); } assert!(!pool.member("reader").unwrap().eligible(7, 0)); - pool.observe("reader", true, true, true, 7, 7, 0, 0); + pool.observe("reader", 19, true, true, true, 7, 7, 0, 0); assert!(pool.member("reader").unwrap().eligible(7, 0)); + pool.observe("reader", 21, true, true, true, 7, 7, 0, 0); + assert!(!pool.member("reader").unwrap().eligible(7, 0)); } #[test] @@ -341,8 +373,8 @@ mod tests { eligible_member(&mut pool, "z-healthy", 20, 1); eligible_member(&mut pool, "a-healthy", 20, 1); eligible_member(&mut pool, "unhealthy", 20, 0); - pool.observe("lagging", true, true, true, 19, 20, 1, 0); - pool.observe("unhealthy", true, true, false, 20, 20, 0, 0); + pool.observe("lagging", 10, true, true, true, 19, 20, 1, 0); + pool.observe("unhealthy", 10, true, true, false, 20, 20, 0, 0); assert_eq!( pool.select_successor(20, 1, None, FailoverCause::HolderExpired) .map(|member| member.identity.as_str()), @@ -387,9 +419,7 @@ mod tests { }, ] ); - assert_eq!(plan.journal_tip(), 50); - assert!(!plan.barrier_reached(49)); - assert!(plan.barrier_reached(50)); + assert_eq!(plan.pre_grant_tip(), 50); lease.apply_revoke("dead", 2, "term expired").unwrap(); lease.apply_grant("successor", 3, Some(60_000)).unwrap(); assert_eq!(lease.holder.as_deref(), Some("successor"));