Diffinery

homeflare/celldpublic

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