Diffinery

homeflare/celldpublic

celld/crates/logic/pressure.rs
302 lines · 14.2 KBRaw History
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)]
20pub 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)]
55pub 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)]
67pub 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)]
79pub 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 // homeflare: no container memory. A container runs in its own cgroup, a
94 // sibling of the node's, and shedding cells gives none of it back, so
95 // counting it here refused and evicted every cell while CI ran. The
96 // container engine admits containers against their own budget instead
97 // (CELLD_CONTAINER_MEMORY_MB).
98}
99
100impl Load {
101 /// The ordinary pressure measurement. A cgroup working set contains active
102 /// kernel charges that process RSS omits. Subtract the same measured
103 /// allocator slack from it, or retained pages would recreate the admission
104 /// wedge through the cgroup path. The process measurement remains the floor
105 /// because cgroup and RSS accounting can differ for shared pages.
106 pub fn memory_bytes(self) -> u64 {
107 let allocator_slack = self.rss_bytes.saturating_sub(self.in_use_bytes);
108 let cgroup_in_use = self
109 .cgroup_working_set_bytes
110 .unwrap_or_default()
111 .saturating_sub(allocator_slack);
112 self.in_use_bytes.max(cgroup_in_use)
113 }
114
115 /// The hard pressure measurement. `memory.current` is authoritative when
116 /// present because the cgroup limit constrains it, not process RSS.
117 pub fn hard_bytes(self) -> u64 {
118 self.cgroup_current_bytes.unwrap_or(self.rss_bytes)
119 }
120
121 pub fn metric_bytes(self, metric: Metric) -> u64 {
122 match metric {
123 Metric::InUse => self.memory_bytes(),
124 Metric::Rss => self.hard_bytes(),
125 }
126 }
127}
128
129/// The latch engaged because the memory the cells hold crossed the ceiling.
130/// This is the ordinary case, and shedding relieves it.
131pub const SHED_MEMORY: &str = "memory";
132
133/// The latch engaged because the complete cgroup charge, or the RSS fallback,
134/// crossed the absolute cap. The string keeps its established telemetry name,
135/// but a Linux container decides it from `memory.current`.
136pub const SHED_RSS_HARD: &str = "rss-hard";
137
138impl PressureConfig {
139 /// Build the watermarks from the machine and the operator's setting.
140 ///
141 /// The policy lives here, not at the edge, because it is arithmetic with a
142 /// correctness argument and requires explicit validation. The shell only
143 /// supplies the two facts it can read: how much memory the process can use, and what
144 /// `CELLD_MAX_RSS_MB` says. `None` for the setting means the default, and
145 /// `Some(0)` disables pressure shedding altogether.
146 ///
147 /// The absolute cap is 95% of the machine and is never derived from the
148 /// ceiling. A cap derived from the ceiling either lands above the machine
149 /// (so it never fires) or below the ceiling (so it fires first on every
150 /// sample and the classifier is reading the hard measurement again). Both
151 /// have shipped in this file; neither is a floor.
152 ///
153 /// When the machine size is unknown, the cap falls back to 125% of an
154 /// explicit ceiling. That is worse than a share of the machine and better
155 /// than no floor at all.
156 pub fn from_limits(total_memory_bytes: Option<u64>, max_rss_mb: Option<u64>) -> Self {
157 // A watermark of zero is worse than no watermark: every sample crosses
158 // it and none can clear it, so the node latches on its first sample and
159 // refuses every cell for its lifetime. A machine that reports nothing
160 // usable therefore gets no watermark at all. Linux reports 0 for a
161 // cgroup limit of `0` and for an unreadable `MemTotal`.
162 let usable = |bytes: u64| (bytes > 0).then_some(bytes);
163 let high_bytes = match max_rss_mb {
164 None => total_memory_bytes.and_then(|total| usable(total / 5 * 4)),
165 Some(0) => None,
166 Some(megabytes) => usable(megabytes.saturating_mul(1024 * 1024)),
167 };
168 let rss_hard_bytes = high_bytes.and_then(|high| {
169 // `checked_mul`, because the fallback multiplies an operator's
170 // number: a saturating multiply followed by a divide would return a
171 // cap *below* the ceiling, which is the shape this avoids.
172 let fallback = high.checked_mul(5).map_or(u64::MAX, |scaled| scaled / 4);
173 let cap = total_memory_bytes
174 .and_then(|total| usable(total / 100 * 95))
175 .unwrap_or(fallback);
176 usable(cap)
177 });
178 Self {
179 high_bytes,
180 rss_hard_bytes,
181 }
182 }
183
184 /// Does the ceiling sit at or above the absolute cap?
185 ///
186 /// Then the cap is the effective limit and the node decides on its complete
187 /// cgroup charge or RSS fallback. That is the operator's
188 /// choice -- they asked for a ceiling above the safety floor -- but it
189 /// gives up the recovery property of this module, so the shell reports it.
190 pub fn ceiling_above_cap(self) -> bool {
191 match (self.high_bytes, self.rss_hard_bytes) {
192 (Some(high), Some(cap)) => high >= cap,
193 _ => false,
194 }
195 }
196
197 /// Fold a sample into the latches, and say why the node is shedding.
198 ///
199 /// Each ceiling latches on its own crossing: it engages at its ceiling and
200 /// releases at its own low watermark, which is 80% of that ceiling. The
201 /// hard cap is reported first, because it is the more serious of the two.
202 ///
203 /// The latches are carried separately and not derived from the reported
204 /// reason. Sharing them lets one crossing hold the node against the other's
205 /// watermark, in either direction: a crossing of the ordinary ceiling then
206 /// holds the node on a resident-set watermark it did not cross,
207 /// and a hard-cap crossing then holds it on a ceiling it never crossed.
208 pub fn classify(self, s: Load, was: Latches) -> (Latches, Option<&'static str>) {
209 let over = |ceiling: Option<u64>, sample: u64, latched: bool| {
210 ceiling.is_some_and(|c| sample >= c || (latched && sample > Self::low_watermark(c)))
211 };
212 let latches = Latches {
213 memory: over(self.high_bytes, s.memory_bytes(), was.memory),
214 rss_hard: over(self.rss_hard_bytes, s.hard_bytes(), was.rss_hard),
215 };
216 let reason = if latches.rss_hard {
217 Some(SHED_RSS_HARD)
218 } else if latches.memory {
219 Some(SHED_MEMORY)
220 } else {
221 None
222 };
223 (latches, reason)
224 }
225
226 /// The sample a latched ceiling releases at: 80% of the ceiling.
227 ///
228 /// One definition, because two callers read it. `classify` decides whether
229 /// the latch still holds, and the walk down's stopping condition asks
230 /// whether shedding can still get the sample down here. Two copies of the
231 /// arithmetic drift, and a walk down that aims at the wrong number either
232 /// stops above the line it could have reached or never stops at all.
233 fn low_watermark(ceiling: u64) -> u64 {
234 ceiling.saturating_mul(4) / 5
235 }
236
237 /// Whether the sample leaves the reserve below every configured low
238 /// watermark. A rollout uses this stricter state instead of `!pressured`:
239 /// a node can be below the high watermark without enough room to absorb a
240 /// donor. A disabled ceiling imposes no headroom condition.
241 pub fn has_headroom(self, sample: Load) -> bool {
242 let below = |ceiling: Option<u64>, bytes: u64| {
243 ceiling.is_none_or(|ceiling| bytes <= Self::low_watermark(ceiling))
244 };
245 below(self.high_bytes, sample.memory_bytes())
246 && below(self.rss_hard_bytes, sample.hard_bytes())
247 }
248
249 /// Where the walk down against `metric` has to get the sample to.
250 ///
251 /// `None` means no ceiling is configured for that measurement, so nothing
252 /// can latch on it and no walk down works against it.
253 pub fn resume_line(self, metric: Metric) -> Option<u64> {
254 let ceiling = match metric {
255 Metric::InUse => self.high_bytes,
256 Metric::Rss => self.rss_hard_bytes,
257 };
258 ceiling.map(Self::low_watermark)
259 }
260
261 /// Which measurement the walk down must work against, given the latches.
262 ///
263 /// The ordinary ceiling wins whenever it is latched, even if the cap is
264 /// latched too. Eviction relieves the ordinary ceiling and may do nothing
265 /// at all for the cap, so choosing the cap's measurement while the node is
266 /// genuinely over its ordinary ceiling stops the walk down exactly when it
267 /// is needed.
268 pub fn walk_metric(latches: Latches) -> Metric {
269 if latches.memory {
270 Metric::InUse
271 } else {
272 Metric::Rss
273 }
274 }
275
276 /// How far to shed down to. A memory trigger takes a proportion of what was
277 /// just measured because the effect of an eviction is not visible until
278 /// the next sample.
279 pub fn release_target(resident_cells: usize) -> usize {
280 resident_cells.saturating_sub((resident_cells / 10).max(1))
281 }
282}
283
284pub const MAX_OUTBOUND_PIN_PERCENT: usize = 50;
285
286/// May another cell be pinned resident by an outbound WebSocket?
287///
288/// An outbound socket is not hibernatable, so eviction refuses its cell for as
289/// long as it is open. That is correct — a live host transport cannot survive
290/// eviction — but it means every pinned cell is removed from the eviction
291/// pool. Pin the whole ceiling and a resource walk down has nothing to
292/// nominate. The budget is node-wide, counted in pinned *cells* rather than
293/// sockets, because one socket is enough to pin. `ceiling` is the hard resident
294/// cap.
295pub fn may_pin_outbound(pinned_cells: usize, ceiling: Option<usize>) -> bool {
296 ceiling.is_none_or(|cap| {
297 // At least one, always. The share alone rounds to zero below a ceiling
298 // of two, which would make an outbound socket impossible on a small
299 // node rather than merely budgeted.
300 pinned_cells < (cap.saturating_mul(MAX_OUTBOUND_PIN_PERCENT) / 100).max(1)
301 })
302}