Diffinery

homeflare/celldpublic

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