| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! The gray-follower eviction policy (sans-IO), the log tier's answer to |
| 4 | //! write-all's classic price: one slow follower stalls every ack, so the |
| 5 | //! leader evicts on suspicion and the empty-join reconfiguration makes a |
| 6 | //! false positive cost one flush plus one CAS. |
| 7 | //! |
| 8 | //! The decision: evict a follower |
| 9 | //! whose windowed append-latency tail exceeds |
| 10 | //! `max(absolute budget, k x sibling median)` sustained for a short |
| 11 | //! window, or whose single append has been outstanding past a hard |
| 12 | //! backstop. Flapping is bounded by rate-capping reconfigurations, not by |
| 13 | //! excluding the evicted member: slowness is transient and the latency rule |
| 14 | //! can judge it again. A member that cannot serve appends at all is a |
| 15 | //! different case and does sit out a term, because no latency verdict can |
| 16 | //! see it. |
| 17 | //! The executor feeds observations and performs the swap; nothing here |
| 18 | //! performs I/O or reads a clock. |
| 19 | |
| 20 | use std::collections::BTreeMap; |
| 21 | use std::collections::VecDeque; |
| 22 | |
| 23 | use crate::NodeId; |
| 24 | |
| 25 | /// The constants are E8 targets, not commitments: the lab sweep measures |
| 26 | /// them, and the env overrides exist so it can. |
| 27 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 28 | pub struct EvictionPolicy { |
| 29 | /// The absolute tail budget: a follower slower than this is suspect |
| 30 | /// regardless of its sibling. |
| 31 | pub budget_ms: u64, |
| 32 | /// The relative signal: suspect when the windowed median exceeds this |
| 33 | /// multiple of the sibling's windowed median. |
| 34 | pub sibling_factor: u64, |
| 35 | /// How long the windowed median must stay over budget before the |
| 36 | /// evict fires — one slow fsync is not a dying disk, and a median |
| 37 | /// cannot be captured by a single outlier the way a tail quantile is. |
| 38 | pub sustain_ms: u64, |
| 39 | /// The hard backstop: any single append outstanding this long evicts |
| 40 | /// immediately, sustain or none. The default covers the measured |
| 41 | /// append tail, not a guess: the worst uncensored measured append is |
| 42 | /// 923 ms with the tail right-censored above the |
| 43 | /// old 400 ms deadline, and the 2026-08-24 stream-fleet |
| 44 | /// verification took the same fleet from two gray evictions of |
| 45 | /// healthy members and 14.5% bucket-proof acks at 400 ms to zero and |
| 46 | /// 0.94% at this value. A truly dead member still evicts well inside |
| 47 | /// the 2 s sustain path's patience. |
| 48 | pub backstop_ms: u64, |
| 49 | /// How long a follower that cannot serve appends sits out recruitment. |
| 50 | /// This is the incapability term only; a gray follower is not excluded |
| 51 | /// by a clock (see `FollowerHealth::evicted`). |
| 52 | pub quarantine_ms: u64, |
| 53 | /// At most one eviction-driven reconfiguration per interval. |
| 54 | pub min_swap_interval_ms: u64, |
| 55 | /// The sliding window the medians are computed over. |
| 56 | pub window_ms: u64, |
| 57 | /// The fewest window samples a median may rest on before the sustain |
| 58 | /// rule may judge it. The 2026-08-26 overload ledger caught a healthy |
| 59 | /// member evicted on ONE 56 ms sample that a quiet window then held as |
| 60 | /// its "median" for the whole sustain; a single outlier is exactly what |
| 61 | /// the median exists to ignore, and one sample is no median at all. |
| 62 | pub min_samples: usize, |
| 63 | /// The stream hedge never arms below this, so a quiet window cannot |
| 64 | /// produce a hair trigger. Above the measured loaded honest service |
| 65 | /// p99 (~72 ms at 3,000 writes/s on the NVMe lab fleet, 2026-08-25) |
| 66 | /// with margin; the fixed 50 ms it replaces sat inside that tail and |
| 67 | /// its constant fires amplified into reseal churn (the |
| 68 | /// log-hedge-deadline design). |
| 69 | pub hedge_floor_ms: u64, |
| 70 | /// The hedge multiple of the fleet's windowed worst honest append — |
| 71 | /// the sibling-factor spirit: honest variance is bounded by a small |
| 72 | /// multiple of recently observed service. |
| 73 | pub hedge_factor: u64, |
| 74 | } |
| 75 | |
| 76 | impl Default for EvictionPolicy { |
| 77 | fn default() -> Self { |
| 78 | EvictionPolicy { |
| 79 | budget_ms: 25, |
| 80 | sibling_factor: 4, |
| 81 | sustain_ms: 2_000, |
| 82 | backstop_ms: 1_500, |
| 83 | quarantine_ms: 300_000, |
| 84 | min_swap_interval_ms: 10_000, |
| 85 | window_ms: 3_000, |
| 86 | min_samples: 5, |
| 87 | hedge_floor_ms: 250, |
| 88 | hedge_factor: 4, |
| 89 | } |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 94 | pub enum Verdict { |
| 95 | Healthy, |
| 96 | /// Over budget, sustain running; the executor need not act yet. |
| 97 | Suspect, |
| 98 | /// Swap this member out now. |
| 99 | Evict, |
| 100 | } |
| 101 | |
| 102 | /// Everything `verdict` computed on the way to its answer, so the executor |
| 103 | /// can log WHY a member was evicted instead of only that it was. The |
| 104 | /// 2026-08-26 overload investigation had to reconstruct these offline from |
| 105 | /// completed-append samples — and could not, because a backstop eviction's |
| 106 | /// evidence is precisely the append that never completed. |
| 107 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 108 | pub struct VerdictDetail { |
| 109 | /// `"backstop"`, `"sustain"`, or `""` when healthy. |
| 110 | pub rule: &'static str, |
| 111 | /// How long the current in-flight append has been outstanding. |
| 112 | pub outstanding_ms: u64, |
| 113 | /// The member's windowed median and how many samples it rests on. |
| 114 | pub own_median_ms: Option<u64>, |
| 115 | pub samples: usize, |
| 116 | /// The fastest sibling's windowed median, if any sibling has one. |
| 117 | pub sibling_median_ms: Option<u64>, |
| 118 | /// `max(budget, sibling_factor x sibling median)`. |
| 119 | pub threshold_ms: u64, |
| 120 | /// How long the median has stayed over the threshold. |
| 121 | pub suspect_ms: u64, |
| 122 | } |
| 123 | |
| 124 | #[derive(Clone, Debug, Default)] |
| 125 | struct MemberHealth { |
| 126 | /// (completed_at_ms, latency_ms), oldest first, pruned to the window. |
| 127 | samples: VecDeque<(u64, u64)>, |
| 128 | /// When the current in-flight append started, if one is out. |
| 129 | outstanding_since: Option<u64>, |
| 130 | /// When the windowed median first exceeded the threshold, while it |
| 131 | /// has stayed exceeded. |
| 132 | suspect_since: Option<u64>, |
| 133 | } |
| 134 | |
| 135 | impl MemberHealth { |
| 136 | fn prune(&mut self, now_ms: u64, window_ms: u64) { |
| 137 | while let Some((at, _)) = self.samples.front() { |
| 138 | if at.saturating_add(window_ms) < now_ms { |
| 139 | self.samples.pop_front(); |
| 140 | } else { |
| 141 | break; |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | fn median_ms(&self) -> Option<u64> { |
| 147 | if self.samples.is_empty() { |
| 148 | return None; |
| 149 | } |
| 150 | let mut sorted: Vec<u64> = self.samples.iter().map(|(_, ms)| *ms).collect(); |
| 151 | sorted.sort_unstable(); |
| 152 | Some(sorted[sorted.len() / 2]) |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | /// The tracker for one ensemble's followers. Survives shipper swaps on the |
| 157 | /// executor side; `reset` starts a fresh ensemble's bookkeeping while the |
| 158 | /// quarantine ledger persists across it. |
| 159 | #[derive(Clone, Debug, Default)] |
| 160 | pub struct FollowerHealth { |
| 161 | members: BTreeMap<NodeId, MemberHealth>, |
| 162 | quarantined_until: BTreeMap<NodeId, u64>, |
| 163 | last_swap_ms: Option<u64>, |
| 164 | } |
| 165 | |
| 166 | impl FollowerHealth { |
| 167 | /// A new ensemble: drop the members' windows, keep the quarantine |
| 168 | /// ledger — it is exactly the memory that stops flapping. |
| 169 | pub fn reset(&mut self) { |
| 170 | self.members.clear(); |
| 171 | } |
| 172 | |
| 173 | /// Return the completion time and latency for each recorded append. |
| 174 | #[cfg(celld_internal_tests)] |
| 175 | pub fn append_samples_for_test(&self, member: &str) -> Vec<(u64, u64)> { |
| 176 | self.members |
| 177 | .get(member) |
| 178 | .map(|health| health.samples.iter().copied().collect()) |
| 179 | .unwrap_or_default() |
| 180 | } |
| 181 | |
| 182 | /// An append POST went out to `member`. |
| 183 | pub fn append_started(&mut self, member: &str, now_ms: u64) { |
| 184 | let health = self.members.entry(member.to_string()).or_default(); |
| 185 | health.outstanding_since.get_or_insert(now_ms); |
| 186 | } |
| 187 | |
| 188 | /// The append completed (ok or not) after `latency_ms`. |
| 189 | pub fn append_completed(&mut self, member: &str, now_ms: u64, latency_ms: u64) { |
| 190 | let health = self.members.entry(member.to_string()).or_default(); |
| 191 | health.outstanding_since = None; |
| 192 | health.samples.push_back((now_ms, latency_ms)); |
| 193 | } |
| 194 | |
| 195 | /// The eviction decision for `member`, judged against its sibling's |
| 196 | /// windowed median. The executor calls this per member per tick (and |
| 197 | /// on every completion) and swaps on the first `Evict`. |
| 198 | pub fn verdict( |
| 199 | &mut self, |
| 200 | policy: &EvictionPolicy, |
| 201 | member: &str, |
| 202 | siblings: &[NodeId], |
| 203 | now_ms: u64, |
| 204 | ) -> Verdict { |
| 205 | self.verdict_detailed(policy, member, siblings, now_ms).0 |
| 206 | } |
| 207 | |
| 208 | /// `verdict` with its evidence. |
| 209 | pub fn verdict_detailed( |
| 210 | &mut self, |
| 211 | policy: &EvictionPolicy, |
| 212 | member: &str, |
| 213 | siblings: &[NodeId], |
| 214 | now_ms: u64, |
| 215 | ) -> (Verdict, VerdictDetail) { |
| 216 | let mut detail = VerdictDetail::default(); |
| 217 | let sibling_median = siblings |
| 218 | .iter() |
| 219 | .filter(|sibling| sibling.as_str() != member) |
| 220 | .filter_map(|sibling| { |
| 221 | let health = self.members.get_mut(sibling)?; |
| 222 | health.prune(now_ms, policy.window_ms); |
| 223 | health.median_ms() |
| 224 | }) |
| 225 | .min(); |
| 226 | detail.sibling_median_ms = sibling_median; |
| 227 | let Some(health) = self.members.get_mut(member) else { |
| 228 | return (Verdict::Healthy, detail); |
| 229 | }; |
| 230 | if let Some(since) = health.outstanding_since { |
| 231 | detail.outstanding_ms = now_ms.saturating_sub(since); |
| 232 | if detail.outstanding_ms >= policy.backstop_ms { |
| 233 | detail.rule = "backstop"; |
| 234 | return (Verdict::Evict, detail); |
| 235 | } |
| 236 | } |
| 237 | health.prune(now_ms, policy.window_ms); |
| 238 | detail.samples = health.samples.len(); |
| 239 | let Some(own_median) = health.median_ms() else { |
| 240 | return (Verdict::Healthy, detail); |
| 241 | }; |
| 242 | detail.own_median_ms = Some(own_median); |
| 243 | // Too few samples for a median to mean anything: not a verdict. |
| 244 | // The suspect clock does not run either — a member that goes quiet |
| 245 | // after one slow sample must not accrue sustain time on it. |
| 246 | if detail.samples < policy.min_samples { |
| 247 | health.suspect_since = None; |
| 248 | return (Verdict::Healthy, detail); |
| 249 | } |
| 250 | // A lone survivor has no relative signal, and the absolute budget |
| 251 | // alone was tuned as a floor under the sibling comparison, not as |
| 252 | // a verdict by itself: judging the last member against it is the |
| 253 | // cascade that empties an ensemble (the churn run's sixth eviction). |
| 254 | if sibling_median.is_none() && siblings.iter().any(|s| s.as_str() != member) { |
| 255 | health.suspect_since = None; |
| 256 | return (Verdict::Healthy, detail); |
| 257 | } |
| 258 | let threshold = sibling_median |
| 259 | .map(|median| median.saturating_mul(policy.sibling_factor)) |
| 260 | .unwrap_or(0) |
| 261 | .max(policy.budget_ms); |
| 262 | detail.threshold_ms = threshold; |
| 263 | if own_median <= threshold { |
| 264 | health.suspect_since = None; |
| 265 | return (Verdict::Healthy, detail); |
| 266 | } |
| 267 | let since = *health.suspect_since.get_or_insert(now_ms); |
| 268 | detail.suspect_ms = now_ms.saturating_sub(since); |
| 269 | if detail.suspect_ms >= policy.sustain_ms { |
| 270 | detail.rule = "sustain"; |
| 271 | (Verdict::Evict, detail) |
| 272 | } else { |
| 273 | (Verdict::Suspect, detail) |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | /// Record the eviction and stamp the swap for the rate cap. A gray |
| 278 | /// member is NOT quarantined. |
| 279 | /// |
| 280 | /// Slowness is transient and re-measurable, so excluding a member by a |
| 281 | /// clock decides in advance something the latency rule can decide again |
| 282 | /// on evidence. In-sync replica sets do not do it either: a lagging Kafka |
| 283 | /// replica rejoins its ISR as soon as it catches up, and the lag rule is |
| 284 | /// the whole membership test. |
| 285 | /// |
| 286 | /// It also cost us. An ensemble is at most two followers and a fleet |
| 287 | /// smaller than four nodes has no spare, so quarantining the evicted |
| 288 | /// member left nothing to recruit and every acknowledgement fell to the |
| 289 | /// bucket for the whole term. A measured A/B that varied only this term |
| 290 | /// on one three-node fleet read 906 ms at 300 s against 22 ms at 5 s, |
| 291 | /// with identical eviction counts in both arms: the evictions came from |
| 292 | /// load, and only the recovery differed. |
| 293 | /// |
| 294 | /// `min_swap_interval_ms` remains the anti-flap bound, and it is the one |
| 295 | /// that belongs here — it limits how often the ensemble may change, which |
| 296 | /// is the cost being avoided, rather than pre-judging which member is |
| 297 | /// fit. Incapability still quarantines: see `append_incapable`, whose |
| 298 | /// member cannot be judged by the latency rule at all. |
| 299 | pub fn evicted(&mut self, policy: &EvictionPolicy, member: &str, now_ms: u64) { |
| 300 | let _ = policy; |
| 301 | self.members.remove(member); |
| 302 | self.last_swap_ms = Some(now_ms); |
| 303 | } |
| 304 | |
| 305 | /// The member answered an append with a protocol-level rejection a |
| 306 | /// healthy follower cannot produce: the route is missing, or the |
| 307 | /// response does not parse — a binary that does not speak the log |
| 308 | /// tier (the 0.2.x rolling-upgrade seam). The latency verdicts are |
| 309 | /// blind to this member, because its rejection is FAST and reads as |
| 310 | /// a healthy sample, so recruiting re-picks it forever and the |
| 311 | /// posture flaps once per repair tick. Incapability therefore feeds |
| 312 | /// the quarantine directly: the member sits out `quarantine_ms` and |
| 313 | /// the next rebuild recruits around it, or parks when no capable |
| 314 | /// peer remains. An epoch refusal (`ok: false` in a well-formed |
| 315 | /// response) is NOT incapability — a sealed or reconfigured |
| 316 | /// follower answers that way and recruits fine at the next epoch. |
| 317 | /// No `last_swap_ms` here: this is not an eviction-driven swap, and |
| 318 | /// the rebuild that follows must not be rate-limited away from the |
| 319 | /// capable peers that remain. |
| 320 | pub fn append_incapable(&mut self, policy: &EvictionPolicy, member: &str, now_ms: u64) { |
| 321 | self.quarantined_until.insert( |
| 322 | member.to_string(), |
| 323 | now_ms.saturating_add(policy.quarantine_ms), |
| 324 | ); |
| 325 | self.members.remove(member); |
| 326 | } |
| 327 | |
| 328 | /// May an eviction-driven swap happen now? A failed follower (a hard |
| 329 | /// error, not a gray tail) bypasses this — that swap is v0's existing |
| 330 | /// degrade path and correctness needs it regardless of cadence. |
| 331 | pub fn swap_allowed(&self, policy: &EvictionPolicy, now_ms: u64) -> bool { |
| 332 | self.last_swap_ms |
| 333 | .is_none_or(|last| now_ms.saturating_sub(last) >= policy.min_swap_interval_ms) |
| 334 | } |
| 335 | |
| 336 | /// The stream hedge deadline: a head frame outstanding longer than |
| 337 | /// this is raced by one idempotent duplicate. Derived from the |
| 338 | /// fleet's windowed worst honest append, not fixed — fleet-wide so a |
| 339 | /// wedged member sticks out against its siblings and a member's own |
| 340 | /// decay cannot stretch its own leash (gradual decay is the eviction |
| 341 | /// machinery's case). The cap is two thirds of the backstop and the |
| 342 | /// floor yields to it, so the deadline stays strictly below the |
| 343 | /// backstop for every supported override — a reduced backstop |
| 344 | /// (`CELLD_LOG_EVICT_BACKSTOP_MS` under the floor) must not let |
| 345 | /// eviction, the expensive remedy, fire before the cheap one. A |
| 346 | /// backstop under 2 ms caps the deadline at zero, which the lane reads |
| 347 | /// as "no hedge": eviction is then the only remedy, by that policy. |
| 348 | pub fn hedge_deadline_ms(&mut self, policy: &EvictionPolicy, now_ms: u64) -> u64 { |
| 349 | let mut worst = 0_u64; |
| 350 | for health in self.members.values_mut() { |
| 351 | health.prune(now_ms, policy.window_ms); |
| 352 | for (_, latency_ms) in &health.samples { |
| 353 | worst = worst.max(*latency_ms); |
| 354 | } |
| 355 | } |
| 356 | let cap = (policy.backstop_ms / 3).saturating_mul(2); |
| 357 | let floor = policy.hedge_floor_ms.min(cap); |
| 358 | policy.hedge_factor.saturating_mul(worst).clamp(floor, cap) |
| 359 | } |
| 360 | |
| 361 | /// Is this candidate quarantined out of re-recruitment? |
| 362 | pub fn quarantined(&self, candidate: &str, now_ms: u64) -> bool { |
| 363 | self.quarantined_until |
| 364 | .get(candidate) |
| 365 | .is_some_and(|until| *until > now_ms) |
| 366 | } |
| 367 | |
| 368 | /// Every member's append is simultaneously outstanding past the |
| 369 | /// backstop: the common cause is us — our NIC, our partition — not |
| 370 | /// two disks dying in the same instant. The executor degrades to |
| 371 | /// bucket posture WITHOUT quarantining anyone, so recruitment |
| 372 | /// recovers the moment connectivity does; quarantining every peer |
| 373 | /// for our own partition held a healed fleet on the bucket floor for |
| 374 | /// the full quarantine term. One member is not evidence of |
| 375 | /// correlation — a single-member stall keeps the ordinary eviction. |
| 376 | pub fn correlated_stall( |
| 377 | &self, |
| 378 | policy: &EvictionPolicy, |
| 379 | members: &[NodeId], |
| 380 | now_ms: u64, |
| 381 | ) -> bool { |
| 382 | members.len() >= 2 |
| 383 | && members.iter().all(|member| { |
| 384 | self.members |
| 385 | .get(member) |
| 386 | .and_then(|health| health.outstanding_since) |
| 387 | .is_some_and(|since| now_ms.saturating_sub(since) >= policy.backstop_ms) |
| 388 | }) |
| 389 | } |
| 390 | |
| 391 | /// Does this member owe an idle probe? Quiet means no append in flight |
| 392 | /// and no completion within the interval — a member under real load |
| 393 | /// needs no synthetic samples. |
| 394 | pub fn probe_due(&self, member: &str, now_ms: u64, quiet_ms: u64) -> bool { |
| 395 | let Some(health) = self.members.get(member) else { |
| 396 | return true; |
| 397 | }; |
| 398 | if health.outstanding_since.is_some() { |
| 399 | return false; |
| 400 | } |
| 401 | health |
| 402 | .samples |
| 403 | .back() |
| 404 | .is_none_or(|(at, _)| at.saturating_add(quiet_ms) < now_ms) |
| 405 | } |
| 406 | } |