Diffinery

homeflare/celldpublic

celld/crates/logic/pressure.rs
163 lines · 6.3 KBRaw History
1//! `PressureConfig::state` reified sans-IO: load shedding is a pure classifier
2//! of a resource sample plus prior shedding state (the hysteresis latch). No
3//! I/O, no clock — the env read that builds the config stays at the edge
4//! (`main.rs`). This is the degenerate case of the pattern: a pure decision
5//! with no ports and no effects, included to prove the seam is uniform. It is
6//! the extraction target for `main.rs`'s private `PressureConfig`.
7
8/// Watermarks and ceilings. Built once from the environment by the caller;
9/// the core never reads the environment itself.
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
11pub struct PressureConfig {
12 pub resident_high: Option<usize>,
13 pub resident_low: usize,
14 pub rss_high_bytes: Option<u64>,
15 pub cpu_high_x100: Option<u64>,
16}
17
18/// A resource sample — the only input the classifier reads.
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub struct Load {
21 pub resident_cells: usize,
22 pub rss_bytes: u64,
23 pub cpu_percent_x100: u64,
24}
25
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub struct PressureState {
28 pub admission_blocked: bool,
29 pub shedding: bool,
30 pub trigger: Option<&'static str>,
31}
32
33impl PressureConfig {
34 /// The first ceiling the sample crosses, or `None`.
35 pub fn trigger(self, s: Load) -> Option<&'static str> {
36 if self.resident_high.is_some_and(|h| s.resident_cells >= h) {
37 return Some("resident_cells");
38 }
39 if self.rss_high_bytes.is_some_and(|h| s.rss_bytes >= h) {
40 return Some("rss");
41 }
42 if self.cpu_high_x100.is_some_and(|h| s.cpu_percent_x100 >= h) {
43 return Some("cpu");
44 }
45 None
46 }
47
48 /// Back under every low watermark (80% of each high) — the latch release.
49 pub fn relieved(self, s: Load) -> bool {
50 let resident_ok =
51 self.resident_high.is_none_or(|_| s.resident_cells <= self.resident_low);
52 let rss_ok = self
53 .rss_high_bytes
54 .is_none_or(|h| s.rss_bytes <= h.saturating_mul(4) / 5);
55 let cpu_ok = self
56 .cpu_high_x100
57 .is_none_or(|h| s.cpu_percent_x100 <= h.saturating_mul(4) / 5);
58 resident_ok && rss_ok && cpu_ok
59 }
60
61 /// How far to shed down to for a given trigger.
62 pub fn release_target(self, resident_cells: usize, reason: &str) -> usize {
63 if reason == "resident_cells" {
64 self.resident_low
65 } else {
66 resident_cells.saturating_sub((resident_cells / 10).max(1))
67 }
68 }
69
70 /// The resource whose low watermark still holds the shedding latch. An
71 /// instantaneous trigger wins; inside a hysteresis band, preserve the
72 /// resource-specific reason until every configured low watermark clears.
73 pub fn shedding_trigger(
74 self,
75 s: Load,
76 was_shedding: bool,
77 ) -> Option<&'static str> {
78 if let Some(trigger) = self.trigger(s) {
79 return Some(trigger);
80 }
81 if !was_shedding || self.relieved(s) {
82 return None;
83 }
84 if self.resident_high.is_some() && s.resident_cells > self.resident_low {
85 return Some("resident_cells");
86 }
87 if self
88 .rss_high_bytes
89 .is_some_and(|h| s.rss_bytes > h.saturating_mul(4) / 5)
90 {
91 return Some("rss");
92 }
93 if self
94 .cpu_high_x100
95 .is_some_and(|h| s.cpu_percent_x100 > h.saturating_mul(4) / 5)
96 {
97 return Some("cpu");
98 }
99 None
100 }
101
102 /// The transition: `was_shedding` is the only carried state — the latch
103 /// that keeps shedding between the high crossing and the low release.
104 pub fn state(self, s: Load, was_shedding: bool) -> PressureState {
105 let trigger = self.trigger(s);
106 let admission_blocked = trigger.is_some();
107 let shedding = self.shedding_trigger(s, was_shedding).is_some();
108 PressureState { admission_blocked, shedding, trigger }
109 }
110}
111
112
113/// May one more cell be admitted to residency right now?
114///
115/// Two independent facts gate admission. Conflating them turns graceful
116/// degradation under load into a cliff.
117///
118/// `sampled_pressure` is the hysteresis latch from [`PressureConfig::state`]:
119/// a periodic view of RSS, CPU, and residency, and the only thing entitled to
120/// say "this node is overloaded". The headroom test below is the other, and it
121/// is instantaneous.
122///
123/// A request that merely lost a race for the last slot has learned the second
124/// fact, not the first. If such a waiter is allowed to assert node-wide
125/// pressure, every other cell on the node is refused until the next sample —
126/// including cells that would fit — and the waiters keep the latch hot for one
127/// another. Capacity that exists then goes unused for a full sampling period.
128pub fn may_admit(
129 owned: usize,
130 pending: usize,
131 resident_high: Option<usize>,
132 sampled_pressure: bool,
133) -> bool {
134 if sampled_pressure {
135 return false;
136 }
137 resident_high.is_none_or(|high| owned.saturating_add(pending) < high)
138}
139
140pub const MAX_OUTBOUND_PIN_PERCENT: usize = 50;
141
142/// May another cell be pinned resident by an outbound WebSocket?
143///
144/// An outbound socket is not hibernatable, so `plan_candidates` refuses to
145/// evict its cell for as long as it is open. That is correct — a live host
146/// transport cannot survive hibernation — but it means every pinned cell is
147/// permanently removed from the eviction pool. Pin the whole ceiling and the
148/// sweep has nothing left to nominate: residency can never fall, admission
149/// waits for capacity that cannot be freed, and the node serves
150/// `capacity_exhausted` until an application happens to close a socket.
151///
152/// A per-cell ceiling does not bound this. One socket each across a thousand
153/// cells pins a thousand cells. The budget has to be node-wide, counted in
154/// pinned *cells* rather than sockets, because one socket is enough to pin.
155pub fn may_pin_outbound(pinned_cells: usize, resident_high: Option<usize>) -> bool {
156 resident_high.is_none_or(|high| {
157 // At least one, always. The share alone rounds to zero below a
158 // ceiling of two, which would make an outbound socket impossible on a
159 // small node rather than merely budgeted -- celld's ceilings were
160 // large enough that the floor never came up.
161 pinned_cells < (high.saturating_mul(MAX_OUTBOUND_PIN_PERCENT) / 100).max(1)
162 })
163}