Diffinery

homeflare/celldpublic

874 lines · 33.5 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3// Isolate admission and deadlines are in the V8 arm outside the Actor execution
4// domain.
5#![allow(clippy::disallowed_methods)]
6
7//! The isolate pool: the shell around `celld_logic::isolate`.
8//!
9//! One multi-threaded tokio runtime owns every socket and timer. Isolates
10//! belong to no thread — `v8::Locker` installs the entering thread's
11//! per-isolate state, so any worker can take an isolate and run a turn in it.
12//! This module owns the isolates and the counters; every choice about which
13//! isolate, when to grow, what to shed and what to retire is made by
14//! `celld_logic::isolate` and merely performed here.
15//!
16//! **The gate exists so nothing blocks.** `SharedIsolate::lock()` blocks
17//! until its holder releases. Every path here takes the slot's async permit
18//! first, so that blocking lock is uncontended by construction. A `lock()`
19//! reached without the permit would park a tokio worker on V8, which is the
20//! one thing this runtime refuses to do.
21
22use std::sync::atomic::AtomicBool;
23use std::sync::atomic::AtomicU64;
24use std::sync::atomic::AtomicUsize;
25use std::sync::atomic::Ordering;
26use std::sync::Arc;
27use std::sync::Mutex;
28use std::sync::RwLock;
29
30use anyhow::Result;
31use celld_logic::isolate::HeapId;
32use celld_logic::isolate::IsolateId;
33use celld_logic::isolate::IsolateLoad;
34use celld_logic::isolate::Placement;
35use celld_logic::isolate::PoolLimits;
36use celld_logic::isolate::PoolLoad;
37use celld_logic::isolate::Refusal;
38
39use crate::js;
40
41/// Heap identity is process-wide because pressure policy compares cells from
42/// every script pool and every draining generation. A counter inside `Pool`
43/// would reproduce the collision this identity prevents. The core treats the
44/// value as opaque, so its allocation order is not a deterministic decision.
45static NEXT_HEAP_ID: AtomicU64 = AtomicU64::new(1);
46
47fn next_heap_id() -> HeapId {
48 let value = NEXT_HEAP_ID
49 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
50 value.checked_add(1)
51 })
52 .expect("V8 heap identity space exhausted");
53 HeapId::new(value)
54}
55
56/// Bound the producer replies that can wait for one Queue's shared commit and
57/// durability proof. Four 64-call groups can overlap, and a stopped bucket
58/// still cannot retain an unbounded number of promises or copied bodies.
59pub(crate) const MAX_QUEUE_PRODUCER_EVENTS_PER_CELL: usize = 256;
60
61#[derive(Clone, Debug, Eq, Hash, PartialEq)]
62enum TurnLane {
63 Stateless,
64 Cell(String),
65}
66
67#[derive(Default)]
68struct TurnSchedule {
69 current: Option<TurnLane>,
70 ready: std::collections::VecDeque<TurnLane>,
71 waiting: std::collections::HashMap<
72 TurnLane,
73 std::collections::VecDeque<tokio::sync::oneshot::Sender<()>>,
74 >,
75}
76
77#[derive(Default)]
78struct TurnScheduler {
79 schedule: Mutex<TurnSchedule>,
80}
81
82struct TurnPermit<'a>(&'a TurnScheduler);
83
84impl TurnScheduler {
85 async fn acquire(&self, lane: TurnLane) -> TurnPermit<'_> {
86 let receive = {
87 let mut schedule = self.schedule.lock().expect("turn scheduler poisoned");
88 if schedule.current.is_none() {
89 schedule.current = Some(lane);
90 None
91 } else {
92 let (send, receive) = tokio::sync::oneshot::channel();
93 if !schedule.waiting.contains_key(&lane) && schedule.current.as_ref() != Some(&lane)
94 {
95 schedule.ready.push_back(lane.clone());
96 }
97 schedule.waiting.entry(lane).or_default().push_back(send);
98 Some(receive)
99 }
100 };
101 if let Some(receive) = receive {
102 // Cancellation leaves a closed sender in this lane. `release`
103 // skips it, so a dropped waiter cannot strand the active token.
104 let _ = receive.await;
105 }
106 TurnPermit(self)
107 }
108
109 fn release(&self) {
110 let mut schedule = self.schedule.lock().expect("turn scheduler poisoned");
111 let current = schedule
112 .current
113 .take()
114 .expect("a released turn scheduler has a current lane");
115 if schedule
116 .waiting
117 .get(&current)
118 .is_some_and(|waiters| !waiters.is_empty())
119 {
120 schedule.ready.push_back(current);
121 }
122 while let Some(lane) = schedule.ready.pop_front() {
123 let (send, keep_lane) = {
124 let waiters = schedule
125 .waiting
126 .get_mut(&lane)
127 .expect("a ready turn lane has waiters");
128 (waiters.pop_front().unwrap(), !waiters.is_empty())
129 };
130 if !keep_lane {
131 schedule.waiting.remove(&lane);
132 }
133 if send.send(()).is_ok() {
134 schedule.current = Some(lane);
135 return;
136 }
137 if keep_lane {
138 schedule.ready.push_back(lane);
139 }
140 }
141 }
142}
143
144impl Drop for TurnPermit<'_> {
145 fn drop(&mut self) {
146 self.0.release();
147 }
148}
149
150pub(crate) struct QueueProducerPermit {
151 slot: Arc<Slot>,
152 scope: String,
153}
154
155impl Drop for QueueProducerPermit {
156 fn drop(&mut self) {
157 self.slot.release_queue_producer(&self.scope);
158 }
159}
160
161/// One isolate, and everything the decision core needs to know about it.
162pub struct Slot {
163 /// The index used only inside this pool's placement snapshot and slot
164 /// vector. Distinct pools can use the same value.
165 pub id: IsolateId,
166 /// The identity reported to node-wide Actor and pressure policy.
167 heap_id: HeapId,
168 /// The async gate, holding the isolate it guards. Locking this is what
169 /// makes the V8 `Locker` beneath it uncontended.
170 ///
171 /// `None` once the isolate has been retired and freed. Retirement only
172 /// frees a slot that is drained — no turns, no affiliations — and a
173 /// retiring slot is filtered out of every placement decision, so nothing
174 /// can arrive afterwards. Entering one would be a bug in this module.
175 worker: tokio::sync::Mutex<Option<js::Worker>>,
176 turn_scheduler: TurnScheduler,
177 queue_producers: Mutex<std::collections::HashMap<String, usize>>,
178 turns: AtomicUsize,
179 requests: AtomicUsize,
180 /// The pool's admission bell, cloned into every slot so an
181 /// `Affiliation` drop can ring it without holding the pool.
182 freed: Arc<tokio::sync::Notify>,
183 /// Cells whose realm lives in this isolate. Not a count of live work: a
184 /// cell stays until it is evicted or handed to another node, which is
185 /// why `retire` refuses an isolate holding any.
186 cells: AtomicUsize,
187 // Reservations can adopt out of order; only completed adoptions count
188 // toward the collection boundary. Residency drop retires both counts.
189 adopted_cells: AtomicUsize,
190 retiring: AtomicBool,
191 #[cfg(celld_internal_tests)]
192 turn_observations: Mutex<Vec<String>>,
193}
194
195impl Slot {
196 fn observe(&self) -> IsolateLoad {
197 IsolateLoad {
198 turns: self.turns.load(Ordering::Relaxed),
199 requests: self.requests.load(Ordering::Relaxed),
200 cells: self.cells.load(Ordering::Relaxed),
201 retiring: self.retiring.load(Ordering::Relaxed),
202 }
203 }
204
205 /// Enter the isolate for one turn and run `f` inside it.
206 ///
207 /// Only the gate is awaited; `f` is synchronous by type, so holding the
208 /// isolate across an await is unwritable rather than a rule a comment
209 /// asks callers to remember.
210 pub async fn turn<T>(&self, f: impl FnOnce(&mut js::Worker) -> T) -> T {
211 self.turn_in(TurnLane::Stateless, f).await
212 }
213
214 /// Enter one cell turn through a round-robin lane for that cell. A hot
215 /// cell can retain its next place, but it cannot take the next place from
216 /// another cell that already waits on the same isolate.
217 pub async fn turn_cell<T>(&self, scope: &str, f: impl FnOnce(&mut js::Worker) -> T) -> T {
218 self.turn_in(TurnLane::Cell(scope.to_string()), f).await
219 }
220
221 async fn turn_in<T>(&self, lane: TurnLane, f: impl FnOnce(&mut js::Worker) -> T) -> T {
222 struct Counted<'a>(&'a Slot);
223 impl Drop for Counted<'_> {
224 fn drop(&mut self) {
225 self.0.turns.fetch_sub(1, Ordering::Relaxed);
226 }
227 }
228 self.turns.fetch_add(1, Ordering::Relaxed);
229 let _turn = Counted(self);
230 let _scheduled = self.turn_scheduler.acquire(lane.clone()).await;
231 let mut worker = self.worker.lock().await;
232 let worker = match worker.as_mut() {
233 Some(worker) => worker,
234 None => panic!("entered isolate {} after it was freed", self.id),
235 };
236 #[cfg(celld_internal_tests)]
237 self.turn_observations.lock().unwrap().push(match lane {
238 TurnLane::Stateless => "stateless".to_string(),
239 TurnLane::Cell(scope) => scope,
240 });
241 f(worker)
242 }
243
244 /// Reserve one event through its complete lifetime, including the reply
245 /// gate. Releasing at the gate would let stalled storage retain unbounded
246 /// promises and copied bodies. Cell turn fairness is enforced separately.
247 pub(crate) fn queue_producer(self: &Arc<Self>, scope: &str) -> Option<QueueProducerPermit> {
248 let mut producers = self
249 .queue_producers
250 .lock()
251 .expect("Queue producer admission poisoned");
252 let outstanding = producers.entry(scope.to_string()).or_default();
253 if *outstanding >= MAX_QUEUE_PRODUCER_EVENTS_PER_CELL {
254 return None;
255 }
256 *outstanding += 1;
257 Some(QueueProducerPermit {
258 slot: self.clone(),
259 scope: scope.to_string(),
260 })
261 }
262
263 fn release_queue_producer(&self, scope: &str) {
264 let mut producers = self
265 .queue_producers
266 .lock()
267 .expect("Queue producer admission poisoned");
268 let outstanding = producers
269 .get_mut(scope)
270 .expect("a Queue producer permit has an admission");
271 *outstanding -= 1;
272 if *outstanding == 0 {
273 producers.remove(scope);
274 }
275 }
276
277 /// Mark a request as living in this isolate. Held for the request's whole
278 /// life, including while it is suspended, because its promise stays in
279 /// this heap and every later turn must come back here.
280 pub fn affiliate(self: &Arc<Self>) -> Affiliation {
281 self.requests.fetch_add(1, Ordering::Relaxed);
282 Affiliation(self.clone())
283 }
284
285 /// A slot holding a Worker outside a placement pool.
286 ///
287 /// A dynamic Worker owns exactly one isolate, so it needs no
288 /// admission, growth, or retirement policy.
289 pub(crate) fn standalone(worker: js::Worker) -> Arc<Self> {
290 Arc::new(Slot {
291 id: 0,
292 heap_id: next_heap_id(),
293 worker: tokio::sync::Mutex::new(Some(worker)),
294 turn_scheduler: TurnScheduler::default(),
295 queue_producers: Mutex::new(std::collections::HashMap::new()),
296 turns: AtomicUsize::new(0),
297 requests: AtomicUsize::new(0),
298 freed: Arc::new(tokio::sync::Notify::new()),
299 cells: AtomicUsize::new(0),
300 adopted_cells: AtomicUsize::new(0),
301 retiring: AtomicBool::new(false),
302 #[cfg(celld_internal_tests)]
303 turn_observations: Mutex::new(Vec::new()),
304 })
305 }
306
307 #[cfg(celld_internal_tests)]
308 pub fn for_test(worker: js::Worker) -> Arc<Self> {
309 Self::standalone(worker)
310 }
311
312 #[cfg(all(test, celld_internal_tests))]
313 pub(crate) fn vacant_for_request_cancellation_test() -> Arc<Self> {
314 Arc::new(Slot {
315 id: 0,
316 heap_id: HeapId::new(0),
317 worker: tokio::sync::Mutex::new(None),
318 turn_scheduler: TurnScheduler::default(),
319 queue_producers: Mutex::new(std::collections::HashMap::new()),
320 turns: AtomicUsize::new(0),
321 requests: AtomicUsize::new(0),
322 freed: Arc::new(tokio::sync::Notify::new()),
323 cells: AtomicUsize::new(0),
324 adopted_cells: AtomicUsize::new(0),
325 retiring: AtomicBool::new(false),
326 turn_observations: Mutex::new(Vec::new()),
327 })
328 }
329
330 #[cfg(celld_internal_tests)]
331 #[doc(hidden)]
332 pub async fn hold_turn_for_test(&self) -> impl Drop + '_ {
333 self.worker.lock().await
334 }
335
336 #[cfg(celld_internal_tests)]
337 #[doc(hidden)]
338 pub fn queued_turns_for_test(&self) -> usize {
339 self.turns.load(Ordering::Relaxed)
340 }
341
342 #[cfg(celld_internal_tests)]
343 #[doc(hidden)]
344 pub fn reset_turn_observations_for_test(&self) {
345 self.turn_observations.lock().unwrap().clear();
346 }
347
348 #[cfg(celld_internal_tests)]
349 #[doc(hidden)]
350 pub fn turn_observations_for_test(&self) -> Vec<String> {
351 self.turn_observations.lock().unwrap().clone()
352 }
353
354 /// Give this isolate a cell's realm. Held for as long as the cell lives
355 /// here, which is what stops the isolate being retired underneath it.
356 fn house(self: &Arc<Self>, max_cells: usize) -> Residency {
357 let cells = self.cells.fetch_add(1, Ordering::Relaxed) + 1;
358 debug_assert!(cells <= max_cells);
359 Residency {
360 slot: self.clone(),
361 max_cells,
362 adopted: false,
363 }
364 }
365
366 pub fn is_retiring(&self) -> bool {
367 self.retiring.load(Ordering::Relaxed)
368 }
369
370 /// The node-wide identity of this slot's currently installed V8 heap.
371 pub fn heap_id(&self) -> HeapId {
372 self.heap_id
373 }
374
375 fn is_reusable(&self) -> bool {
376 let load = self.observe();
377 if !celld_logic::isolate::may_free(&load) || load.cells != 0 {
378 return false;
379 }
380 self.worker.try_lock().is_ok_and(|worker| worker.is_none())
381 }
382}
383
384/// A request's claim on the isolate that ran its first turn.
385pub struct Affiliation(Arc<Slot>);
386
387impl Affiliation {
388 pub fn slot(&self) -> &Arc<Slot> {
389 &self.0
390 }
391}
392
393impl Drop for Affiliation {
394 fn drop(&mut self) {
395 self.0.requests.fetch_sub(1, Ordering::Relaxed);
396 // Exactly one admission waiter per freed slot: `notify_one` hands
397 // the capacity to a single parked request, where waking them all
398 // would stampede `admit` on every release.
399 self.0.freed.notify_one();
400 }
401}
402
403/// A cell's claim on the isolate that holds its realm.
404///
405/// The counterpart of [`Affiliation`], and the difference between them is
406/// the whole reason both exist: an affiliation lasts one request, a
407/// residency lasts until the cell is evicted or moves node.
408pub struct Residency {
409 slot: Arc<Slot>,
410 max_cells: usize,
411 adopted: bool,
412}
413
414impl Residency {
415 pub fn slot(&self) -> &Arc<Slot> {
416 &self.slot
417 }
418
419 /// Open a reserved cell's storage and return its residency with its alarm snapshot.
420 /// Collection follows the last completed adoption, because reservation
421 /// order can differ from the order in which activation futures resume.
422 pub(crate) async fn adopt(
423 mut self,
424 cell: &str,
425 storage: js::CellStorage<'_>,
426 ) -> Result<(Self, celld_logic::wake::AlarmSnapshot)> {
427 anyhow::ensure!(!self.adopted, "cell residency already adopted");
428 let slot = self.slot.clone();
429 let alarm = slot
430 .turn(|worker| -> Result<celld_logic::wake::AlarmSnapshot> {
431 let alarm = worker.own_cell(cell, Some(storage))?;
432 // There is no await between adoption and accounting. Cancellation
433 // before this turn drops only the reservation; afterward the
434 // residency owns both counters, including on an error unwind.
435 self.adopted = true;
436 let adopted = slot.adopted_cells.fetch_add(1, Ordering::Relaxed) + 1;
437 debug_assert!(adopted <= self.max_cells);
438 if adopted == self.max_cells {
439 worker.settle_heap();
440 }
441 Ok(alarm)
442 })
443 .await?;
444 Ok((self, alarm))
445 }
446}
447
448impl Drop for Residency {
449 fn drop(&mut self) {
450 if self.adopted {
451 self.slot.adopted_cells.fetch_sub(1, Ordering::Relaxed);
452 }
453 self.slot.cells.fetch_sub(1, Ordering::Relaxed);
454 }
455}
456
457type Build = Box<dyn Fn() -> Result<js::Worker> + Send + Sync>;
458
459/// One pool's isolates by state, as `/state` reports them.
460#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)]
461pub struct PoolCensus {
462 /// Isolates that accept placement and work.
463 pub live: usize,
464 /// Live isolates that house no cell. The next maintenance pass retires
465 /// them, so a count that persists across passes means the pass is not
466 /// running.
467 pub live_empty: usize,
468 /// Retiring isolates whose heap is still installed, because a turn, a
469 /// request, or a cell holds it.
470 pub retiring: usize,
471 /// Slots whose heap has been freed.
472 pub freed: usize,
473 /// Cells housed across the pool.
474 pub cells: usize,
475 /// Request affiliations across the pool, running or suspended.
476 pub requests: usize,
477 /// Turns in flight across the pool.
478 pub turns: usize,
479 /// Physical memory V8 has committed to the heaps of the isolates a turn
480 /// did not hold at the sample.
481 pub heap_bytes: u64,
482 /// External memory those isolates track: array buffer stores and the
483 /// like, which live outside the V8 heap.
484 pub external_bytes: u64,
485}
486
487pub struct Pool {
488 slots: RwLock<Vec<Arc<Slot>>>,
489 limits: PoolLimits,
490 build: Build,
491 freed: Arc<tokio::sync::Notify>,
492 admission_wait: std::time::Duration,
493 /// The whole pool belongs to a superseded generation. An isolate grown
494 /// after this is set starts out retiring: a placement that snapshotted
495 /// the old generation just before the flip can still land, but nothing
496 /// it builds outlives the work it was built for.
497 retired: AtomicBool,
498 /// Keeps admission and cell placement from racing isolate retirement.
499 /// Stateless admission takes a shared guard, while maintenance and cell
500 /// placement take the exclusive guard.
501 maintenance: RwLock<()>,
502}
503
504impl Pool {
505 pub fn new(limits: PoolLimits, admission_wait: std::time::Duration, build: Build) -> Self {
506 Pool {
507 slots: RwLock::new(Vec::new()),
508 limits,
509 build,
510 freed: Arc::new(tokio::sync::Notify::new()),
511 admission_wait,
512 retired: AtomicBool::new(false),
513 maintenance: RwLock::new(()),
514 }
515 }
516
517 fn load(&self) -> PoolLoad {
518 let slots = self.slots.read().expect("pool poisoned");
519 PoolLoad {
520 isolates: slots.iter().map(|s| s.observe()).collect(),
521 limits: self.limits,
522 }
523 }
524
525 pub fn len(&self) -> usize {
526 self.slots.read().expect("pool poisoned").len()
527 }
528
529 pub fn is_empty(&self) -> bool {
530 self.len() == 0
531 }
532
533 fn get(&self, id: IsolateId) -> Arc<Slot> {
534 self.slots.read().expect("pool poisoned")[id].clone()
535 }
536
537 /// Build an isolate and admit it to the pool.
538 ///
539 /// The isolate is constructed before the lock is taken: loading a script
540 /// runs JS and can take milliseconds, and holding the pool lock across it
541 /// would stall every other placement on the node.
542 /// Build an isolate, unless a capped pool reached `cap` while this one
543 /// was being built. Cell placement passes no cap because node memory is
544 /// bounded before placement and its per-isolate limit must remain exact.
545 ///
546 /// `cap` is re-checked under the write lock because admission decides
547 /// against a snapshot it does not hold. Without the re-check every
548 /// request that saw the same pre-growth snapshot grows, so a cap of two
549 /// produced sixteen isolates under load — the breach scaled with offered
550 /// concurrency, and the configured limit was met only when serialised.
551 fn grow(&self, cap: Option<usize>) -> Result<Arc<Slot>> {
552 let worker = (self.build)()?;
553 let mut slots = self.slots.write().expect("pool poisoned");
554 let live = slots.iter().filter(|slot| !slot.is_retiring()).count();
555 if cap.is_some_and(|cap| live >= cap) {
556 if let Some(slot) = slots.iter().find(|slot| !slot.is_retiring()) {
557 return Ok(slot.clone());
558 }
559 }
560 // A freed slot has no worker, work, affiliations, or cells. Reuse its
561 // stable index so placement scans scale with the current pool rather
562 // than with every isolate created during the process lifetime.
563 let reusable = slots.iter().position(|slot| slot.is_reusable());
564 let id = reusable.unwrap_or(slots.len());
565 let heap_id = next_heap_id();
566 let slot = Arc::new(Slot {
567 id,
568 heap_id,
569 worker: tokio::sync::Mutex::new(Some(worker)),
570 turn_scheduler: TurnScheduler::default(),
571 queue_producers: Mutex::new(std::collections::HashMap::new()),
572 turns: AtomicUsize::new(0),
573 requests: AtomicUsize::new(0),
574 freed: self.freed.clone(),
575 cells: AtomicUsize::new(0),
576 adopted_cells: AtomicUsize::new(0),
577 retiring: AtomicBool::new(self.retired.load(Ordering::Relaxed)),
578 #[cfg(celld_internal_tests)]
579 turn_observations: Mutex::new(Vec::new()),
580 });
581 if let Some(id) = reusable {
582 slots[id] = slot.clone();
583 } else {
584 slots.push(slot.clone());
585 }
586 tracing::info!(isolate = %heap_id, slot = id, total = slots.len(), "isolate started");
587 Ok(slot)
588 }
589
590 fn resolve(&self, placement: Placement, cap: Option<usize>) -> Result<Arc<Slot>> {
591 match placement {
592 Placement::Existing(id) => Ok(self.get(id)),
593 Placement::Grow => self.grow(cap),
594 }
595 }
596
597 /// Build one isolate up front.
598 ///
599 /// The pool is otherwise lazy, and an idle node holding no isolates is the
600 /// point. But the first isolate is built at startup for two reasons that
601 /// laziness cannot serve: a node whose script does not load must fail
602 /// *then*, not once per request forever after; and compiling the script
603 /// inside the first request adds its whole cost to that request's latency,
604 /// which a startup probe reads as a node that never came up.
605 pub fn warm(&self) -> Result<()> {
606 self.grow(Some(self.limits.max_stateless))?;
607 Ok(())
608 }
609
610 /// Take a stateless request, or refuse it.
611 ///
612 /// One call against one snapshot: admission and placement are the same
613 /// decision, so the node cannot admit a request it then fails to place.
614 pub fn admit(&self, shedding: bool) -> Result<Affiliation, AdmitError> {
615 // A configured request ceiling must remain exact under concurrent
616 // admission, so serialize the check and reservation only in that
617 // mode. The default unbounded path keeps concurrent shared access.
618 if self.limits.max_requests.is_some() {
619 let _maintenance = self.maintenance.write().expect("pool poisoned");
620 self.admit_locked(shedding)
621 } else {
622 let _maintenance = self.maintenance.read().expect("pool poisoned");
623 self.admit_locked(shedding)
624 }
625 }
626
627 fn admit_locked(&self, shedding: bool) -> Result<Affiliation, AdmitError> {
628 let placement = celld_logic::isolate::admit(&self.load(), shedding)?;
629 self.resolve(placement, Some(self.limits.max_stateless))
630 .map(|slot| slot.affiliate())
631 .map_err(AdmitError::Build)
632 }
633
634 /// [`admit`](Self::admit), except a request that finds the node full
635 /// waits — bounded — for a slot instead of being refused at once.
636 ///
637 /// The wait is the middle gear between "admit" and "refuse". At
638 /// overload the parse-and-503 path costs about half a served request,
639 /// so a node refusing 200k times a second spends its cores saying no.
640 /// A parked waiter costs nothing until an `Affiliation` drop hands it
641 /// the slot, and the excess load queues in kernel socket buffers
642 /// behind connections nobody is reading. `NodePressured` still
643 /// refuses at once: pressure means give resources back, not hold
644 /// callers.
645 pub async fn admit_or_wait(&self, shedding: bool) -> Result<Affiliation, AdmitError> {
646 let deadline_ms =
647 crate::asyncrt::mono_ms().saturating_add(self.admission_wait.as_millis() as u64);
648 loop {
649 // Armed before the check: a slot freed between a failed admit
650 // and the park would otherwise be a lost wakeup.
651 let freed = self.freed.notified();
652 match self.admit(shedding) {
653 Err(AdmitError::Refused(Refusal::NodeFull)) => {
654 tokio::pin!(freed);
655 // A freed slot before the deadline: both arms end the
656 // wait, so declaring the order costs nothing and makes
657 // the branch replayable. Priority to the wakeup, because
658 // a slot that freed in the same instant the deadline
659 // expired is a slot the caller can have.
660 crate::asyncrt::select_biased! {
661 "a slot freed in the same instant as the deadline goes to the caller";
662 _ = &mut freed => {},
663 _ = crate::asyncrt::sleep_until(deadline_ms) => {
664 return Err(AdmitError::Refused(Refusal::NodeFull));
665 }
666 }
667 }
668 other => return other,
669 }
670 }
671 }
672
673 /// Give a cell a home, building an isolate if every one is full.
674 ///
675 /// The counterpart of [`admit`](Self::admit) and deliberately the same
676 /// shape: one call against one snapshot. It cannot refuse — by the time
677 /// a cell needs a realm, ownership has already agreed the node serves
678 /// it, so `celld_logic::isolate::place_cell` always answers.
679 pub fn place_cell(&self) -> Result<Residency> {
680 let _maintenance = self.maintenance.write().expect("pool poisoned");
681 let placement = celld_logic::isolate::place_cell(&self.load());
682 // Cell isolates have no arbitrary total cap. The resident-cell and
683 // RSS limits bound node memory before placement. The lock keeps this
684 // reservation exact and prevents maintenance from retiring the slot.
685 Ok(self.resolve(placement, None)?.house(self.limits.max_cells))
686 }
687
688 /// One maintenance pass: give back an isolate the pool no longer needs,
689 /// and free whatever has finished draining.
690 ///
691 /// Without this the pool only grows. A burst takes it to `max_stateless`
692 /// and every one of those V8 heaps is held for the life of the process,
693 /// which is the whole reason `celld_logic::isolate::retire` exists —
694 /// and, until this existed, the reason it was dead code hiding a leak.
695 ///
696 /// Retire at most one isolate. Stateless pools use this paced maintenance
697 /// so a quiet interval does not discard every warm compiled Worker.
698 pub fn reap(&self) {
699 // Maintenance runs on a Tokio worker. Skip this pass when a blocking
700 // cell start is compiling an isolate instead of blocking the worker.
701 let Ok(_maintenance) = self.maintenance.try_write() else {
702 return;
703 };
704 self.retire_one();
705 self.free_retired();
706 }
707
708 /// Retire every empty isolate. Cell pools use this after eviction because
709 /// an empty cell heap carries no warm request capacity worth preserving.
710 pub fn reap_empty(&self) {
711 let Ok(_maintenance) = self.maintenance.try_write() else {
712 tracing::debug!(
713 event = "isolate_reap_skipped",
714 "a cell start holds the pool; empty isolates wait for the next pass"
715 );
716 return;
717 };
718 while self.retire_one() {}
719 self.free_retired();
720 }
721
722 /// Retire every isolate, housed or not: the pool belongs to a superseded
723 /// application generation and must take no new work. Stateless slots
724 /// free as their affiliations drop; a slot hosting cells frees once the
725 /// last of them has moved to a newer generation, which `may_free`
726 /// enforces by refusing a housed isolate.
727 pub fn retire_all(&self) {
728 let _maintenance = self.maintenance.write().expect("pool poisoned");
729 self.retired.store(true, Ordering::Relaxed);
730 for slot in self.slots.read().expect("pool poisoned").iter() {
731 if !slot.retiring.swap(true, Ordering::Relaxed) {
732 tracing::info!(isolate = %slot.heap_id, slot = slot.id, "isolate retiring");
733 }
734 }
735 self.free_retired();
736 }
737
738 /// Whether every isolate this pool ever built has been freed. True for a
739 /// pool that never grew, so a generation whose scripts took no traffic
740 /// drains at once.
741 pub fn is_drained(&self) -> bool {
742 self.slots
743 .read()
744 .expect("pool poisoned")
745 .iter()
746 .all(|slot| slot.worker.try_lock().is_ok_and(|worker| worker.is_none()))
747 }
748
749 fn retire_one(&self) -> bool {
750 let Some(id) = celld_logic::isolate::retire(&self.load()) else {
751 return false;
752 };
753 let slot = self.get(id);
754 if !slot.retiring.swap(true, Ordering::Relaxed) {
755 tracing::info!(isolate = %slot.heap_id, slot = id, "isolate retiring");
756 }
757 true
758 }
759
760 fn free_retired(&self) {
761 // A retiring isolate takes no new work, so once its counters reach
762 // zero nothing can enter it again and its heap can go. `try_lock`
763 // rather than blocking: if a turn holds it, it is not drained and
764 // this pass has nothing to do.
765 for slot in self.slots.read().expect("pool poisoned").iter() {
766 if !celld_logic::isolate::may_free(&slot.observe()) {
767 continue;
768 }
769 let Ok(mut worker) = slot.worker.try_lock() else {
770 continue;
771 };
772 if worker.take().is_some() {
773 tracing::info!(isolate = %slot.heap_id, slot = slot.id, "isolate freed");
774 }
775 }
776 }
777
778 /// Return the current live-isolate count.
779 pub fn live(&self) -> usize {
780 self.slots
781 .read()
782 .expect("pool poisoned")
783 .iter()
784 .filter(|slot| !slot.is_retiring())
785 .count()
786 }
787
788 /// What the pool holds right now, for `/state`.
789 ///
790 /// The count an operator of a hibernation-heavy node needs and could
791 /// not get: a dormant cell keeps about 160 KB more than its own records
792 /// explain (GCE, 2026-09-03), and the one O(cells) structure
793 /// that fits is the isolate. `live_empty` is what `reap_empty` retires
794 /// on its next pass and `retiring` is what `may_free` still refuses, so
795 /// either staying positive across passes names the leak.
796 pub fn census(&self) -> PoolCensus {
797 let mut census = PoolCensus::default();
798 for slot in self.slots.read().expect("pool poisoned").iter() {
799 let load = slot.observe();
800 census.cells += load.cells;
801 census.requests += load.requests;
802 census.turns += load.turns;
803 // A heap is gone once its worker was taken. A worker a turn
804 // holds right now is installed, so a failed `try_lock` counts
805 // as a heap and never as freed; its size is unknown this pass.
806 // Holding the guard is the permit a turn holds, which is what
807 // makes the V8 lock inside `heap_bytes` uncontended.
808 match slot.worker.try_lock() {
809 Ok(worker) if worker.is_none() => {
810 census.freed += 1;
811 continue;
812 }
813 Ok(worker) => {
814 if let Some(heap) = worker.as_ref().and_then(js::Worker::heap_bytes) {
815 census.heap_bytes += heap.physical;
816 census.external_bytes += heap.external;
817 }
818 }
819 Err(_) => {}
820 }
821 if load.retiring {
822 census.retiring += 1;
823 } else {
824 census.live += 1;
825 if load.cells == 0 {
826 census.live_empty += 1;
827 }
828 }
829 }
830 census
831 }
832}
833
834/// Refused by policy, or the isolate could not be built. Distinct because the
835/// first is a 503 the caller may retry elsewhere and the second is a fault.
836#[derive(Debug)]
837pub enum AdmitError {
838 Refused(Refusal),
839 Build(anyhow::Error),
840}
841
842impl From<Refusal> for AdmitError {
843 fn from(refusal: Refusal) -> Self {
844 AdmitError::Refused(refusal)
845 }
846}
847
848impl std::fmt::Display for AdmitError {
849 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
850 match self {
851 AdmitError::Refused(Refusal::NodeFull) => {
852 write!(f, "node is at its stateless request limit")
853 }
854 AdmitError::Refused(Refusal::NodePressured) => write!(f, "node is shedding load"),
855 AdmitError::Build(error) => write!(f, "isolate could not be started: {error}"),
856 }
857 }
858}
859
860impl std::error::Error for AdmitError {}
861
862/// The property the whole design rests on: an isolate and everything hanging
863/// off it can be reached from any tokio worker. This is what `v8::Locker` and
864/// `Send` Globals buy (denoland/rusty_v8#2044, #2045); without them
865/// `js::Worker` would not be `Send` and the pool could not exist.
866///
867/// A compile-time check rather than a comment, because losing it would show
868/// up as a confusing error somewhere far away.
869const _: fn() = || {
870 fn assert_send_sync<T: Send + Sync>() {}
871 assert_send_sync::<Pool>();
872 assert_send_sync::<Slot>();
873 assert_send_sync::<Affiliation>();
874};