Diffinery

homeflare/celldpublic

celld/crates/logic/isolate.rs
302 lines · 13.1 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3//! The isolate pool, reified sans-IO.
4//!
5//! celld runs JS on a set of isolates that grow and shrink with demand. An
6//! isolate is not bound to a thread: `v8::Locker` installs the entering
7//! thread's per-isolate state, so any worker can take an isolate and run a
8//! turn in it. What an isolate *is* bound to is the JS state it holds, and
9//! that is what every decision here is about.
10//!
11//! Two quantities, because they answer different questions:
12//!
13//! - **turns** — turns in flight on this isolate: queued for it plus the
14//! one running. CPU demand. A request awaiting I/O contributes nothing,
15//! because the isolate is released across the await, so this is what
16//! placement balances. It must count the queue, not just the runner: an
17//! isolate serves one turn at a time, so "executing" never exceeds one
18//! and could never signal that another isolate would help.
19//! - **requests** — requests affiliated with this isolate. A request runs
20//! its first turn somewhere and its promise then lives in that isolate's
21//! heap, so every later turn must come back. Affiliation is memory, not
22//! CPU, and is what admission and shedding care about.
23//!
24//! Everything here is a predicate over observed load. The shell reports what
25//! it sees and performs what it is told; it never decides.
26
27/// Which isolate. An index the shell keeps, stable for that isolate's life.
28/// Never a thread id — an isolate has no thread.
29pub type IsolateId = usize;
30
31/// What the shell observes about one isolate.
32#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
33pub struct IsolateLoad {
34 /// Turns in flight: waiting for this isolate plus the one running in it.
35 /// Released across an await, so this is CPU demand rather than total
36 /// outstanding work. Counting only the runner would cap this at one,
37 /// since an isolate serves one turn at a time.
38 pub turns: usize,
39 /// Requests whose JS state lives here, running or awaiting. Each one
40 /// pins a promise and its closures in this isolate's heap.
41 pub requests: usize,
42 /// Cells hosted here: realms this isolate holds, one per cell.
43 ///
44 /// The third quantity, and unlike the other two it does not come back on
45 /// its own. A request ends; a cell stays until it is evicted or handed
46 /// to another node. So this measures what the isolate is *committed* to,
47 /// and it is what cell placement balances.
48 pub cells: usize,
49 /// The shell has stopped affiliating new work and is draining this
50 /// isolate.
51 pub retiring: bool,
52}
53
54/// Pool-wide limits, built once from configuration by the caller. The core
55/// never reads the environment itself.
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub struct PoolLimits {
58 /// Turns in flight at which an isolate is considered busy, so the pool
59 /// prefers to grow rather than queue another turn behind those. Small:
60 /// a couple of turns already waiting means another isolate would help.
61 pub grow_at: usize,
62 /// Per-isolate turn level the pool must stay under for a retirement to be
63 /// worth starting. Below `grow_at`, and the gap is the hysteresis that
64 /// stops growth and retirement chasing each other.
65 pub shrink_under: usize,
66 /// Ceiling on live isolates. Past it the pool queues rather than grows.
67 pub max_stateless: usize,
68 /// Affiliated stateless requests the node may hold at once, across every
69 /// isolate. `None` leaves admission unbounded, which is only correct
70 /// while something else caps concurrency.
71 ///
72 /// A node-wide figure rather than a per-isolate one, because the memory
73 /// it bounds is the node's: a suspended request pins its promise and
74 /// buffers wherever it landed, and spreading the same requests over more
75 /// isolates does not make them cheaper.
76 pub max_requests: Option<usize>,
77 /// Cells one isolate may host. Past it, cell placement builds another
78 /// isolate rather than adding a realm.
79 ///
80 /// A per-isolate figure where `max_requests` is node-wide, and the
81 /// difference is not an inconsistency. A suspended request costs the
82 /// same wherever it landed, so spreading requests buys nothing and the
83 /// node-wide total is the real bound. Cells are not like that: they
84 /// share one V8 heap, and a heap that holds too many of them is a
85 /// single OOM taking every cell in it down together. Spreading is the
86 /// whole point, so the bound has to be per-isolate.
87 pub max_cells: usize,
88}
89
90/// The pool as the shell sees it. Indexed by [`IsolateId`].
91#[derive(Clone, Debug, PartialEq, Eq)]
92pub struct PoolLoad {
93 pub isolates: Vec<IsolateLoad>,
94 pub limits: PoolLimits,
95}
96
97/// Why a request was refused. The shell maps this to a status; a refusal is
98/// a 503, because the node is the thing that is unavailable, not the request
99/// that is wrong.
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101pub enum Refusal {
102 /// The node already holds all the stateless requests it may.
103 NodeFull,
104 /// The node is shedding: it is over a resource ceiling and recovering.
105 NodePressured,
106}
107
108/// Where a new request runs its first turn.
109#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110pub enum Placement {
111 Existing(IsolateId),
112 /// Build an isolate and use that. Growth is a placement outcome rather
113 /// than a separate command, because an isolate cannot be addressed
114 /// before the shell has built it.
115 Grow,
116}
117
118impl PoolLoad {
119 fn live(&self) -> impl Iterator<Item = (IsolateId, &IsolateLoad)> {
120 self.isolates
121 .iter()
122 .enumerate()
123 .filter(|(_, l)| !l.retiring)
124 }
125
126 fn live_count(&self) -> usize {
127 self.live().count()
128 }
129}
130
131/// Take a stateless request, or refuse it.
132///
133/// Admission and placement are one decision — *may this run, and where* —
134/// so they are one call against one snapshot. Split apart they were two
135/// views of the same node that could disagree, and the shell could admit a
136/// request and then fail to place it, or place one it had never admitted.
137///
138/// Called after the connection is accepted, not before. A node that stops
139/// accepting leaves connections in its kernel backlog, where they wait
140/// without an answer until the client's own deadline — the failure this
141/// bound exists to prevent, arriving one layer lower. Accepting and refusing
142/// costs a syscall and gives the caller a 503 it can act on.
143///
144/// **Pressure does not close stateless admission.** It used to, and that was
145/// wrong twice over.
146///
147/// Transient work gives memory back on its own, so a request cheap enough to
148/// drain by itself is not the thing to refuse.
149///
150/// And it wedged the node's clients. The stateless Worker entry is also the
151/// ingress that routes a cell to whichever node owns it, so refusing it does
152/// not move load off a latched node; it removes that node's ability to move
153/// load anywhere. A latched node must keep answering and place its cells on a
154/// spare.
155///
156/// What pressure does instead is **stop the pool growing**: a node over its
157/// memory ceiling may keep serving on the isolates it already has, but must
158/// not build another. Growth is still allowed when there is nothing to place
159/// onto, because an isolate the node cannot build is a request it cannot
160/// answer at all.
161///
162/// Stateless memory is bounded by `max_requests`, which is the figure that
163/// actually measures it.
164pub fn admit(load: &PoolLoad, shedding: bool) -> Result<Placement, Refusal> {
165 if let Some(max) = load.limits.max_requests {
166 let held: usize = load.isolates.iter().map(|l| l.requests).sum();
167 if held >= max {
168 return Err(if shedding {
169 // Reported ahead of fullness: a full node drains on its own,
170 // a pressured one does not, so pressure is the more
171 // actionable thing to tell the caller.
172 Refusal::NodePressured
173 } else {
174 Refusal::NodeFull
175 });
176 }
177 }
178 Ok(if shedding {
179 place_without_growing(load)
180 } else {
181 place(load)
182 })
183}
184
185/// [`place`], except that it will not build an isolate while one exists to
186/// use. The node is over a memory ceiling; another heap is the last thing it
187/// needs.
188fn place_without_growing(load: &PoolLoad) -> Placement {
189 match load.live().min_by_key(|(_, l)| l.turns) {
190 Some((id, _)) => Placement::Existing(id),
191 None => Placement::Grow,
192 }
193}
194
195/// Choose the isolate for a request's first turn.
196///
197/// This is the only free choice a stateless request gets. Every later turn of
198/// that request is addressed to the isolate chosen here, because its promise
199/// lives in that heap — so the shell must remember the affiliation, and this
200/// function is not consulted again for that request.
201///
202/// Balanced on turns in flight rather than affiliations, because an awaiting
203/// request occupies nothing: an isolate holding a thousand suspended
204/// requests and running no JS is idle and should be given work. Affiliation
205/// count is a memory signal and belongs to admission, not here.
206///
207/// Retiring isolates are skipped: the point of retiring one is that it stops
208/// taking new affiliations.
209pub fn place(load: &PoolLoad) -> Placement {
210 match load.live().min_by_key(|(_, l)| l.turns) {
211 // No isolate, or every one of them is draining.
212 None => Placement::Grow,
213 Some((id, l)) => {
214 if l.turns >= load.limits.grow_at && load.live_count() < load.limits.max_stateless {
215 Placement::Grow
216 } else {
217 // At the ceiling the pool queues. Refusing work is
218 // admission's job: see `worker::may_admit`.
219 Placement::Existing(id)
220 }
221 }
222 }
223}
224
225/// Where a cell's realm goes, for the whole life of that cell on this node.
226///
227/// **Not the same decision as [`place`], and the difference is permanence.**
228/// A stateless request picks an isolate for its first turn and is done: the
229/// next request picks again, so a bad choice costs one request. A cell's
230/// realm holds its JS state, so every event it ever receives comes back
231/// here. The shell records the assignment and never asks again — this is
232/// consulted once per cell, not once per event.
233///
234/// That makes the balance different too. `place` balances `turns`, because
235/// an awaiting request occupies nothing and CPU is what a new turn contends
236/// for. Here the cost is a realm that stays, so this balances `cells` and
237/// leaves turns alone: an isolate running hot right now may still be the
238/// right home for a cell that will outlive the burst.
239///
240/// Growth happens at `max_cells` rather than at a busy-ness threshold, and
241/// the ceiling is per-isolate for the reason in [`PoolLimits::max_cells`] —
242/// too many cells in one heap is one OOM that takes all of them.
243///
244/// There is no separate cell-isolate ceiling. The node-wide resident and RSS
245/// limits decide whether this node can host another cell. Once ownership has
246/// admitted the cell, placement always provides enough isolates to preserve
247/// the per-isolate limit.
248pub fn place_cell(load: &PoolLoad) -> Placement {
249 match load.live().min_by_key(|(_, l)| l.cells) {
250 // No isolate, or every one of them is draining.
251 None => Placement::Grow,
252 Some((id, l)) => {
253 if l.cells >= load.limits.max_cells {
254 Placement::Grow
255 } else {
256 Placement::Existing(id)
257 }
258 }
259 }
260}
261
262/// Which isolate to retire, if any.
263///
264/// Worth starting only when the rest of the pool can absorb the current turns
265/// without immediately wanting to grow again.
266///
267/// The victim is cheapest to empty: fewer affiliated requests, then the
268/// newest, so a pool that grew for a burst gives back what the burst added.
269/// An isolate empties itself as its requests finish, so the shell only has
270/// to stop sending it work and wait.
271///
272/// This returns a candidate, not a command. The shell still stops affiliating
273/// new work and lets outstanding requests finish before the isolate goes
274/// away — `Pool::reap`.
275///
276/// **An isolate hosting a cell is never a candidate.** Retiring rests on the
277/// victim emptying itself, and requests do that because they answer. A cell
278/// does not: it stays until it is evicted or handed to another node, neither
279/// of which retirement can cause. Choosing one would mark it retiring
280/// forever — refused new work, never drained, never freed — which is a
281/// smaller pool and a leak at the same time.
282///
283/// Cell and stateless pools both run this maintenance decision. The cell pool
284/// uses this filter to reclaim empty heaps after eviction while preserving
285/// every isolate that still holds a realm.
286pub fn retire(load: &PoolLoad) -> Option<IsolateId> {
287 let live = load.live().count();
288 if live == 0 {
289 return None;
290 }
291
292 let turns: usize = load.live().map(|(_, l)| l.turns).sum();
293 let remaining = live - 1;
294 if turns > remaining.saturating_mul(load.limits.shrink_under) {
295 return None;
296 }
297
298 load.live()
299 .filter(|(_, l)| l.cells == 0)
300 .min_by_key(|(id, l)| (l.requests, std::cmp::Reverse(*id)))
301 .map(|(id, _)| id)
302}