Diffinery

homeflare/celldpublic

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