| 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. |
| 29 | pub type IsolateId = usize; |
| 30 | |
| 31 | /// What the shell observes about one isolate. |
| 32 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 33 | pub 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)] |
| 57 | pub 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)] |
| 92 | pub 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)] |
| 101 | pub 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)] |
| 110 | pub 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 | |
| 118 | impl 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. |
| 164 | pub 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. |
| 188 | fn 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. |
| 209 | pub 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 reads `cells` and leaves |
| 237 | /// turns alone: an isolate running hot right now may still be the right home |
| 238 | /// 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. |
| 248 | pub fn place_cell(load: &PoolLoad) -> Placement { |
| 249 | // The fullest isolate that still has room, not the emptiest. |
| 250 | // |
| 251 | // Packing is what makes a heap reclaimable. The walk down evicts from the |
| 252 | // isolate closest to empty, because only the cut that takes an isolate's |
| 253 | // last cell returns its heap. Spreading aimed new cells at that same |
| 254 | // isolate, so under any load that keeps admitting, eviction drained a heap |
| 255 | // and placement refilled it: the isolate never reached zero, `retire` |
| 256 | // refused it, and the node paid an eviction and a cold start per cell for |
| 257 | // no memory back. |
| 258 | // |
| 259 | // Packing costs nothing that `max_cells` was not already bounding. That |
| 260 | // ceiling is what limits how many cells one OOM can take, and it applies |
| 261 | // either way. |
| 262 | match load |
| 263 | .live() |
| 264 | .filter(|(_, l)| l.cells < load.limits.max_cells) |
| 265 | .max_by_key(|(id, l)| (l.cells, std::cmp::Reverse(*id))) |
| 266 | { |
| 267 | // No isolate, or every one of them is draining. |
| 268 | None => Placement::Grow, |
| 269 | Some((id, _)) => Placement::Existing(id), |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | /// Which isolate to retire, if any. |
| 274 | /// |
| 275 | /// Worth starting only when the rest of the pool can absorb the current turns |
| 276 | /// without immediately wanting to grow again. |
| 277 | /// |
| 278 | /// The victim is cheapest to empty: fewer affiliated requests, then the |
| 279 | /// newest, so a pool that grew for a burst gives back what the burst added. |
| 280 | /// An isolate empties itself as its requests finish, so the shell only has |
| 281 | /// to stop sending it work and wait. |
| 282 | /// |
| 283 | /// This returns a candidate, not a command. The shell still stops affiliating |
| 284 | /// new work and lets outstanding requests finish before the isolate goes |
| 285 | /// away — `Pool::reap`. |
| 286 | /// |
| 287 | /// **An isolate hosting a cell is never a candidate.** Retiring rests on the |
| 288 | /// victim emptying itself, and requests do that because they answer. A cell |
| 289 | /// does not: it stays until it is evicted or handed to another node, neither |
| 290 | /// of which retirement can cause. Choosing one would mark it retiring |
| 291 | /// forever — refused new work, never drained, never freed — which is a |
| 292 | /// smaller pool and a leak at the same time. |
| 293 | /// |
| 294 | /// Cell and stateless pools both run this maintenance decision. The cell pool |
| 295 | /// uses this filter to reclaim empty heaps after eviction while preserving |
| 296 | /// every isolate that still holds a realm. |
| 297 | /// May a RETIRING isolate's worker and heap be freed? Only when it is |
| 298 | /// provably drained: no queued or running turn, and no live affiliation. |
| 299 | /// An affiliation is any dispatched event's claim on the isolate, held |
| 300 | /// across suspensions — a suspended event holds no turn, so `turns` |
| 301 | /// alone is not drained-ness, and freeing on it re-enters a freed heap |
| 302 | /// when the event's host I/O completes (denoland/celld#147). `cells` is |
| 303 | /// consulted too: `retire` never selects a housed isolate, but a |
| 304 | /// generation-wide retirement marks every isolate of a superseded |
| 305 | /// deployment, housed or not, and freeing a housed one would drop every |
| 306 | /// resident cell in it. A cell whose residency dropped mid-event is still |
| 307 | /// the affiliation's case, not this one. |
| 308 | pub fn may_free(load: &IsolateLoad) -> bool { |
| 309 | load.retiring && load.turns == 0 && load.requests == 0 && load.cells == 0 |
| 310 | } |
| 311 | |
| 312 | pub fn retire(load: &PoolLoad) -> Option<IsolateId> { |
| 313 | let live = load.live().count(); |
| 314 | if live == 0 { |
| 315 | return None; |
| 316 | } |
| 317 | |
| 318 | let turns: usize = load.live().map(|(_, l)| l.turns).sum(); |
| 319 | let remaining = live - 1; |
| 320 | if turns > remaining.saturating_mul(load.limits.shrink_under) { |
| 321 | return None; |
| 322 | } |
| 323 | |
| 324 | load.live() |
| 325 | .filter(|(_, l)| l.cells == 0) |
| 326 | .min_by_key(|(id, l)| (l.requests, std::cmp::Reverse(*id))) |
| 327 | .map(|(id, _)| id) |
| 328 | } |