| 1 | //! Maintenance-sweep decisions, reified sans-IO. The sweep in `main.rs` is the |
| 2 | //! densest remaining cluster of imperative coordination — idle/pressure |
| 3 | //! eviction, the alarm-pin residency gate, owed-alarm retry, death detection. |
| 4 | //! Each is a pure predicate over scalars the executor samples; the executor |
| 5 | //! keeps the locks, the registry, and the interleaving. This module grows one |
| 6 | //! decision at a time as the sweep is lifted. |
| 7 | |
| 8 | use crate::Ms; |
| 9 | |
| 10 | /// Whether an armed cell must stay resident, or may hibernate. |
| 11 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 12 | pub enum AlarmPin { |
| 13 | /// Keep the cell resident: the alarm fires too soon to bother, or its wake |
| 14 | /// entry is not yet durable to catch it after hibernation. |
| 15 | Hold, |
| 16 | /// The alarm is safely covered; the cell may hibernate. |
| 17 | Lift, |
| 18 | } |
| 19 | |
| 20 | /// The fail-closed hibernation gate for an armed cell. A cell hibernates only |
| 21 | /// when its alarm is far enough out to beat the stay-resident break-even AND |
| 22 | /// its wake entry is DURABLE in the bucket — no durable entry, no eviction, so |
| 23 | /// a lost index can never strand an armed alarm. |
| 24 | /// |
| 25 | /// `next_alarm_ms < 0` means no alarm is armed: nothing pins the cell. |
| 26 | pub fn alarm_pin( |
| 27 | next_alarm_ms: Ms, |
| 28 | now_ms: Ms, |
| 29 | resident_ms: Ms, |
| 30 | wake_covered: bool, |
| 31 | ) -> AlarmPin { |
| 32 | if next_alarm_ms < 0 { |
| 33 | return AlarmPin::Lift; |
| 34 | } |
| 35 | if next_alarm_ms - now_ms > resident_ms && wake_covered { |
| 36 | AlarmPin::Lift |
| 37 | } else { |
| 38 | AlarmPin::Hold |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | /// Whether the sweep evicts a cell on this pass, or keeps it resident. |
| 43 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 44 | pub enum Verdict { |
| 45 | Evict, |
| 46 | Keep, |
| 47 | } |
| 48 | |
| 49 | /// Ordinary recency eviction, with a pressure override. Under pressure the |
| 50 | /// sweep evicts regardless of how recently the cell was touched — shedding load |
| 51 | /// is the whole point; otherwise a cell is evicted only once it has been idle |
| 52 | /// for at least `idle_evict_s`. The armed-alarm pin is a separate, earlier gate |
| 53 | /// (`alarm_pin`); this decides an unpinned cell's fate. |
| 54 | pub fn idle(pressure_evict: bool, idle_s: u64, idle_evict_s: u64) -> Verdict { |
| 55 | if pressure_evict || idle_s >= idle_evict_s { |
| 56 | Verdict::Evict |
| 57 | } else { |
| 58 | Verdict::Keep |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | /// The durability gate before hibernating a cell: never evict local state the |
| 63 | /// bucket cannot restore at the current epoch. |
| 64 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 65 | pub enum ReplicaGate { |
| 66 | /// The current epoch is verified durable in the bucket; hibernation may |
| 67 | /// proceed. |
| 68 | Durable, |
| 69 | /// The epoch advanced since the replica check was sampled — the check is |
| 70 | /// stale; retry next sweep, quietly. |
| 71 | StaleCheck, |
| 72 | /// The checked epoch has no bucket replica — replication is wedged; hold |
| 73 | /// resident (the executor warns, deduplicated per epoch) rather than let the |
| 74 | /// cell become unrestorable. |
| 75 | Unreplicated, |
| 76 | } |
| 77 | |
| 78 | /// `checked_epoch`/`replicated` come from a replica LIST taken earlier in the |
| 79 | /// sweep; `epoch` is the cell's epoch now. The epoch-staleness check wins first |
| 80 | /// — a moved epoch means the durability verdict is about the wrong lineage. |
| 81 | pub fn replica_gate(epoch: u64, checked_epoch: u64, replicated: bool) -> ReplicaGate { |
| 82 | if epoch != checked_epoch { |
| 83 | ReplicaGate::StaleCheck |
| 84 | } else if !replicated { |
| 85 | ReplicaGate::Unreplicated |
| 86 | } else { |
| 87 | ReplicaGate::Durable |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | /// The pressure-eviction budget for one sweep pass — two counters that keep a |
| 92 | /// shed from overshooting or stalling. `to_evict` is the real cut needed to |
| 93 | /// reach the target; `to_nominate` is a small reserve beyond it so a pinned, |
| 94 | /// busy, or stale candidate cannot starve the pass. The load-bearing rule: the |
| 95 | /// real budget is spent ONLY on `commit`, called after a cell is actually |
| 96 | /// removed — spending it at nomination let candidates that never evicted eat the |
| 97 | /// cut and the controller settled below its floor. |
| 98 | #[derive(Clone, Copy, Debug)] |
| 99 | pub struct PressureBudget { |
| 100 | to_evict: usize, |
| 101 | to_nominate: usize, |
| 102 | } |
| 103 | |
| 104 | impl PressureBudget { |
| 105 | /// `reserve` (production: the hibernation concurrency) bounds how far past |
| 106 | /// the real cut the pass may nominate candidates. |
| 107 | pub fn new(resident_cells: usize, target: usize, reserve: usize) -> Self { |
| 108 | let to_evict = resident_cells.saturating_sub(target); |
| 109 | Self { to_evict, to_nominate: to_evict.saturating_add(reserve) } |
| 110 | } |
| 111 | |
| 112 | /// Room to nominate another eviction candidate this pass. |
| 113 | pub fn may_nominate(&self) -> bool { |
| 114 | self.to_nominate > 0 |
| 115 | } |
| 116 | |
| 117 | /// Nominate a candidate — spends the reserve, not the real cut. |
| 118 | pub fn nominate(&mut self) { |
| 119 | self.to_nominate = self.to_nominate.saturating_sub(1); |
| 120 | } |
| 121 | |
| 122 | /// Room to actually evict — the real cut, so the sweep never dips below the |
| 123 | /// target watermark. |
| 124 | pub fn may_evict(&self) -> bool { |
| 125 | self.to_evict > 0 |
| 126 | } |
| 127 | |
| 128 | /// Commit a real eviction. Call ONLY after the cell is removed. |
| 129 | pub fn commit(&mut self) { |
| 130 | self.to_evict = self.to_evict.saturating_sub(1); |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | /// One cell as the sweep's candidate selection reads it — a snapshot the |
| 135 | /// executor gathers (under its locks) so the selection itself is pure. No I/O, |
| 136 | /// no locks here. |
| 137 | pub struct CellState { |
| 138 | pub scope: String, |
| 139 | pub idle_s: u64, |
| 140 | /// A regular (non-hibernatable) WebSocket pins the actor. |
| 141 | pub has_regular_websocket: bool, |
| 142 | /// Live hibernatable-socket count — a handoff cannot move a live transport. |
| 143 | pub websocket_count: usize, |
| 144 | pub epoch: u64, |
| 145 | } |
| 146 | |
| 147 | /// The sweep's Phase-1 output: cells to replica-verify, and the subset selected |
| 148 | /// for pressure eviction. |
| 149 | #[derive(Default)] |
| 150 | pub struct CandidatePlan { |
| 151 | /// `(scope, epoch)` to check for a durable replica (the executor's I/O step). |
| 152 | pub replica_candidates: Vec<(String, u64)>, |
| 153 | /// Scopes nominated for pressure eviction (spent the reserve budget). |
| 154 | pub pressure_candidates: std::collections::HashSet<String>, |
| 155 | } |
| 156 | |
| 157 | /// Phase 1 of the maintenance sweep, reified: pick eviction candidates from |
| 158 | /// `cells` (given in eviction-priority — idle descending — order), nominating |
| 159 | /// pressure candidates against `budget`. Pure; the executor performs the |
| 160 | /// replica I/O and the eviction against this plan. |
| 161 | pub fn plan_candidates( |
| 162 | cells: &[CellState], |
| 163 | idle_evict_s: u64, |
| 164 | lazy_leases: bool, |
| 165 | pressure_release: bool, |
| 166 | budget: &mut Option<PressureBudget>, |
| 167 | ) -> CandidatePlan { |
| 168 | let mut plan = CandidatePlan::default(); |
| 169 | for c in cells { |
| 170 | let pressure_evict = budget.as_ref().is_some_and(|b| b.may_nominate()); |
| 171 | // Idle-young cells are only touched under pressure. |
| 172 | if c.idle_s < idle_evict_s && !pressure_evict { |
| 173 | continue; |
| 174 | } |
| 175 | if c.has_regular_websocket { |
| 176 | continue; |
| 177 | } |
| 178 | // A live host transport cannot move with ownership: skip when a lazy |
| 179 | // lease or a release-policy pressure handoff would migrate it. |
| 180 | let pressure_handoff = pressure_evict && pressure_release; |
| 181 | if (lazy_leases || pressure_handoff) && c.websocket_count > 0 { |
| 182 | continue; |
| 183 | } |
| 184 | plan.replica_candidates.push((c.scope.clone(), c.epoch)); |
| 185 | if pressure_evict { |
| 186 | plan.pressure_candidates.insert(c.scope.clone()); |
| 187 | if let Some(b) = budget.as_mut() { |
| 188 | b.nominate(); |
| 189 | } |
| 190 | } |
| 191 | } |
| 192 | plan |
| 193 | } |
| 194 | |
| 195 | /// The eviction verdict after the executor has won the close exclusion. |
| 196 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 197 | pub enum PostClose { |
| 198 | /// Remove the cell and hibernate it. |
| 199 | Evict, |
| 200 | /// Put it back — it became active, or its alarm changed, during the replica |
| 201 | /// I/O window. |
| 202 | Abort, |
| 203 | } |
| 204 | |
| 205 | /// Phase 2's post-close decision: after `begin_close` succeeds, the sweep |
| 206 | /// re-reads the cell's idle time and alarm (both may have moved during the |
| 207 | /// replica verification I/O) and decides evict-or-abort. `alarm_unchanged` is |
| 208 | /// the fresh alarm compared against the value the pin decision saw — a change |
| 209 | /// means the coverage check is stale and a refire could be lost. |
| 210 | pub fn decide_post_close( |
| 211 | current_idle: u64, |
| 212 | idle_evict_s: u64, |
| 213 | pressure_evict: bool, |
| 214 | alarm_unchanged: bool, |
| 215 | ) -> PostClose { |
| 216 | if idle(pressure_evict, current_idle, idle_evict_s) == Verdict::Keep { |
| 217 | return PostClose::Abort; |
| 218 | } |
| 219 | if !alarm_unchanged { |
| 220 | return PostClose::Abort; |
| 221 | } |
| 222 | PostClose::Evict |
| 223 | } |
| 224 | |
| 225 | /// Share of the residency ceiling that may be pinned by outbound sockets. |
| 226 | /// Half: enough headroom that the sweep always has something it is allowed to |
| 227 | /// evict, without making a legitimate socket workload useless. |
| 228 | pub const MAX_OUTBOUND_PIN_PERCENT: usize = 50; |
| 229 | |
| 230 | /// May another cell be pinned resident by an outbound WebSocket? |
| 231 | /// |
| 232 | /// An outbound socket is not hibernatable, so `plan_candidates` refuses to |
| 233 | /// evict its cell for as long as it is open. That is correct — a live host |
| 234 | /// transport cannot survive hibernation — but it means every pinned cell is |
| 235 | /// permanently removed from the eviction pool. Pin the whole ceiling and the |
| 236 | /// sweep has nothing left to nominate: residency can never fall, admission |
| 237 | /// waits for capacity that cannot be freed, and the node serves |
| 238 | /// `capacity_exhausted` until an application happens to close a socket. |
| 239 | /// |
| 240 | /// A per-cell ceiling does not bound this. One socket each across a thousand |
| 241 | /// cells pins a thousand cells. The budget has to be node-wide, counted in |
| 242 | /// pinned *cells* rather than sockets, because one socket is enough to pin. |
| 243 | pub fn may_pin_outbound(pinned_cells: usize, resident_high: Option<usize>) -> bool { |
| 244 | resident_high.is_none_or(|high| { |
| 245 | pinned_cells < high.saturating_mul(MAX_OUTBOUND_PIN_PERCENT) / 100 |
| 246 | }) |
| 247 | } |