| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! Memory-pressure shedding as a pure classifier of a memory sample plus the |
| 4 | //! prior shedding state (the hysteresis latch). No I/O, no clock — the env |
| 5 | //! read that builds the config stays at the edge (`main.rs`), and so does the |
| 6 | //! measurement, which has to ask both the operating system and the allocator. |
| 7 | //! |
| 8 | //! Residency is deliberately *not* here. A node's cell count is a hard cap |
| 9 | //! enforced at admission ([`crate::State::has_capacity`]), self-limiting and |
| 10 | //! known exactly; it is not a resource that needs a proactive walk down. This |
| 11 | //! classifier answers only the other question — "is this node out of memory |
| 12 | //! and must give cells back to recover?" — which a cell count cannot answer. |
| 13 | //! Conflating the two produced the placement churn and the admission wedge; |
| 14 | //! splitting them is what keeps each decision small. |
| 15 | |
| 16 | /// Resource watermarks. Built once from the environment by the caller; the |
| 17 | /// core never reads the environment itself. Residency has no watermark here — |
| 18 | /// it is capped at admission. |
| 19 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] |
| 20 | pub struct PressureConfig { |
| 21 | /// The ceiling on the memory the cells hold. This is the ordinary limit, |
| 22 | /// and `CELLD_MAX_RSS_MB` sets it. |
| 23 | pub high_bytes: Option<u64>, |
| 24 | /// An absolute ceiling on the cgroup charge, or process RSS when the |
| 25 | /// process has no readable cgroup: 95% of the available memory. |
| 26 | /// |
| 27 | /// `high_bytes` applies to allocator-adjusted RSS and to the active cgroup |
| 28 | /// working set after the same allocator adjustment. The adjustment lets a |
| 29 | /// node recover after a free, and the cgroup measurement includes active |
| 30 | /// kernel charges outside RSS. Neither measurement includes every charge |
| 31 | /// that the cgroup limit uses. |
| 32 | /// |
| 33 | /// This is the floor under that trade. A container reads |
| 34 | /// `memory.current`, so kernel charges outside process RSS cannot hide |
| 35 | /// from it. |
| 36 | /// |
| 37 | /// It is a fixed share of the machine and is never derived from |
| 38 | /// `high_bytes`. A first attempt placed it "at least 125% of the ceiling", |
| 39 | /// which put it at exactly 100% of the machine for the default ceiling of |
| 40 | /// 80% -- above anything the kernel would let the process reach, so the |
| 41 | /// floor did not exist in the configuration that ships. See |
| 42 | /// [`PressureConfig::from_limits`]. |
| 43 | pub rss_hard_bytes: Option<u64>, |
| 44 | } |
| 45 | |
| 46 | /// Which ceilings are currently latched. Each one engages at its own ceiling |
| 47 | /// and releases at its own low watermark, so one crossing can never hold the |
| 48 | /// node against the other's watermark. |
| 49 | /// |
| 50 | /// This is two booleans rather than the reported reason, because the reason |
| 51 | /// names only the more serious crossing. Deriving the latches from it lets a |
| 52 | /// hard-cap crossing arm the ordinary ceiling, and then a node stays closed on |
| 53 | /// a ceiling it never crossed. |
| 54 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 55 | pub struct Latches { |
| 56 | pub memory: bool, |
| 57 | pub rss_hard: bool, |
| 58 | } |
| 59 | |
| 60 | /// Which measurement a walk down is working against. |
| 61 | /// |
| 62 | /// The futility stop compares a sample with the one the last cut measured, so |
| 63 | /// it has to know that the two samples are the same measurement. They are not |
| 64 | /// interchangeable: eviction moves the ordinary working-set figure at once and |
| 65 | /// may never move the complete cgroup charge at all. |
| 66 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 67 | pub enum Metric { |
| 68 | /// The greater of allocator-adjusted RSS and the allocator-adjusted active |
| 69 | /// cgroup working set. An eviction can return this memory. |
| 70 | InUse, |
| 71 | /// The complete cgroup charge, with process RSS as a host fallback. |
| 72 | Rss, |
| 73 | } |
| 74 | |
| 75 | /// A resource sample — the only input the classifier reads. `resident_cells` |
| 76 | /// is carried so a resource trigger can size its walk down as a proportion of |
| 77 | /// what is actually resident. |
| 78 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 79 | pub struct Load { |
| 80 | pub resident_cells: usize, |
| 81 | /// Reported to peers and operators, never decided on. |
| 82 | pub rss_bytes: u64, |
| 83 | /// RSS minus the pages the allocator keeps but nothing uses. This is the |
| 84 | /// ordinary pressure fallback when no cgroup working set is readable. |
| 85 | pub in_use_bytes: u64, |
| 86 | /// The cgroup charge after inactive file pages from `memory.stat` are |
| 87 | /// removed. `None` outside a readable Linux memory cgroup. |
| 88 | pub cgroup_working_set_bytes: Option<u64>, |
| 89 | /// The complete `memory.current` charge. This is the number the cgroup |
| 90 | /// limit constrains, including charges that process RSS does not contain. |
| 91 | /// `None` outside a readable Linux memory cgroup. |
| 92 | pub cgroup_current_bytes: Option<u64>, |
| 93 | } |
| 94 | |
| 95 | impl Load { |
| 96 | /// The ordinary pressure measurement. A cgroup working set contains active |
| 97 | /// kernel charges that process RSS omits. Subtract the same measured |
| 98 | /// allocator slack from it, or retained pages would recreate the admission |
| 99 | /// wedge through the cgroup path. The process measurement remains the floor |
| 100 | /// because cgroup and RSS accounting can differ for shared pages. |
| 101 | pub fn memory_bytes(self) -> u64 { |
| 102 | let allocator_slack = self.rss_bytes.saturating_sub(self.in_use_bytes); |
| 103 | let cgroup_in_use = self |
| 104 | .cgroup_working_set_bytes |
| 105 | .unwrap_or_default() |
| 106 | .saturating_sub(allocator_slack); |
| 107 | self.in_use_bytes.max(cgroup_in_use) |
| 108 | } |
| 109 | |
| 110 | /// The hard pressure measurement. `memory.current` is authoritative when |
| 111 | /// present because the cgroup limit constrains it, not process RSS. |
| 112 | pub fn hard_bytes(self) -> u64 { |
| 113 | self.cgroup_current_bytes.unwrap_or(self.rss_bytes) |
| 114 | } |
| 115 | |
| 116 | pub fn metric_bytes(self, metric: Metric) -> u64 { |
| 117 | match metric { |
| 118 | Metric::InUse => self.memory_bytes(), |
| 119 | Metric::Rss => self.hard_bytes(), |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | /// The latch engaged because the memory the cells hold crossed the ceiling. |
| 125 | /// This is the ordinary case, and shedding relieves it. |
| 126 | pub const SHED_MEMORY: &str = "memory"; |
| 127 | |
| 128 | /// The latch engaged because the complete cgroup charge, or the RSS fallback, |
| 129 | /// crossed the absolute cap. The string keeps its established telemetry name, |
| 130 | /// but a Linux container decides it from `memory.current`. |
| 131 | pub const SHED_RSS_HARD: &str = "rss-hard"; |
| 132 | |
| 133 | impl PressureConfig { |
| 134 | /// Build the watermarks from the machine and the operator's setting. |
| 135 | /// |
| 136 | /// The policy lives here, not at the edge, because it is arithmetic with a |
| 137 | /// correctness argument and requires explicit validation. The shell only |
| 138 | /// supplies the two facts it can read: how much memory the process can use, and what |
| 139 | /// `CELLD_MAX_RSS_MB` says. `None` for the setting means the default, and |
| 140 | /// `Some(0)` disables pressure shedding altogether. |
| 141 | /// |
| 142 | /// The absolute cap is 95% of the machine and is never derived from the |
| 143 | /// ceiling. A cap derived from the ceiling either lands above the machine |
| 144 | /// (so it never fires) or below the ceiling (so it fires first on every |
| 145 | /// sample and the classifier is reading the hard measurement again). Both |
| 146 | /// have shipped in this file; neither is a floor. |
| 147 | /// |
| 148 | /// When the machine size is unknown, the cap falls back to 125% of an |
| 149 | /// explicit ceiling. That is worse than a share of the machine and better |
| 150 | /// than no floor at all. |
| 151 | pub fn from_limits(total_memory_bytes: Option<u64>, max_rss_mb: Option<u64>) -> Self { |
| 152 | // A watermark of zero is worse than no watermark: every sample crosses |
| 153 | // it and none can clear it, so the node latches on its first sample and |
| 154 | // refuses every cell for its lifetime. A machine that reports nothing |
| 155 | // usable therefore gets no watermark at all. Linux reports 0 for a |
| 156 | // cgroup limit of `0` and for an unreadable `MemTotal`. |
| 157 | let usable = |bytes: u64| (bytes > 0).then_some(bytes); |
| 158 | let high_bytes = match max_rss_mb { |
| 159 | None => total_memory_bytes.and_then(|total| usable(total / 5 * 4)), |
| 160 | Some(0) => None, |
| 161 | Some(megabytes) => usable(megabytes.saturating_mul(1024 * 1024)), |
| 162 | }; |
| 163 | let rss_hard_bytes = high_bytes.and_then(|high| { |
| 164 | // `checked_mul`, because the fallback multiplies an operator's |
| 165 | // number: a saturating multiply followed by a divide would return a |
| 166 | // cap *below* the ceiling, which is the shape this avoids. |
| 167 | let fallback = high.checked_mul(5).map_or(u64::MAX, |scaled| scaled / 4); |
| 168 | let cap = total_memory_bytes |
| 169 | .and_then(|total| usable(total / 100 * 95)) |
| 170 | .unwrap_or(fallback); |
| 171 | usable(cap) |
| 172 | }); |
| 173 | Self { |
| 174 | high_bytes, |
| 175 | rss_hard_bytes, |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | /// Does the ceiling sit at or above the absolute cap? |
| 180 | /// |
| 181 | /// Then the cap is the effective limit and the node decides on its complete |
| 182 | /// cgroup charge or RSS fallback. That is the operator's |
| 183 | /// choice -- they asked for a ceiling above the safety floor -- but it |
| 184 | /// gives up the recovery property of this module, so the shell reports it. |
| 185 | pub fn ceiling_above_cap(self) -> bool { |
| 186 | match (self.high_bytes, self.rss_hard_bytes) { |
| 187 | (Some(high), Some(cap)) => high >= cap, |
| 188 | _ => false, |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | /// Fold a sample into the latches, and say why the node is shedding. |
| 193 | /// |
| 194 | /// Each ceiling latches on its own crossing: it engages at its ceiling and |
| 195 | /// releases at its own low watermark, which is 80% of that ceiling. The |
| 196 | /// hard cap is reported first, because it is the more serious of the two. |
| 197 | /// |
| 198 | /// The latches are carried separately and not derived from the reported |
| 199 | /// reason. Sharing them lets one crossing hold the node against the other's |
| 200 | /// watermark, in either direction: a crossing of the ordinary ceiling then |
| 201 | /// holds the node on a resident-set watermark, which is issue #36 again, |
| 202 | /// and a hard-cap crossing then holds it on a ceiling it never crossed. |
| 203 | pub fn classify(self, s: Load, was: Latches) -> (Latches, Option<&'static str>) { |
| 204 | let over = |ceiling: Option<u64>, sample: u64, latched: bool| { |
| 205 | ceiling.is_some_and(|c| sample >= c || (latched && sample > Self::low_watermark(c))) |
| 206 | }; |
| 207 | let latches = Latches { |
| 208 | memory: over(self.high_bytes, s.memory_bytes(), was.memory), |
| 209 | rss_hard: over(self.rss_hard_bytes, s.hard_bytes(), was.rss_hard), |
| 210 | }; |
| 211 | let reason = if latches.rss_hard { |
| 212 | Some(SHED_RSS_HARD) |
| 213 | } else if latches.memory { |
| 214 | Some(SHED_MEMORY) |
| 215 | } else { |
| 216 | None |
| 217 | }; |
| 218 | (latches, reason) |
| 219 | } |
| 220 | |
| 221 | /// The sample a latched ceiling releases at: 80% of the ceiling. |
| 222 | /// |
| 223 | /// One definition, because two callers read it. `classify` decides whether |
| 224 | /// the latch still holds, and the walk down's stopping condition asks |
| 225 | /// whether shedding can still get the sample down here. Two copies of the |
| 226 | /// arithmetic drift, and a walk down that aims at the wrong number either |
| 227 | /// stops above the line it could have reached or never stops at all. |
| 228 | fn low_watermark(ceiling: u64) -> u64 { |
| 229 | ceiling.saturating_mul(4) / 5 |
| 230 | } |
| 231 | |
| 232 | /// Whether the sample leaves the reserve below every configured low |
| 233 | /// watermark. A rollout uses this stricter state instead of `!pressured`: |
| 234 | /// a node can be below the high watermark without enough room to absorb a |
| 235 | /// donor. A disabled ceiling imposes no headroom condition. |
| 236 | pub fn has_headroom(self, sample: Load) -> bool { |
| 237 | let below = |ceiling: Option<u64>, bytes: u64| { |
| 238 | ceiling.is_none_or(|ceiling| bytes <= Self::low_watermark(ceiling)) |
| 239 | }; |
| 240 | below(self.high_bytes, sample.memory_bytes()) |
| 241 | && below(self.rss_hard_bytes, sample.hard_bytes()) |
| 242 | } |
| 243 | |
| 244 | /// Where the walk down against `metric` has to get the sample to. |
| 245 | /// |
| 246 | /// `None` means no ceiling is configured for that measurement, so nothing |
| 247 | /// can latch on it and no walk down works against it. |
| 248 | pub fn resume_line(self, metric: Metric) -> Option<u64> { |
| 249 | let ceiling = match metric { |
| 250 | Metric::InUse => self.high_bytes, |
| 251 | Metric::Rss => self.rss_hard_bytes, |
| 252 | }; |
| 253 | ceiling.map(Self::low_watermark) |
| 254 | } |
| 255 | |
| 256 | /// Which measurement the walk down must work against, given the latches. |
| 257 | /// |
| 258 | /// The ordinary ceiling wins whenever it is latched, even if the cap is |
| 259 | /// latched too. Eviction relieves the ordinary ceiling and may do nothing |
| 260 | /// at all for the cap, so choosing the cap's measurement while the node is |
| 261 | /// genuinely over its ordinary ceiling stops the walk down exactly when it |
| 262 | /// is needed. |
| 263 | pub fn walk_metric(latches: Latches) -> Metric { |
| 264 | if latches.memory { |
| 265 | Metric::InUse |
| 266 | } else { |
| 267 | Metric::Rss |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | /// How far to shed down to. A memory trigger takes a proportion of what was |
| 272 | /// just measured because the effect of an eviction is not visible until |
| 273 | /// the next sample. |
| 274 | pub fn release_target(resident_cells: usize) -> usize { |
| 275 | resident_cells.saturating_sub((resident_cells / 10).max(1)) |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | pub const MAX_OUTBOUND_PIN_PERCENT: usize = 50; |
| 280 | |
| 281 | /// May another cell be pinned resident by an outbound WebSocket? |
| 282 | /// |
| 283 | /// An outbound socket is not hibernatable, so eviction refuses its cell for as |
| 284 | /// long as it is open. That is correct — a live host transport cannot survive |
| 285 | /// eviction — but it means every pinned cell is removed from the eviction |
| 286 | /// pool. Pin the whole ceiling and a resource walk down has nothing to |
| 287 | /// nominate. The budget is node-wide, counted in pinned *cells* rather than |
| 288 | /// sockets, because one socket is enough to pin. `ceiling` is the hard resident |
| 289 | /// cap. |
| 290 | pub fn may_pin_outbound(pinned_cells: usize, ceiling: Option<usize>) -> bool { |
| 291 | ceiling.is_none_or(|cap| { |
| 292 | // At least one, always. The share alone rounds to zero below a ceiling |
| 293 | // of two, which would make an outbound socket impossible on a small |
| 294 | // node rather than merely budgeted. |
| 295 | pinned_cells < (cap.saturating_mul(MAX_OUTBOUND_PIN_PERCENT) / 100).max(1) |
| 296 | }) |
| 297 | } |