Diffinery

homeflare/celldpublic

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