Diffinery

homeflare/celldpublic

celld/crates/logic/log_evict.rs
266 lines · 10.1 KBRaw History
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 hysteresis: an evicted follower is
13//! quarantined from re-recruitment, and reconfigurations are rate-capped.
14//! The executor feeds observations and performs the swap; nothing here
15//! performs I/O or reads a clock.
16
17use std::collections::BTreeMap;
18use std::collections::VecDeque;
19
20use crate::NodeId;
21
22/// The constants are E8 targets, not commitments: the lab sweep measures
23/// them, and the env overrides exist so it can.
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub struct EvictionPolicy {
26 /// The absolute tail budget: a follower slower than this is suspect
27 /// regardless of its sibling.
28 pub budget_ms: u64,
29 /// The relative signal: suspect when the windowed median exceeds this
30 /// multiple of the sibling's windowed median.
31 pub sibling_factor: u64,
32 /// How long the windowed median must stay over budget before the
33 /// evict fires — one slow fsync is not a dying disk, and a median
34 /// cannot be captured by a single outlier the way a tail quantile is.
35 pub sustain_ms: u64,
36 /// The hard backstop: any single append outstanding this long evicts
37 /// immediately, sustain or none.
38 pub backstop_ms: u64,
39 /// An evicted follower is not re-recruited for this long.
40 pub quarantine_ms: u64,
41 /// At most one eviction-driven reconfiguration per interval.
42 pub min_swap_interval_ms: u64,
43 /// The sliding window the medians are computed over.
44 pub window_ms: u64,
45}
46
47impl Default for EvictionPolicy {
48 fn default() -> Self {
49 EvictionPolicy {
50 budget_ms: 25,
51 sibling_factor: 4,
52 sustain_ms: 2_000,
53 backstop_ms: 400,
54 quarantine_ms: 300_000,
55 min_swap_interval_ms: 10_000,
56 window_ms: 3_000,
57 }
58 }
59}
60
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62pub enum Verdict {
63 Healthy,
64 /// Over budget, sustain running; the executor need not act yet.
65 Suspect,
66 /// Swap this member out now.
67 Evict,
68}
69
70#[derive(Clone, Debug, Default)]
71struct MemberHealth {
72 /// (completed_at_ms, latency_ms), oldest first, pruned to the window.
73 samples: VecDeque<(u64, u64)>,
74 /// When the current in-flight append started, if one is out.
75 outstanding_since: Option<u64>,
76 /// When the windowed median first exceeded the threshold, while it
77 /// has stayed exceeded.
78 suspect_since: Option<u64>,
79}
80
81impl MemberHealth {
82 fn prune(&mut self, now_ms: u64, window_ms: u64) {
83 while let Some((at, _)) = self.samples.front() {
84 if at.saturating_add(window_ms) < now_ms {
85 self.samples.pop_front();
86 } else {
87 break;
88 }
89 }
90 }
91
92 fn median_ms(&self) -> Option<u64> {
93 if self.samples.is_empty() {
94 return None;
95 }
96 let mut sorted: Vec<u64> = self.samples.iter().map(|(_, ms)| *ms).collect();
97 sorted.sort_unstable();
98 Some(sorted[sorted.len() / 2])
99 }
100}
101
102/// The tracker for one ensemble's followers. Survives shipper swaps on the
103/// executor side; `reset` starts a fresh ensemble's bookkeeping while the
104/// quarantine ledger persists across it.
105#[derive(Clone, Debug, Default)]
106pub struct FollowerHealth {
107 members: BTreeMap<NodeId, MemberHealth>,
108 quarantined_until: BTreeMap<NodeId, u64>,
109 last_swap_ms: Option<u64>,
110}
111
112impl FollowerHealth {
113 /// A new ensemble: drop the members' windows, keep the quarantine
114 /// ledger — it is exactly the memory that stops flapping.
115 pub fn reset(&mut self) {
116 self.members.clear();
117 }
118
119 /// An append POST went out to `member`.
120 pub fn append_started(&mut self, member: &str, now_ms: u64) {
121 let health = self.members.entry(member.to_string()).or_default();
122 health.outstanding_since.get_or_insert(now_ms);
123 }
124
125 /// The append completed (ok or not) after `latency_ms`.
126 pub fn append_completed(&mut self, member: &str, now_ms: u64, latency_ms: u64) {
127 let health = self.members.entry(member.to_string()).or_default();
128 health.outstanding_since = None;
129 health.samples.push_back((now_ms, latency_ms));
130 }
131
132 /// The eviction decision for `member`, judged against its sibling's
133 /// windowed median. The executor calls this per member per tick (and
134 /// on every completion) and swaps on the first `Evict`.
135 pub fn verdict(
136 &mut self,
137 policy: &EvictionPolicy,
138 member: &str,
139 siblings: &[NodeId],
140 now_ms: u64,
141 ) -> Verdict {
142 let sibling_median = siblings
143 .iter()
144 .filter(|sibling| sibling.as_str() != member)
145 .filter_map(|sibling| {
146 let health = self.members.get_mut(sibling)?;
147 health.prune(now_ms, policy.window_ms);
148 health.median_ms()
149 })
150 .min();
151 let Some(health) = self.members.get_mut(member) else {
152 return Verdict::Healthy;
153 };
154 if let Some(since) = health.outstanding_since {
155 if now_ms.saturating_sub(since) >= policy.backstop_ms {
156 return Verdict::Evict;
157 }
158 }
159 health.prune(now_ms, policy.window_ms);
160 let Some(own_median) = health.median_ms() else {
161 return Verdict::Healthy;
162 };
163 let threshold = sibling_median
164 .map(|median| median.saturating_mul(policy.sibling_factor))
165 .unwrap_or(0)
166 .max(policy.budget_ms);
167 if own_median <= threshold {
168 health.suspect_since = None;
169 return Verdict::Healthy;
170 }
171 let since = *health.suspect_since.get_or_insert(now_ms);
172 if now_ms.saturating_sub(since) >= policy.sustain_ms {
173 Verdict::Evict
174 } else {
175 Verdict::Suspect
176 }
177 }
178
179 /// Record the eviction: quarantine the member and stamp the swap for
180 /// the rate cap.
181 pub fn evicted(&mut self, policy: &EvictionPolicy, member: &str, now_ms: u64) {
182 self.quarantined_until.insert(
183 member.to_string(),
184 now_ms.saturating_add(policy.quarantine_ms),
185 );
186 self.members.remove(member);
187 self.last_swap_ms = Some(now_ms);
188 }
189
190 /// The member answered an append with a protocol-level rejection a
191 /// healthy follower cannot produce: the route is missing, or the
192 /// response does not parse — a binary that does not speak the log
193 /// tier (the 0.2.x rolling-upgrade seam). The latency verdicts are
194 /// blind to this member, because its rejection is FAST and reads as
195 /// a healthy sample, so recruiting re-picks it forever and the
196 /// posture flaps once per repair tick. Incapability therefore feeds
197 /// the quarantine directly: the member sits out `quarantine_ms` and
198 /// the next rebuild recruits around it, or parks when no capable
199 /// peer remains. An epoch refusal (`ok: false` in a well-formed
200 /// response) is NOT incapability — a sealed or reconfigured
201 /// follower answers that way and recruits fine at the next epoch.
202 /// No `last_swap_ms` here: this is not an eviction-driven swap, and
203 /// the rebuild that follows must not be rate-limited away from the
204 /// capable peers that remain.
205 pub fn append_incapable(&mut self, policy: &EvictionPolicy, member: &str, now_ms: u64) {
206 self.quarantined_until.insert(
207 member.to_string(),
208 now_ms.saturating_add(policy.quarantine_ms),
209 );
210 self.members.remove(member);
211 }
212
213 /// May an eviction-driven swap happen now? A failed follower (a hard
214 /// error, not a gray tail) bypasses this — that swap is v0's existing
215 /// degrade path and correctness needs it regardless of cadence.
216 pub fn swap_allowed(&self, policy: &EvictionPolicy, now_ms: u64) -> bool {
217 self.last_swap_ms
218 .is_none_or(|last| now_ms.saturating_sub(last) >= policy.min_swap_interval_ms)
219 }
220
221 /// Is this candidate quarantined out of re-recruitment?
222 pub fn quarantined(&self, candidate: &str, now_ms: u64) -> bool {
223 self.quarantined_until
224 .get(candidate)
225 .is_some_and(|until| *until > now_ms)
226 }
227
228 /// Every member's append is simultaneously outstanding past the
229 /// backstop: the common cause is us — our NIC, our partition — not
230 /// two disks dying in the same instant. The executor degrades to
231 /// bucket posture WITHOUT quarantining anyone, so recruitment
232 /// recovers the moment connectivity does; quarantining every peer
233 /// for our own partition held a healed fleet on the bucket floor for
234 /// the full quarantine term. One member is not evidence of
235 /// correlation — a single-member stall keeps the ordinary eviction.
236 pub fn correlated_stall(
237 &self,
238 policy: &EvictionPolicy,
239 members: &[NodeId],
240 now_ms: u64,
241 ) -> bool {
242 members.len() >= 2
243 && members.iter().all(|member| {
244 self.members
245 .get(member)
246 .and_then(|health| health.outstanding_since)
247 .is_some_and(|since| now_ms.saturating_sub(since) >= policy.backstop_ms)
248 })
249 }
250
251 /// Does this member owe an idle probe? Quiet means no append in flight
252 /// and no completion within the interval — a member under real load
253 /// needs no synthetic samples.
254 pub fn probe_due(&self, member: &str, now_ms: u64, quiet_ms: u64) -> bool {
255 let Some(health) = self.members.get(member) else {
256 return true;
257 };
258 if health.outstanding_since.is_some() {
259 return false;
260 }
261 health
262 .samples
263 .back()
264 .is_none_or(|(at, _)| at.saturating_add(quiet_ms) < now_ms)
265 }
266}