| 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 resident set size: 95% of the machine. |
| 25 | /// |
| 26 | /// `high_bytes` applies to `Load::in_use_bytes`, which excludes the pages |
| 27 | /// the allocator keeps. That exclusion is what lets a node recover, but it |
| 28 | /// is not exact: the allocator also holds metadata and fragmentation |
| 29 | /// behind live allocations, and an eviction does not return those either. |
| 30 | /// A node could therefore keep admitting while its true resident set |
| 31 | /// climbed, and trade a wedge for a kill by the operating system. |
| 32 | /// |
| 33 | /// This is the floor under that trade. It reads the resident set size |
| 34 | /// directly, so nothing can hide from it. |
| 35 | /// |
| 36 | /// It is a fixed share of the machine and is never derived from |
| 37 | /// `high_bytes`. A first attempt placed it "at least 125% of the ceiling", |
| 38 | /// which put it at exactly 100% of the machine for the default ceiling of |
| 39 | /// 80% -- above anything the kernel would let the process reach, so the |
| 40 | /// floor did not exist in the configuration that ships. See |
| 41 | /// [`PressureConfig::from_limits`]. |
| 42 | pub rss_hard_bytes: Option<u64>, |
| 43 | } |
| 44 | |
| 45 | /// Which ceilings are currently latched. Each one engages at its own ceiling |
| 46 | /// and releases at its own low watermark, so one crossing can never hold the |
| 47 | /// node against the other's watermark. |
| 48 | /// |
| 49 | /// This is two booleans rather than the reported reason, because the reason |
| 50 | /// names only the more serious crossing. Deriving the latches from it lets a |
| 51 | /// hard-cap crossing arm the ordinary ceiling, and then a node stays closed on |
| 52 | /// a ceiling it never crossed. |
| 53 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 54 | pub struct Latches { |
| 55 | pub memory: bool, |
| 56 | pub rss_hard: bool, |
| 57 | } |
| 58 | |
| 59 | /// Which measurement a walk down is working against. |
| 60 | /// |
| 61 | /// The futility stop compares a sample with the one the last cut measured, so |
| 62 | /// it has to know that the two samples are the same measurement. They are not |
| 63 | /// interchangeable: eviction moves the in-use figure at once and may never move |
| 64 | /// the resident set size at all. |
| 65 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 66 | pub enum Metric { |
| 67 | InUse, |
| 68 | Rss, |
| 69 | } |
| 70 | |
| 71 | /// A resource sample — the only input the classifier reads. `resident_cells` |
| 72 | /// is carried so a resource trigger can size its walk down as a proportion of |
| 73 | /// what is actually resident. |
| 74 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 75 | pub struct Load { |
| 76 | pub resident_cells: usize, |
| 77 | /// Reported to peers and operators, never decided on. |
| 78 | pub rss_bytes: u64, |
| 79 | /// RSS minus the pages the allocator keeps but nothing uses. Shedding can |
| 80 | /// only return the memory a cell holds, so only this may hold the latch -- |
| 81 | /// a classifier reading RSS never releases once jemalloc retains, however |
| 82 | /// many cells the node gives back. |
| 83 | pub in_use_bytes: u64, |
| 84 | } |
| 85 | |
| 86 | /// The latch engaged because the memory the cells hold crossed the ceiling. |
| 87 | /// This is the ordinary case, and shedding relieves it. |
| 88 | pub const SHED_MEMORY: &str = "memory"; |
| 89 | |
| 90 | /// The latch engaged because the resident set size crossed the absolute cap. |
| 91 | /// Shedding may not relieve this one, so it is named apart: an operator who |
| 92 | /// sees it is looking at allocator retention that did not come back, and the |
| 93 | /// node is close to a kill by the operating system. |
| 94 | pub const SHED_RSS_HARD: &str = "rss-hard"; |
| 95 | |
| 96 | impl PressureConfig { |
| 97 | /// Build the watermarks from the machine and the operator's setting. |
| 98 | /// |
| 99 | /// The policy lives here, not at the edge, because it is arithmetic with a |
| 100 | /// correctness argument and it needs tests. The shell only supplies the two |
| 101 | /// facts it can read: how much memory the process may use, and what |
| 102 | /// `CELLD_MAX_RSS_MB` says. `None` for the setting means the default, and |
| 103 | /// `Some(0)` disables pressure shedding altogether. |
| 104 | /// |
| 105 | /// The absolute cap is 95% of the machine and is never derived from the |
| 106 | /// ceiling. A cap derived from the ceiling either lands above the machine |
| 107 | /// (so it never fires) or below the ceiling (so it fires first on every |
| 108 | /// sample and the classifier is reading the resident set size again). Both |
| 109 | /// have shipped in this file; neither is a floor. |
| 110 | /// |
| 111 | /// When the machine size is unknown, the cap falls back to 125% of an |
| 112 | /// explicit ceiling. That is worse than a share of the machine and better |
| 113 | /// than no floor at all. |
| 114 | pub fn from_limits(total_memory_bytes: Option<u64>, max_rss_mb: Option<u64>) -> Self { |
| 115 | // A watermark of zero is worse than no watermark: every sample crosses |
| 116 | // it and none can clear it, so the node latches on its first sample and |
| 117 | // refuses every cell for its lifetime. A machine that reports nothing |
| 118 | // usable therefore gets no watermark at all. Linux reports 0 for a |
| 119 | // cgroup limit of `0` and for an unreadable `MemTotal`. |
| 120 | let usable = |bytes: u64| (bytes > 0).then_some(bytes); |
| 121 | let high_bytes = match max_rss_mb { |
| 122 | None => total_memory_bytes.and_then(|total| usable(total / 5 * 4)), |
| 123 | Some(0) => None, |
| 124 | Some(megabytes) => usable(megabytes.saturating_mul(1024 * 1024)), |
| 125 | }; |
| 126 | let rss_hard_bytes = high_bytes.and_then(|high| { |
| 127 | // `checked_mul`, because the fallback multiplies an operator's |
| 128 | // number: a saturating multiply followed by a divide would return a |
| 129 | // cap *below* the ceiling, which is the shape this avoids. |
| 130 | let fallback = high.checked_mul(5).map_or(u64::MAX, |scaled| scaled / 4); |
| 131 | let cap = total_memory_bytes |
| 132 | .and_then(|total| usable(total / 100 * 95)) |
| 133 | .unwrap_or(fallback); |
| 134 | usable(cap) |
| 135 | }); |
| 136 | Self { |
| 137 | high_bytes, |
| 138 | rss_hard_bytes, |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | /// Does the ceiling sit at or above the absolute cap? |
| 143 | /// |
| 144 | /// Then the cap is the effective limit and the node decides on its resident |
| 145 | /// set size, not on the memory the cells hold. That is the operator's |
| 146 | /// choice -- they asked for a ceiling above the safety floor -- but it |
| 147 | /// gives up the recovery property of this module, so the shell reports it. |
| 148 | pub fn ceiling_above_cap(self) -> bool { |
| 149 | match (self.high_bytes, self.rss_hard_bytes) { |
| 150 | (Some(high), Some(cap)) => high >= cap, |
| 151 | _ => false, |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | /// Fold a sample into the latches, and say why the node is shedding. |
| 156 | /// |
| 157 | /// Each ceiling latches on its own crossing: it engages at its ceiling and |
| 158 | /// releases at its own low watermark, which is 80% of that ceiling. The |
| 159 | /// hard cap is reported first, because it is the more serious of the two. |
| 160 | /// |
| 161 | /// The latches are carried separately and not derived from the reported |
| 162 | /// reason. Sharing them lets one crossing hold the node against the other's |
| 163 | /// watermark, in either direction: a crossing of the ordinary ceiling then |
| 164 | /// holds the node on a resident-set watermark, which is issue #36 again, |
| 165 | /// and a hard-cap crossing then holds it on a ceiling it never crossed. |
| 166 | pub fn classify(self, s: Load, was: Latches) -> (Latches, Option<&'static str>) { |
| 167 | let over = |ceiling: Option<u64>, sample: u64, latched: bool| { |
| 168 | ceiling.is_some_and(|c| sample >= c || (latched && sample > Self::low_watermark(c))) |
| 169 | }; |
| 170 | let latches = Latches { |
| 171 | memory: over(self.high_bytes, s.in_use_bytes, was.memory), |
| 172 | rss_hard: over(self.rss_hard_bytes, s.rss_bytes, was.rss_hard), |
| 173 | }; |
| 174 | let reason = if latches.rss_hard { |
| 175 | Some(SHED_RSS_HARD) |
| 176 | } else if latches.memory { |
| 177 | Some(SHED_MEMORY) |
| 178 | } else { |
| 179 | None |
| 180 | }; |
| 181 | (latches, reason) |
| 182 | } |
| 183 | |
| 184 | /// The sample a latched ceiling releases at: 80% of the ceiling. |
| 185 | /// |
| 186 | /// One definition, because two callers read it. `classify` decides whether |
| 187 | /// the latch still holds, and the walk down's stopping condition asks |
| 188 | /// whether shedding can still get the sample down here. Two copies of the |
| 189 | /// arithmetic drift, and a walk down that aims at the wrong number either |
| 190 | /// stops above the line it could have reached or never stops at all. |
| 191 | fn low_watermark(ceiling: u64) -> u64 { |
| 192 | ceiling.saturating_mul(4) / 5 |
| 193 | } |
| 194 | |
| 195 | /// Where the walk down against `metric` has to get the sample to. |
| 196 | /// |
| 197 | /// `None` means no ceiling is configured for that measurement, so nothing |
| 198 | /// can latch on it and no walk down works against it. |
| 199 | pub fn resume_line(self, metric: Metric) -> Option<u64> { |
| 200 | let ceiling = match metric { |
| 201 | Metric::InUse => self.high_bytes, |
| 202 | Metric::Rss => self.rss_hard_bytes, |
| 203 | }; |
| 204 | ceiling.map(Self::low_watermark) |
| 205 | } |
| 206 | |
| 207 | /// Which measurement the walk down must work against, given the latches. |
| 208 | /// |
| 209 | /// The ordinary ceiling wins whenever it is latched, even if the cap is |
| 210 | /// latched too. Eviction relieves the ordinary ceiling and may do nothing |
| 211 | /// at all for the cap, so choosing the cap's measurement while the node is |
| 212 | /// genuinely over its ordinary ceiling stops the walk down exactly when it |
| 213 | /// is needed. |
| 214 | pub fn walk_metric(latches: Latches) -> Metric { |
| 215 | if latches.memory { |
| 216 | Metric::InUse |
| 217 | } else { |
| 218 | Metric::Rss |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | /// How far to shed down to. A memory trigger takes a proportion of what was |
| 223 | /// just measured because the effect of an eviction is not visible until |
| 224 | /// the next sample. |
| 225 | pub fn release_target(resident_cells: usize) -> usize { |
| 226 | resident_cells.saturating_sub((resident_cells / 10).max(1)) |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | pub const MAX_OUTBOUND_PIN_PERCENT: usize = 50; |
| 231 | |
| 232 | /// May another cell be pinned resident by an outbound WebSocket? |
| 233 | /// |
| 234 | /// An outbound socket is not hibernatable, so eviction refuses its cell for as |
| 235 | /// long as it is open. That is correct — a live host transport cannot survive |
| 236 | /// eviction — but it means every pinned cell is removed from the eviction |
| 237 | /// pool. Pin the whole ceiling and a resource walk down has nothing to |
| 238 | /// nominate. The budget is node-wide, counted in pinned *cells* rather than |
| 239 | /// sockets, because one socket is enough to pin. `ceiling` is the hard resident |
| 240 | /// cap. |
| 241 | pub fn may_pin_outbound(pinned_cells: usize, ceiling: Option<usize>) -> bool { |
| 242 | ceiling.is_none_or(|cap| { |
| 243 | // At least one, always. The share alone rounds to zero below a ceiling |
| 244 | // of two, which would make an outbound socket impossible on a small |
| 245 | // node rather than merely budgeted. |
| 246 | pinned_cells < (cap.saturating_mul(MAX_OUTBOUND_PIN_PERCENT) / 100).max(1) |
| 247 | }) |
| 248 | } |