Diffinery

homeflare/celldpublic

celld/crates/celld/actor.rs
4419 lines · 179.0 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3//! The serial lifecycle executor and its shell-side request drivers.
4
5use crate::cell_host::CellHost;
6use crate::js::{HttpResponse, WsBatch};
7use crate::machine::{
8 ownership_on_evict_from_environment, pressure_config_from_environment,
9 random_process_generation, DEFAULT_MAX_OUTBOUND_WEBSOCKETS,
10 DEFAULT_OWNER_LOG_RECOVERY_ATTEMPTS, DEFAULT_OWNER_LOG_RECOVERY_BACKOFF_MS,
11};
12use crate::ownership_store::{now_ms, BucketOwnership, LeaseCasError};
13use crate::peer_auth::{self, PeerAuth};
14use crate::runtime::RuntimeManager;
15use anyhow::Context as _;
16use celld_logic::{
17 on_event, AdoptedCell, CapacityPeer, CasGuard, CasOutcome, CellId, Channel, Config, Effect,
18 Event, EvictionAdmission, Failure, LeaseCasOutcome, NodeLeaseRecord, NodeLeaseSpec, OpId,
19 OwnerRecord, OwnershipOnEvict, Phase, RequestError, Route, State, StopCause, Timer,
20 WebSocketKind, WorkerRoute,
21};
22use futures_util::stream::FuturesUnordered;
23use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
24use std::future::Future;
25use std::pin::Pin;
26use std::sync::atomic::{AtomicUsize, Ordering};
27use std::sync::Arc;
28use tokio::sync::{mpsc, oneshot, watch, Mutex};
29use tokio_util::time::{delay_queue, DelayQueue};
30
31mod effects;
32mod local_request;
33mod production;
34pub use celld_logic::{EvictCancellation, EvictError, EvictFailure, EvictRefusal, EvictSuccess};
35pub use effects::StepOutput;
36pub(crate) use effects::{drain_step_output, LeaseRequest};
37pub use local_request::{LocalRequest, LocalRequestCompletion, LocalRequestFailure};
38
39type EvictionReply = oneshot::Sender<Result<EvictSuccess, EvictError>>;
40
41const DEFAULT_OPERATION_DEADLINE_MS: u64 = 15_000;
42/// How long a graceful handoff keeps refreshing an uncovered alarm's wake
43/// entry before it gives up and lets the drain deadline decide.
44const HANDOFF_ALARM_COVERAGE_MS: u64 = 5_000;
45
46/// The shell's deadline for one actor operation. Queue leases include this
47/// exact budget for their settlement call, so the actor and broker must read
48/// one accessor rather than duplicate the environment default.
49#[doc(hidden)]
50pub fn operation_deadline_ms() -> anyhow::Result<u64> {
51 crate::env_vars::positive_or("CELLD_OPERATION_DEADLINE_MS", DEFAULT_OPERATION_DEADLINE_MS)
52}
53
54#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
55pub enum TimerSlot {
56 NodeLeaseRenew,
57 NodeLeaseFence,
58 CellAlarm(String),
59 /// Keyed by operation, deliberately. Every other timer here coalesces
60 /// because only its newest arming matters; a deadline is the opposite --
61 /// each watches a different outstanding operation, and a shared slot
62 /// would let arming one silently cancel another, leaving every activation
63 /// but the most recent with nothing watching it.
64 OperationDeadline(OpId),
65 /// Keyed by cell and generation for the same reason as the deadline
66 /// above: a node parks many cells at once, and one slot per cell would
67 /// let a later parking disarm an earlier one.
68 QueuedActivation(String, u64),
69 /// Keyed like `QueuedActivation`: one pending retry per cell, and a
70 /// newer episode's arming supersedes a stale one.
71 OwnerLogRecoveryRetry(String, u64),
72}
73
74impl TimerSlot {
75 pub fn of(timer: &Timer) -> Self {
76 match timer {
77 Timer::NodeLeaseRenew { .. } => Self::NodeLeaseRenew,
78 Timer::NodeLeaseFence { .. } => Self::NodeLeaseFence,
79 Timer::CellAlarm { cell, .. } => Self::CellAlarm(cell.clone()),
80 Timer::OperationDeadline { op } => Self::OperationDeadline(*op),
81 Timer::QueuedActivation { cell, generation } => {
82 Self::QueuedActivation(cell.clone(), *generation)
83 }
84 Timer::OwnerLogRecoveryRetry { cell, generation } => {
85 Self::OwnerLogRecoveryRetry(cell.clone(), *generation)
86 }
87 }
88 }
89}
90
91/// One versioned timer arm emitted by an Actor step.
92#[derive(Clone, Debug, PartialEq, Eq)]
93pub struct TimerArm {
94 pub slot: TimerSlot,
95 pub ordinal: u64,
96 pub timer: Timer,
97 pub at_mono_ms: u64,
98}
99
100/// The shared displacement discipline for production and deterministic timers.
101///
102/// `armed` is the only per-slot map, so what this holds is bounded by the
103/// timers that are armed right now. A second map keyed by slot would not be:
104/// `TimerSlot::OperationDeadline` names a unique `OpId`, and the Actor arms
105/// one deadline for every watched effect, so a slot-keyed entry that outlives
106/// its arm grows once per operation for the lifetime of the process.
107pub struct TimerSlots<V> {
108 armed: BTreeMap<TimerSlot, (u64, V)>,
109 next_ordinal: u64,
110}
111
112impl<V> Default for TimerSlots<V> {
113 fn default() -> Self {
114 Self {
115 armed: BTreeMap::new(),
116 next_ordinal: 0,
117 }
118 }
119}
120
121impl<V> TimerSlots<V> {
122 /// Creates one arm, assigns its ordinal, and applies it.
123 ///
124 /// The ordinal counts arms of every slot together rather than arms of one
125 /// slot, so no slot-keyed counter has to outlive the arm it numbered. A
126 /// per-slot counter pruned when its slot leaves `armed` would restart at
127 /// zero, and [`fire`](Self::fire) would then accept a spent arm as the
128 /// arm that replaced it.
129 pub fn arm(&mut self, timer: Timer, at_mono_ms: u64, value: V) -> (TimerArm, Option<V>) {
130 let slot = TimerSlot::of(&timer);
131 let ordinal = self.next_ordinal;
132 self.next_ordinal = ordinal.saturating_add(1);
133 let arm = TimerArm {
134 slot: slot.clone(),
135 ordinal,
136 timer,
137 at_mono_ms,
138 };
139 let displaced = self.replace(&slot, ordinal, value);
140 (arm, displaced)
141 }
142
143 /// Applies an arm whose ordinal the Actor has already assigned.
144 pub fn install(&mut self, arm: &TimerArm, value: V) -> Option<V> {
145 self.replace(&arm.slot, arm.ordinal, value)
146 }
147
148 fn replace(&mut self, slot: &TimerSlot, ordinal: u64, value: V) -> Option<V> {
149 let displaced = self
150 .armed
151 .insert(slot.clone(), (ordinal, value))
152 .map(|(_, value)| value);
153 debug_assert!(
154 displaced.is_none() || !matches!(slot, TimerSlot::OperationDeadline(_)),
155 "an operation deadline displaced another: {slot:?}"
156 );
157 displaced
158 }
159
160 /// Removes the current arm only when both parts of its identity match.
161 pub fn fire(&mut self, slot: &TimerSlot, ordinal: u64) -> Option<V> {
162 if self
163 .armed
164 .get(slot)
165 .is_some_and(|(armed, _)| *armed == ordinal)
166 {
167 self.armed.remove(slot).map(|(_, value)| value)
168 } else {
169 None
170 }
171 }
172
173 fn clear_slot(&mut self, slot: &TimerSlot) {
174 self.armed.remove(slot);
175 }
176
177 /// Every slot this map still retains, across all of its bookkeeping.
178 ///
179 /// `TimerSlot::OperationDeadline` carries a unique `OpId`, so a per-slot
180 /// entry that outlives its arm grows once per operation and never
181 /// shrinks. The count exists so a test can prove the map returns to the
182 /// armed set. A map added beside `armed` must be counted here.
183 #[cfg(all(test, celld_internal_tests))]
184 pub fn retained_slots(&self) -> usize {
185 self.armed.len()
186 }
187}
188
189pub struct MemoryOwnership {
190 node: String,
191 owners: BTreeMap<String, OwnerRecord>,
192 leases: BTreeMap<String, NodeLeaseRecord>,
193 next_etag: u64,
194}
195
196#[derive(Clone)]
197pub enum Ownership {
198 Memory(Arc<Mutex<MemoryOwnership>>),
199 Bucket(Arc<BucketOwnership>),
200}
201
202fn ownership_read_failed(error: anyhow::Error) -> Failure {
203 eprintln!("celld ownership read failed: {error:#}");
204 Failure::Definite
205}
206
207impl Ownership {
208 /// Read the record as it is stored. A missing record here means only that
209 /// no record exists now, so this read must not decide a claim; the core
210 /// reads through [`Self::read_owner_for_claim`].
211 pub(crate) async fn read_owner(&self, cell: &str) -> Result<Option<OwnerRecord>, Failure> {
212 match self {
213 Self::Memory(memory) => Ok(memory.lock().await.owners.get(cell).cloned()),
214 Self::Bucket(bucket) => bucket.read_owner(cell).await.map_err(ownership_read_failed),
215 }
216 }
217
218 /// Read the record for the core, which claims epoch one as a fresh cell
219 /// when the record is missing.
220 pub(crate) async fn read_owner_for_claim(
221 &self,
222 cell: &str,
223 ) -> Result<Option<OwnerRecord>, Failure> {
224 // Memory ownership runs without replication, so it never has LTX.
225 let Self::Bucket(bucket) = self else {
226 return self.read_owner(cell).await;
227 };
228 if bucket.lost_record_held(cell, crate::asyncrt::mono_ms()) {
229 return Err(Failure::Definite);
230 }
231 let record = self.read_owner(cell).await?;
232 if record.is_some()
233 || !bucket
234 .ltx_exists(cell)
235 .await
236 .map_err(ownership_read_failed)?
237 {
238 return Ok(record);
239 }
240 // A claim writes the record before any LTX, and celld never deletes
241 // the record, so LTX proves that a record existed before the listing.
242 // A first claim on another node can still write it after the first
243 // read. Only a read after the listing that finds no record proves a
244 // loss; without it, this node fails a request that it can forward and
245 // reports a record that exists.
246 if let Some(record) = self.read_owner(cell).await? {
247 return Ok(Some(record));
248 }
249 // A missing record tells the core that the cell was never owned, so
250 // the core claims epoch one as a fresh cell and the activation
251 // restores nothing. celld never deletes `own.json`, but a bucket
252 // lifecycle rule, a manual cleanup, or a partial bucket copy can. The
253 // cell would then serve an empty database beside its acknowledged
254 // chain and ship over `e1/`, and a node that asks while the owner
255 // still serves would become a second writer. Failing the read writes
256 // nothing: each claim fails until an operator restores the record and
257 // the hold ends.
258 // A refusal in `LtxRepl::activate_with` comes too late, because the
259 // claim has already written a record at epoch one. Each later wake
260 // then advances one epoch, and a wake without a takeover can reuse a
261 // stale local eviction snapshot, which skips the used-epoch check.
262 eprintln!(
263 "celld ownership record lost: cells/{cell}/own.json is missing, but the bucket \
264 holds LTX under cells/{cell}/ltx/; refusing to claim {cell} as a new cell for \
265 {} s. See the ownership record repair in docs/guarantees.md.",
266 crate::ownership_store::LOST_RECORD_RECHECK_MS / 1_000
267 );
268 bucket.hold_lost_record(cell, crate::asyncrt::mono_ms());
269 Err(Failure::Definite)
270 }
271
272 async fn read_node_lease(&self, owner: &str) -> Result<Option<NodeLeaseRecord>, Failure> {
273 match self {
274 Self::Memory(memory) => Ok(memory.lock().await.leases.get(owner).cloned()),
275 Self::Bucket(bucket) => bucket.read_node_lease(owner).await.map_err(|error| {
276 eprintln!("celld node lease read failed: {error:#}");
277 Failure::Definite
278 }),
279 }
280 }
281
282 async fn read_capacity_peers(&self) -> Result<Vec<celld_logic::CapacityPeer>, Failure> {
283 match self {
284 // The in-memory adapter is a single-node development mode. It has
285 // no external membership enumeration to offer.
286 Self::Memory(_) => Ok(Vec::new()),
287 Self::Bucket(bucket) => bucket.read_capacity_peers().await.map_err(|error| {
288 eprintln!("celld capacity peer read failed: {error:#}");
289 Failure::Definite
290 }),
291 }
292 }
293
294 /// The shared fleet sample and the instant it was taken, for placement.
295 async fn read_capacity_view(&self) -> Result<(u64, Vec<celld_logic::CapacityPeer>), Failure> {
296 match self {
297 Self::Memory(_) => Ok((now_ms(), Vec::new())),
298 Self::Bucket(bucket) => bucket.read_shared_capacity_view().await.map_err(|error| {
299 eprintln!("celld capacity view read failed: {error:#}");
300 Failure::Definite
301 }),
302 }
303 }
304
305 async fn read_self_node_lease(&self, node: &str) -> Result<Option<NodeLeaseRecord>, Failure> {
306 match self {
307 Self::Memory(memory) => Ok(memory.lock().await.leases.get(node).cloned()),
308 Self::Bucket(bucket) => bucket.read_self_node_lease(node).await.map_err(|error| {
309 eprintln!("celld self node lease read failed: {error:#}");
310 Failure::Definite
311 }),
312 }
313 }
314
315 async fn cas_owner(
316 &self,
317 cell: &str,
318 guard: CasGuard,
319 epoch: u64,
320 ) -> Result<CasOutcome, Failure> {
321 match self {
322 Self::Memory(memory) => {
323 let mut memory = memory.lock().await;
324 let allowed = match guard {
325 CasGuard::Absent => !memory.owners.contains_key(cell),
326 CasGuard::Match(expected) => memory
327 .owners
328 .get(cell)
329 .is_some_and(|owner| owner.etag == expected),
330 };
331 if allowed {
332 let etag = format!("e{}", memory.next_etag);
333 memory.next_etag += 1;
334 let node = memory.node.clone();
335 memory.owners.insert(
336 cell.into(),
337 OwnerRecord {
338 node: Some(node),
339 epoch,
340 etag,
341 },
342 );
343 }
344 Ok(if allowed {
345 CasOutcome::Applied
346 } else {
347 CasOutcome::Rejected
348 })
349 }
350 Self::Bucket(bucket) => bucket.cas_owner(cell, guard, epoch).await.map_err(|error| {
351 // Any transport or 5xx failure may have happened after the
352 // store committed. The core reconciles by reading the owner
353 // again.
354 eprintln!("celld ownership CAS ambiguous: {error:#}");
355 Failure::Ambiguous
356 }),
357 }
358 }
359
360 async fn release_owner(&self, cell: &str, epoch: u64) -> Result<CasOutcome, Failure> {
361 match self {
362 Self::Memory(memory) => {
363 let mut memory = memory.lock().await;
364 let node = memory.node.clone();
365 let releasable = memory.owners.get(cell).is_some_and(|owner| {
366 owner.node.as_deref() == Some(node.as_str()) && owner.epoch == epoch
367 });
368 if releasable {
369 let etag = format!("e{}", memory.next_etag);
370 memory.next_etag += 1;
371 memory.owners.insert(
372 cell.into(),
373 OwnerRecord {
374 node: None,
375 epoch,
376 etag,
377 },
378 );
379 }
380 Ok(if releasable {
381 CasOutcome::Applied
382 } else {
383 CasOutcome::Rejected
384 })
385 }
386 // A release that may or may not have committed needs no
387 // reconciliation: the record either still names this node, and the
388 // next eviction releases it again, or it does not, and the cell is
389 // already free. Either way nothing is owed.
390 Self::Bucket(bucket) => bucket.release_owner(cell, epoch).await.map_err(|error| {
391 eprintln!("celld ownership release failed: {error:#}");
392 Failure::Definite
393 }),
394 }
395 }
396
397 async fn cas_node_lease(
398 &self,
399 guard: CasGuard,
400 mut record: NodeLeaseRecord,
401 stamped: &mut Option<celld_logic::log_tier::LogState>,
402 ) -> Result<LeaseCasOutcome, Failure> {
403 match self {
404 Self::Memory(memory) => {
405 let mut memory = memory.lock().await;
406 let current = memory.leases.get(&record.node);
407 let allowed = match guard {
408 CasGuard::Absent => current.is_none(),
409 CasGuard::Match(expected) => {
410 current.is_some_and(|lease| lease.etag == expected)
411 }
412 };
413 if !allowed {
414 return Ok(LeaseCasOutcome::Rejected);
415 }
416 let etag = format!("e{}", memory.next_etag);
417 memory.next_etag += 1;
418 record.etag = etag.clone();
419 *stamped = record.log_state;
420 memory.leases.insert(record.node.clone(), record);
421 Ok(LeaseCasOutcome::Applied { etag })
422 }
423 Self::Bucket(bucket) => bucket
424 .cas_node_lease(guard, &record, stamped)
425 .await
426 .map_err(|error| match error {
427 // The write provably did not commit, so the record
428 // still holds what the prior attempt left. A readback
429 // would only spend authority to re-learn that, and the
430 // renewal window is exactly what a store blip is
431 // eating.
432 LeaseCasError::NotCommitted(error) => {
433 eprintln!("celld node-lease CAS did not commit: {error:#}");
434 Failure::Definite
435 }
436 LeaseCasError::Ambiguous(error) => {
437 eprintln!("celld node-lease CAS ambiguous: {error:#}");
438 Failure::Ambiguous
439 }
440 }),
441 }
442 }
443
444 pub fn name(&self) -> &'static str {
445 match self {
446 Self::Memory(_) => "memory",
447 Self::Bucket(bucket) => bucket.storage_scheme(),
448 }
449 }
450}
451
452/// The identity that lets a request finish on a quiescing resident, where an
453/// ordinary request waits for the successor route. One field holds it, so a
454/// request cannot claim two identities.
455#[derive(Clone, Copy, Debug, PartialEq, Eq)]
456pub enum ResidentWork {
457 /// An event from this exact registered WebSocket.
458 WebSocket(u64),
459 /// The output gate for an effect that the cell's running work raised.
460 OutputGate,
461}
462
463pub enum Message {
464 /// A periodic resource sample. The measuring is the shell's job; every
465 /// decision that follows belongs to the core.
466 SampleLoad(crate::host_services::HostMetricsSample),
467 /// The log tier changed the folded log object the next lease write
468 /// must carry (lease-fold): renew now so the change becomes durable.
469 NudgeNodeLease,
470 /// Stop new internal routing while a clean same-node reload drains. The
471 /// request shell has already stopped admission; this closes wake and
472 /// service paths that do not pass through the HTTP gate.
473 BeginPreserve,
474 /// The node adopted a new application generation. Resident cells on an
475 /// older one move to it at a safe point, or by force after `max_age_ms`;
476 /// cells of an eager class move at once.
477 GenerationChanged {
478 generation: crate::generation::GenerationId,
479 max_age_ms: u64,
480 eager_classes: Vec<String>,
481 },
482 /// Graceful shutdown: release every owned cell's record so peers take
483 /// over immediately. The release writes run as effects inside the
484 /// shutdown drain window, and the drain waits for them to complete —
485 /// bounded by the drain deadline, so a wedged store still cannot hold
486 /// the exit hostage.
487 ReleaseAll,
488 /// Give up to `cells` idle cells to the fleet. The balancing loop sends
489 /// this after it has confirmed from the leases that this node is the
490 /// densest and a peer has room.
491 Rebalance {
492 cells: usize,
493 },
494 /// Has the shutdown handoff finished? True once no cell occupies
495 /// capacity: nothing resident, restoring, or mid-eviction. The drain
496 /// loop polls this to exit as soon as the handoff completes instead of
497 /// sitting out the full drain window.
498 Drained {
499 reply: oneshot::Sender<DrainStatus>,
500 },
501 Request {
502 request: u64,
503 cell: String,
504 capacity_handoff: bool,
505 /// Present only for the signed shutdown-handoff endpoint. The actor
506 /// settles this channel as soon as the ownership CAS is authoritative;
507 /// the ordinary route reply remains pending until it is cancelled.
508 handoff_accept: Option<HandoffAcceptWaiter>,
509 /// Work that can finish on a quiescing resident. Ordinary requests
510 /// carry none and wait for the successor route.
511 resident_work: Option<ResidentWork>,
512 reply: oneshot::Sender<Result<Routed, RequestError>>,
513 },
514 /// A caller disappeared before routing finished. The request identity is
515 /// allocated by the shell, so the actor can remove it from either cold
516 /// admission queue immediately.
517 CancelRoute {
518 request: u64,
519 },
520 WorkerRequest {
521 reply: oneshot::Sender<WorkerRouted>,
522 },
523 ActivityFinished {
524 request: u64,
525 // The activity drop also observes the cell's alarm. Folded in here so a
526 // request's completion costs the serial core one message, not two — the
527 // hot path for every routed DO call.
528 cell: String,
529 alarm: celld_logic::wake::AlarmSnapshot,
530 alarm_covered: bool,
531 },
532 /// An outbound effect is ready to leave on `channel`. A write opens a
533 /// durability barrier, and a read trails the newest barrier already open on
534 /// its cell. The channel rides along so the release can be routed back to
535 /// whichever adapter is holding the effect.
536 Output {
537 request: u64,
538 ticket: GateTicket,
539 reply: oneshot::Sender<Result<(), RequestError>>,
540 },
541 /// A `webSocketMessage` finished; hand its captured outbound frames to the
542 /// cell's output gate. `write_position` present means the handler wrote, so
543 /// the frames are held behind that write until it is durable; absent means
544 /// flush them behind the proof of what the handler observed, if a proof is
545 /// still owed for that (`observed`, as on [`GateTicket`]), else behind any
546 /// earlier still-pending write, else immediately.
547 WsOutput {
548 request: u64,
549 scope: String,
550 frames: WsBatch,
551 write_position: Option<u64>,
552 observed: Option<u64>,
553 reply: oneshot::Sender<()>,
554 },
555 WebSocketOpened {
556 cell: String,
557 websocket: u64,
558 kind: WebSocketKind,
559 reply: oneshot::Sender<bool>,
560 },
561 WebSocketClosed {
562 cell: String,
563 websocket: u64,
564 },
565 AlarmObserved {
566 cell: String,
567 alarm: celld_logic::wake::AlarmSnapshot,
568 covered: bool,
569 },
570 MaintainWake {
571 cell: String,
572 },
573 WakeHint {
574 cell: String,
575 entry_ms: i64,
576 scope: celld_logic::WakeHintScope,
577 },
578 Evict {
579 cell: String,
580 reply: EvictionReply,
581 },
582 InvalidateRemote {
583 cell: String,
584 node: String,
585 epoch: u64,
586 reply: oneshot::Sender<()>,
587 },
588 Snapshot {
589 reply: oneshot::Sender<(String, Vec<celld_logic::DrainPin>, SwapCensus)>,
590 },
591 Health {
592 reply: oneshot::Sender<bool>,
593 },
594 Presence {
595 reply: oneshot::Sender<celld_logic::PresenceSnapshot>,
596 },
597 ResidentEpoch {
598 cell: String,
599 reply: oneshot::Sender<Option<u64>>,
600 },
601}
602
603#[derive(Clone, Copy, Debug, PartialEq, Eq)]
604pub enum ShutdownMode {
605 /// The logical node is leaving. Release every owner record so another
606 /// node can take over without waiting for the node lease to expire.
607 Handoff,
608 /// The same logical node will start again at the same address. Drain the
609 /// request shell, but keep ownership and the local replica cache intact.
610 Preserve,
611}
612
613pub struct Routed {
614 pub request: u64,
615 pub route: Route,
616}
617
618/// A test-only receipt for three request-path outcomes. `AppHandle::request`
619/// deliberately maps both channel failures to `NodeFenced`, so its public
620/// result cannot identify which asynchronous seam failed.
621#[cfg(all(test, celld_internal_tests))]
622#[derive(Clone, Debug, PartialEq, Eq)]
623pub(crate) enum RequestPathReceiptForTest {
624 SubmissionFailure {
625 request: u64,
626 },
627 ReplyChannelClosed {
628 request: u64,
629 },
630 Returned {
631 allocated_request: u64,
632 result: Result<(u64, Route), RequestError>,
633 },
634}
635
636/// A test-only receipt for three output-gate outcomes. The public gate maps
637/// both channel failures to `NodeFenced`, so its result cannot identify which
638/// asynchronous seam failed.
639#[cfg(all(test, celld_internal_tests))]
640#[derive(Clone, Debug, PartialEq, Eq)]
641pub(crate) enum OutputGateReceiptForTest {
642 SubmissionFailure {
643 request: u64,
644 },
645 ReplyChannelClosed {
646 request: u64,
647 },
648 Returned {
649 request: u64,
650 result: Result<(), RequestError>,
651 },
652}
653
654enum RequestPathOutcome {
655 SubmissionFailure,
656 ReplyChannelClosed,
657 Returned(Result<Routed, RequestError>),
658}
659
660enum OutputGateOutcome {
661 SubmissionFailure,
662 ReplyChannelClosed,
663 Returned(Result<(), RequestError>),
664}
665
666#[derive(Clone, Copy, Default)]
667pub struct DrainStatus {
668 pub occupied: usize,
669 pub activating: usize,
670 /// Resident cells reserved for shutdown handoff. New requests wait for
671 /// their successor routes while admitted work finishes.
672 pub quiescing: usize,
673 pub evicting: usize,
674 /// Ownership releases still in flight. A handoff drain waits for zero:
675 /// a released cell leaves `occupied` before its record write commits,
676 /// so exiting on occupancy alone can abort the write mid-flight and
677 /// leave a record the successor waits out the node lease for.
678 pub releasing: usize,
679 /// Released cells waiting for a successor's ownership acknowledgement.
680 /// These hold the shutdown pacing permits.
681 pub adopting: usize,
682 /// Monotonic ownership acknowledgements. A progressing handoff can
683 /// take longer than one stall interval when the node owns many cells.
684 pub handed_off: u64,
685}
686
687#[derive(serde::Deserialize, serde::Serialize)]
688#[serde(rename_all = "camelCase", deny_unknown_fields)]
689pub struct HandoffRequest {
690 pub cell: String,
691 pub released_epoch: u64,
692}
693
694#[derive(serde::Deserialize, serde::Serialize)]
695#[serde(rename_all = "camelCase", deny_unknown_fields)]
696pub struct HandoffResponse {
697 pub node: String,
698 pub addr: String,
699 pub epoch: u64,
700 pub peer_protocol: u16,
701 /// Whether the successor adopted the cell. It repeats what the status code
702 /// reports, and the donor accepts the reply only when the two agree: `200`
703 /// with `true` is an adoption, and `409` with `false` names the current
704 /// owner for the donor to contact instead. Every other pairing is refused,
705 /// so a disagreement between the two cannot be read as a handoff.
706 pub published: bool,
707}
708
709pub struct HandoffAcceptWaiter {
710 released_epoch: u64,
711 reply: oneshot::Sender<AdoptedCell>,
712}
713
714// Read only by the orphaned `worker_route`, and removed with the rest of the
715// landing-cell machinery when that goes.
716#[allow(dead_code)]
717pub struct WorkerRouted {
718 pub request: u64,
719 pub route: Option<WorkerRoute>,
720}
721
722/// Worker requests owned by one HTTP connection. Hyper can finish a failed
723/// connection without dropping its service future, so the connection also
724/// aborts these requests explicitly when its transport ends.
725#[derive(Clone, Default)]
726pub struct ConnectionWorkerRequests(
727 Arc<std::sync::Mutex<Vec<Arc<crate::runtime::RequestCancellationLifetime>>>>,
728);
729
730impl ConnectionWorkerRequests {
731 pub fn register(&self, cancellation: Arc<crate::runtime::RequestCancellationLifetime>) {
732 self.0.lock().unwrap().push(cancellation);
733 }
734
735 pub fn complete(&self, cancellation: &Arc<crate::runtime::RequestCancellationLifetime>) {
736 self.0
737 .lock()
738 .unwrap()
739 .retain(|active| !Arc::ptr_eq(active, cancellation));
740 }
741
742 pub fn abort_all(&self) {
743 let cancellations = std::mem::take(&mut *self.0.lock().unwrap());
744 for cancellation in cancellations {
745 cancellation.publish_abort();
746 }
747 }
748}
749
750pub struct IngressAbortGuard {
751 cancellation: Option<Arc<crate::runtime::RequestCancellationLifetime>>,
752 connection: ConnectionWorkerRequests,
753}
754
755impl IngressAbortGuard {
756 pub fn new(
757 cancellation: Arc<crate::runtime::RequestCancellationLifetime>,
758 connection: ConnectionWorkerRequests,
759 ) -> Self {
760 connection.register(cancellation.clone());
761 Self {
762 cancellation: Some(cancellation),
763 connection,
764 }
765 }
766
767 pub fn disarm(&mut self) {
768 if let Some(cancellation) = self.cancellation.take() {
769 self.connection.complete(&cancellation);
770 }
771 }
772}
773
774/// Cancels a core route when the future awaiting it is dropped. A normal
775/// route disarms the guard before returning its result.
776pub struct RouteCancelGuard {
777 tx: mpsc::UnboundedSender<Message>,
778 request: Option<u64>,
779}
780
781impl RouteCancelGuard {
782 pub fn new(tx: mpsc::UnboundedSender<Message>, request: u64) -> Self {
783 Self {
784 tx,
785 request: Some(request),
786 }
787 }
788
789 pub fn disarm(&mut self) {
790 self.request = None;
791 }
792}
793
794impl Drop for RouteCancelGuard {
795 fn drop(&mut self) {
796 if let Some(request) = self.request {
797 let _ = self.tx.send(Message::CancelRoute { request });
798 }
799 }
800}
801
802impl Drop for IngressAbortGuard {
803 fn drop(&mut self) {
804 if let Some(cancellation) = self.cancellation.take() {
805 self.connection.complete(&cancellation);
806 cancellation.publish_abort();
807 }
808 }
809}
810
811/// One public HTTP request admitted before shutdown closed the gate. Peer
812/// requests do not hold this guard because the handoff must keep serving them.
813pub struct PublicRequestGuard {
814 in_flight: Arc<AtomicUsize>,
815}
816
817impl Drop for PublicRequestGuard {
818 fn drop(&mut self) {
819 self.in_flight.fetch_sub(1, Ordering::SeqCst);
820 }
821}
822
823#[derive(Clone, Default)]
824pub struct DrainPinRegistry(Arc<std::sync::Mutex<DrainPinState>>);
825
826#[derive(Default)]
827struct DrainPinState {
828 pins: BTreeMap<u64, DrainPinTrace>,
829 requests: HashMap<crate::js::RequestId, u64>,
830}
831
832struct DrainPinTrace {
833 request_id: Option<crate::js::RequestId>,
834 origin: &'static str,
835 started_mono_ms: u64,
836 phase: &'static str,
837 response_headers_sent: bool,
838 response_body_active: bool,
839 durable_txid: Option<u64>,
840 output_gate_result: &'static str,
841 ack_point: &'static str,
842 cancellation_state: &'static str,
843 cancel: watch::Sender<bool>,
844}
845
846#[derive(serde::Serialize)]
847#[serde(rename_all = "camelCase")]
848struct DrainPinView {
849 cell: String,
850 core_request_id: Option<u64>,
851 request_id: Option<String>,
852 origin: &'static str,
853 age_ms: u64,
854 phase: &'static str,
855 response_headers_sent: bool,
856 response_body_active: bool,
857 durable_txid: Option<u64>,
858 output_gate_result: &'static str,
859 ack_point: &'static str,
860 active_request_count: usize,
861 output_gate_count: usize,
862 cancellation_state: &'static str,
863 regular_websocket_count: usize,
864 outbound_websocket_count: usize,
865}
866
867impl DrainPinRegistry {
868 fn begin(
869 &self,
870 core_request: u64,
871 request_id: Option<crate::js::RequestId>,
872 origin: &'static str,
873 ) -> watch::Receiver<bool> {
874 let (cancel, receive) = watch::channel(false);
875 let mut state = self.0.lock().unwrap();
876 state.pins.insert(
877 core_request,
878 DrainPinTrace {
879 request_id,
880 origin,
881 started_mono_ms: crate::asyncrt::mono_ms(),
882 phase: "handler",
883 response_headers_sent: false,
884 response_body_active: false,
885 durable_txid: None,
886 output_gate_result: "not_applicable",
887 ack_point: "not_acknowledged",
888 cancellation_state: "not_cancelled",
889 cancel,
890 },
891 );
892 if let Some(request_id) = request_id {
893 state.requests.insert(request_id, core_request);
894 }
895 receive
896 }
897
898 fn update(
899 &self,
900 core_request: u64,
901 phase: &'static str,
902 response_headers_sent: bool,
903 response_body_active: bool,
904 ) {
905 if let Some(pin) = self.0.lock().unwrap().pins.get_mut(&core_request) {
906 pin.phase = phase;
907 pin.response_headers_sent = response_headers_sent;
908 pin.response_body_active = response_body_active;
909 if response_headers_sent {
910 pin.ack_point = "response_headers_sent";
911 }
912 }
913 }
914
915 fn gate_started(&self, core_request: u64, durable_txid: u64) {
916 if let Some(pin) = self.0.lock().unwrap().pins.get_mut(&core_request) {
917 pin.durable_txid = Some(durable_txid);
918 pin.output_gate_result = "pending";
919 }
920 }
921
922 fn gate_finished(&self, core_request: u64, proven: bool) {
923 if let Some(pin) = self.0.lock().unwrap().pins.get_mut(&core_request) {
924 pin.output_gate_result = if proven { "proven" } else { "failed" };
925 }
926 }
927
928 pub fn cancel_request(
929 &self,
930 request_id: crate::js::RequestId,
931 cancellation_state: &'static str,
932 ) -> Option<&'static str> {
933 let mut state = self.0.lock().unwrap();
934 let core_request = state.requests.get(&request_id).copied()?;
935 let pin = state.pins.get_mut(&core_request)?;
936 pin.cancellation_state = cancellation_state;
937 let _ = pin.cancel.send(true);
938 Some(pin.phase)
939 }
940
941 fn cancel_core_request(
942 &self,
943 core_request: u64,
944 cancellation_state: &'static str,
945 ) -> Option<(Option<crate::js::RequestId>, &'static str)> {
946 let mut state = self.0.lock().unwrap();
947 let pin = state.pins.get_mut(&core_request)?;
948 pin.cancellation_state = cancellation_state;
949 let _ = pin.cancel.send(true);
950 Some((pin.request_id, pin.phase))
951 }
952
953 fn finish(&self, core_request: u64) -> Option<DrainPinTrace> {
954 let mut state = self.0.lock().unwrap();
955 let pin = state.pins.remove(&core_request)?;
956 if let Some(request_id) = pin.request_id {
957 state.requests.remove(&request_id);
958 }
959 Some(pin)
960 }
961
962 fn snapshot(&self, pins: Vec<celld_logic::DrainPin>) -> Vec<DrainPinView> {
963 let state = self.0.lock().unwrap();
964 pins.into_iter()
965 .map(|pin| {
966 let trace = pin.request.and_then(|request| state.pins.get(&request));
967 DrainPinView {
968 cell: pin.cell,
969 core_request_id: pin.request,
970 request_id: trace
971 .and_then(|trace| trace.request_id)
972 .map(crate::js::request_id_string),
973 origin: trace.map_or("unknown", |trace| trace.origin),
974 age_ms: trace.map_or(0, |trace| {
975 crate::asyncrt::mono_ms().saturating_sub(trace.started_mono_ms)
976 }),
977 phase: trace.map_or("unknown", |trace| trace.phase),
978 response_headers_sent: trace.is_some_and(|trace| trace.response_headers_sent),
979 response_body_active: trace.is_some_and(|trace| trace.response_body_active),
980 durable_txid: trace.and_then(|trace| trace.durable_txid),
981 output_gate_result: trace.map_or("unknown", |trace| trace.output_gate_result),
982 ack_point: trace.map_or("unknown", |trace| trace.ack_point),
983 active_request_count: pin.active_request_count,
984 output_gate_count: pin.output_gate_count,
985 cancellation_state: trace.map_or("unknown", |trace| trace.cancellation_state),
986 regular_websocket_count: pin.regular_websocket_count,
987 outbound_websocket_count: pin.outbound_websocket_count,
988 }
989 })
990 .collect()
991 }
992}
993
994pub struct ActivityGuard {
995 tx: mpsc::UnboundedSender<Message>,
996 request: u64,
997 host: Option<CellHost>,
998 cell: String,
999 drain_pins: DrainPinRegistry,
1000 cancellation: watch::Receiver<bool>,
1001}
1002
1003impl ActivityGuard {
1004 pub fn set_phase(
1005 &self,
1006 phase: &'static str,
1007 response_headers_sent: bool,
1008 response_body_active: bool,
1009 ) {
1010 self.drain_pins.update(
1011 self.request,
1012 phase,
1013 response_headers_sent,
1014 response_body_active,
1015 );
1016 }
1017
1018 pub fn cancellation(&self) -> watch::Receiver<bool> {
1019 self.cancellation.clone()
1020 }
1021
1022 pub fn gate_started(&self, durable_txid: u64) {
1023 self.drain_pins.gate_started(self.request, durable_txid);
1024 }
1025
1026 pub fn gate_finished(&self, proven: bool) {
1027 self.drain_pins.gate_finished(self.request, proven);
1028 }
1029}
1030
1031impl Drop for ActivityGuard {
1032 fn drop(&mut self) {
1033 if let Some(pin) = self.drain_pins.finish(self.request) {
1034 if let Some(request_id) = pin
1035 .request_id
1036 .filter(|_| tracing::enabled!(target: "timing", tracing::Level::DEBUG))
1037 {
1038 tracing::debug!(
1039 target: "timing",
1040 event = "cell_request_lifecycle",
1041 core_request_id = self.request,
1042 request_id = %crate::js::request_id_string(request_id),
1043 scope = %self.cell,
1044 origin = pin.origin,
1045 age_ms = crate::asyncrt::mono_ms().saturating_sub(pin.started_mono_ms),
1046 phase = pin.phase,
1047 response_headers_sent = pin.response_headers_sent,
1048 response_body_active = pin.response_body_active,
1049 durable_txid = pin.durable_txid,
1050 output_gate_result = pin.output_gate_result,
1051 ack_point = pin.ack_point,
1052 cancellation_state = pin.cancellation_state,
1053 "cell request lifetime ended"
1054 );
1055 }
1056 }
1057 // Read and send under the registry lock (`with_alarm`), so this
1058 // report cannot carry an alarm older than one the reporter already
1059 // sent — a stale fold arriving later would unarm the core and
1060 // delete the wake entry (`alarm_reporter` documents the ordering).
1061 // The cache also retains the source revision: this notification can
1062 // still wait in the mailbox while an admitted handler arms the cell.
1063 let send = |tx: &mpsc::UnboundedSender<Message>, alarm, covered| {
1064 let _ = tx.send(Message::ActivityFinished {
1065 request: self.request,
1066 cell: self.cell.clone(),
1067 alarm,
1068 alarm_covered: covered,
1069 });
1070 };
1071 match &self.host {
1072 Some(host) => host.with_alarm(&self.cell, |alarm, covered| {
1073 send(&self.tx, alarm, covered);
1074 }),
1075 None => send(
1076 &self.tx,
1077 celld_logic::wake::AlarmSnapshot::without_wake(None),
1078 false,
1079 ),
1080 }
1081 }
1082}
1083
1084#[derive(Clone, Copy)]
1085enum RouteStage {
1086 OwnershipRead,
1087 NodeLeaseLookup,
1088 CapacityLookup,
1089 OwnershipAcquire,
1090 Restore,
1091 IsolateStartup,
1092 RegistryInsert,
1093}
1094
1095struct EffectTiming {
1096 cell: String,
1097 stage: RouteStage,
1098 elapsed_us: u64,
1099}
1100
1101pub struct CompletedEffect {
1102 event: Event,
1103 timing: Option<EffectTiming>,
1104}
1105
1106impl CompletedEffect {
1107 fn plain(event: Event) -> Self {
1108 Self {
1109 event,
1110 timing: None,
1111 }
1112 }
1113
1114 fn timed(event: Event, cell: String, stage: RouteStage, started_mono_ms: u64) -> Self {
1115 Self {
1116 event,
1117 timing: Some(EffectTiming {
1118 cell,
1119 stage,
1120 elapsed_us: mono_elapsed_us(started_mono_ms),
1121 }),
1122 }
1123 }
1124}
1125
1126struct CellRouteTiming {
1127 started_mono_ms: u64,
1128 activation_started: bool,
1129 capacity_wait_started_mono_ms: Option<u64>,
1130 latch_wait_us: u64,
1131 ownership_read_us: u64,
1132 node_lease_lookup_us: u64,
1133 capacity_lookup_us: u64,
1134 capacity_wait_us: u64,
1135 activation_slot_wait_us: u64,
1136 lease_permit_us: u64,
1137 ownership_acquire_us: u64,
1138 replica_discovery_us: u64,
1139 restore_us: u64,
1140 isolate_startup_us: u64,
1141 registry_insert_us: u64,
1142 fresh: Option<bool>,
1143}
1144
1145impl CellRouteTiming {
1146 fn new() -> Self {
1147 Self {
1148 started_mono_ms: crate::asyncrt::mono_ms(),
1149 activation_started: false,
1150 capacity_wait_started_mono_ms: None,
1151 latch_wait_us: 0,
1152 ownership_read_us: 0,
1153 node_lease_lookup_us: 0,
1154 capacity_lookup_us: 0,
1155 capacity_wait_us: 0,
1156 activation_slot_wait_us: 0,
1157 lease_permit_us: 0,
1158 ownership_acquire_us: 0,
1159 replica_discovery_us: 0,
1160 restore_us: 0,
1161 isolate_startup_us: 0,
1162 registry_insert_us: 0,
1163 fresh: None,
1164 }
1165 }
1166
1167 fn effect_started(&mut self) {
1168 if !self.activation_started {
1169 self.activation_started = true;
1170 self.activation_slot_wait_us = mono_elapsed_us(self.started_mono_ms);
1171 }
1172 if let Some(started) = self.capacity_wait_started_mono_ms.take() {
1173 self.capacity_wait_us = self
1174 .capacity_wait_us
1175 .saturating_add(mono_elapsed_us(started));
1176 }
1177 }
1178
1179 fn record(&mut self, stage: RouteStage, elapsed_us: u64) {
1180 let field = match stage {
1181 RouteStage::OwnershipRead => &mut self.ownership_read_us,
1182 RouteStage::NodeLeaseLookup => &mut self.node_lease_lookup_us,
1183 RouteStage::CapacityLookup => &mut self.capacity_lookup_us,
1184 RouteStage::OwnershipAcquire => &mut self.ownership_acquire_us,
1185 RouteStage::Restore => &mut self.restore_us,
1186 RouteStage::IsolateStartup => &mut self.isolate_startup_us,
1187 RouteStage::RegistryInsert => &mut self.registry_insert_us,
1188 };
1189 *field = field.saturating_add(elapsed_us);
1190 }
1191}
1192
1193/// Report a cell's runtime stopped, but only once the host has actually let
1194/// the cell go.
1195///
1196/// A stop that failed can leave the cell's realm holding its open database,
1197/// so reporting it stopped is what makes that dangerous: the core answers a
1198/// stop by starting the cell again — on the current application generation
1199/// for a swap, or on another node after a handoff — against storage the old
1200/// realm may still have. Both stop paths therefore retry rather than report,
1201/// and they share this loop so neither can drift into reporting first.
1202///
1203/// A bounded eviction checks its retry deadline after a release returns an
1204/// error. Neither this await nor the core's `Cleaning` phase has an overall
1205/// timeout. A pending release must not trigger a restart against a database
1206/// that the old runtime can still own; it can keep the eviction reply pending.
1207async fn report_stopped_when_released<F, Fut>(
1208 op: OpId,
1209 cell: String,
1210 epoch: u64,
1211 event: &'static str,
1212 deadline_mono_ms: Option<u64>,
1213 mut release: F,
1214) -> CompletedEffect
1215where
1216 F: FnMut() -> Fut,
1217 Fut: std::future::Future<Output = anyhow::Result<()>>,
1218{
1219 while let Err(error) = release().await {
1220 // An abandoned eviction is the one failure that must not be retried.
1221 // The cell is resident at its own epoch with a request waiting on it,
1222 // and a retry would take the cell the abandonment just gave back.
1223 // The core restarts both outcomes in place, but callers must be able
1224 // to distinguish this cancellation from an execution failure.
1225 if let Some(abandoned) = error.downcast_ref::<crate::replication::EvictionAbandoned>() {
1226 tracing::info!(
1227 event,
1228 %cell,
1229 epoch,
1230 reason = %abandoned,
1231 "a request reached the cell before the eviction took it; restarting it in place"
1232 );
1233 return CompletedEffect::plain(Event::RuntimeStopCancelled { op });
1234 }
1235 if deadline_mono_ms.is_some_and(|deadline| crate::asyncrt::mono_ms() >= deadline) {
1236 tracing::warn!(
1237 event,
1238 %cell,
1239 epoch,
1240 %error,
1241 "the host did not release the cell before the deadline; restarting it in place"
1242 );
1243 return CompletedEffect::plain(Event::RuntimeStopFailed { op });
1244 }
1245 tracing::warn!(
1246 event,
1247 %cell,
1248 epoch,
1249 %error,
1250 "the host did not release the cell; retrying before reporting it stopped"
1251 );
1252 crate::asyncrt::sleep(std::time::Duration::from_millis(
1253 crate::replication::CELL_RELEASE_RETRY_BASE_MS,
1254 ))
1255 .await;
1256 }
1257 CompletedEffect::plain(Event::RuntimeStopped { op })
1258}
1259
1260fn mono_elapsed_us(started_mono_ms: u64) -> u64 {
1261 crate::asyncrt::mono_ms()
1262 .saturating_sub(started_mono_ms)
1263 .saturating_mul(1_000)
1264}
1265
1266pub type EffectFuture = Pin<Box<dyn Future<Output = CompletedEffect> + Send>>;
1267pub type ConnectionFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
1268pub type DoCallFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
1269pub type AssetCallFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
1270pub type WebSocketFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
1271pub type CachePruneFuture = Pin<
1272 Box<
1273 dyn Future<
1274 Output = (
1275 u64,
1276 Result<std::io::Result<(usize, usize, u64)>, crate::asyncrt::TaskPanic>,
1277 ),
1278 > + Send,
1279 >,
1280>;
1281
1282/// One ready item selected for the serial Actor.
1283pub enum ActorInput {
1284 Message(Message),
1285 Completed(CompletedEffect),
1286 TimerFired(Timer),
1287}
1288
1289/// The largest request body that a node accepts unless the operator lowers
1290/// the limit. The value keeps the large git-pack ingress use case supported.
1291pub const DEFAULT_MAX_REQUEST_BODY_BYTES: usize = 1 << 30;
1292
1293/// The generation census `/state` reports beside the serving deployment.
1294pub struct SwapCensus {
1295 /// Resident cells moving to the current generation right now.
1296 pub swapping: usize,
1297 /// Each resident cell and the generation its runtime started on.
1298 pub generations: Vec<(String, u64)>,
1299}
1300
1301#[derive(Clone)]
1302pub struct AppHandle {
1303 pub tx: mpsc::UnboundedSender<Message>,
1304 pub runtime: Option<RuntimeManager>,
1305 #[cfg(all(test, celld_internal_tests))]
1306 pub(crate) scripted_activity_host: Option<crate::conformance_sim_cell_host::SimCellHost>,
1307 /// Asks the pointer watcher to adopt the current deployment now. Sending
1308 /// fails on a node with no pointer to watch, such as a local-script node.
1309 pub reload: crate::generation::ReloadSender,
1310 pub peer_http: reqwest::Client,
1311 pub peer_auth: Arc<PeerAuth>,
1312 pub advertise: String,
1313 pub websockets: mpsc::UnboundedSender<WebSocketFuture>,
1314 /// Concurrent outbound WebSockets one cell may hold, for the refusal
1315 /// message; the core enforces it.
1316 pub max_outbound_websockets: usize,
1317 /// Set the instant a graceful shutdown begins, so `/.well-known/celld/health` reports
1318 /// unhealthy and a load balancer stops routing here before teardown.
1319 pub draining: Arc<std::sync::atomic::AtomicBool>,
1320 /// The one-shot fleet gate on the first health 200. A fresh process
1321 /// reports ready only after no peer donor is mid-handoff and the fleet has
1322 /// successor capacity, so a rolling update cannot advance faster than the
1323 /// fleet recovers. Fleet state never demotes readiness after the gate
1324 /// opens; peers reach owned cells directly regardless.
1325 pub fleet_ready: Arc<std::sync::atomic::AtomicBool>,
1326 /// Public requests which passed the shutdown gate and have not finished.
1327 /// This includes the complete top-level Worker call, so a cell write it
1328 /// goes on to make cannot outlive the pre-handoff durability boundary.
1329 pub public_in_flight: Arc<AtomicUsize>,
1330 /// Shell-side phases joined to the decision core's exact eviction pins.
1331 pub drain_pins: DrainPinRegistry,
1332 /// The log tier's follower store: this node holds peers' log fragments
1333 /// whatever its own durability posture. `None` without a bucket.
1334 pub follower: Option<Arc<crate::node_log::FollowerStore>>,
1335 /// Whether forwarded scheme and host headers can set `request.url`.
1336 /// The default is false because a direct client controls both headers.
1337 pub trust_forwarded_headers: bool,
1338 /// The maximum body size for public Worker ingress and direct Durable
1339 /// Object ingress. The same value must govern both entry points because a
1340 /// caller can choose either route for an ordinary Durable Object.
1341 pub max_request_body_bytes: usize,
1342 /// The complete retry budget for a contradicted remote ownership
1343 /// generation. This is the same operation deadline that bounds the
1344 /// decision core, so a shell retry cannot outlive its core operation.
1345 pub operation_deadline_ms: u64,
1346}
1347
1348impl AppHandle {
1349 pub async fn request(&self, cell: String) -> Result<Routed, RequestError> {
1350 self.request_with_mode(cell, false, None).await
1351 }
1352
1353 /// Route the output gate for an effect raised inside one of `cell`'s
1354 /// handlers. See `ResidentWork::OutputGate`.
1355 pub async fn gate_request(&self, cell: String) -> Result<Routed, RequestError> {
1356 self.request_with_mode(cell, false, Some(ResidentWork::OutputGate))
1357 .await
1358 }
1359
1360 /// Route one test request and retain which asynchronous seam produced the
1361 /// result. The shipping method keeps its compact public result, while this
1362 /// receipt prevents an inference from `NodeFenced` or an error string.
1363 #[cfg(all(test, celld_internal_tests))]
1364 pub(crate) async fn request_with_receipt_for_test(
1365 &self,
1366 cell: String,
1367 ) -> RequestPathReceiptForTest {
1368 let (request, outcome) = self.request_path(cell, false, None).await;
1369 match outcome {
1370 RequestPathOutcome::SubmissionFailure => {
1371 RequestPathReceiptForTest::SubmissionFailure { request }
1372 }
1373 RequestPathOutcome::ReplyChannelClosed => {
1374 RequestPathReceiptForTest::ReplyChannelClosed { request }
1375 }
1376 RequestPathOutcome::Returned(result) => RequestPathReceiptForTest::Returned {
1377 allocated_request: request,
1378 result: result.map(|routed| (routed.request, routed.route)),
1379 },
1380 }
1381 }
1382
1383 pub async fn capacity_request(&self, cell: String) -> Result<Routed, RequestError> {
1384 self.request_with_mode(cell, true, None).await
1385 }
1386
1387 pub async fn websocket_request(
1388 &self,
1389 cell: String,
1390 websocket: u64,
1391 ) -> Result<Routed, RequestError> {
1392 self.request_with_mode(cell, false, Some(ResidentWork::WebSocket(websocket)))
1393 .await
1394 }
1395
1396 async fn request_with_mode(
1397 &self,
1398 cell: String,
1399 capacity_handoff: bool,
1400 resident_work: Option<ResidentWork>,
1401 ) -> Result<Routed, RequestError> {
1402 match self
1403 .request_path(cell, capacity_handoff, resident_work)
1404 .await
1405 .1
1406 {
1407 RequestPathOutcome::Returned(result) => result,
1408 RequestPathOutcome::SubmissionFailure | RequestPathOutcome::ReplyChannelClosed => {
1409 Err(RequestError::NodeFenced)
1410 }
1411 }
1412 }
1413
1414 async fn request_path(
1415 &self,
1416 cell: String,
1417 capacity_handoff: bool,
1418 resident_work: Option<ResidentWork>,
1419 ) -> (u64, RequestPathOutcome) {
1420 let request = crate::asyncrt::next_core_request();
1421 let (reply, receive) = oneshot::channel();
1422 if self
1423 .tx
1424 .send(Message::Request {
1425 request,
1426 cell,
1427 capacity_handoff,
1428 handoff_accept: None,
1429 resident_work,
1430 reply,
1431 })
1432 .is_err()
1433 {
1434 return (request, RequestPathOutcome::SubmissionFailure);
1435 }
1436 let mut cancel = RouteCancelGuard::new(self.tx.clone(), request);
1437 let outcome = match receive.await {
1438 Ok(result) => RequestPathOutcome::Returned(result),
1439 Err(_) => RequestPathOutcome::ReplyChannelClosed,
1440 };
1441 cancel.disarm();
1442 (request, outcome)
1443 }
1444
1445 /// Acquire a released cell without materializing its runtime. The donor's
1446 /// final snapshot makes a later demand-driven restore authoritative, and
1447 /// avoiding an eager restore keeps a fleet restart from becoming a cold
1448 /// start storm.
1449 pub async fn accept_handoff(
1450 &self,
1451 cell: String,
1452 released_epoch: u64,
1453 ) -> Result<HandoffAttempt, RequestError> {
1454 let request = crate::asyncrt::next_core_request();
1455 let (route_reply, mut route_receive) = oneshot::channel();
1456 let (accept_reply, mut accept_receive) = oneshot::channel();
1457 if self
1458 .tx
1459 .send(Message::Request {
1460 request,
1461 cell: cell.clone(),
1462 capacity_handoff: true,
1463 handoff_accept: Some(HandoffAcceptWaiter {
1464 released_epoch,
1465 reply: accept_reply,
1466 }),
1467 resident_work: None,
1468 reply: route_reply,
1469 })
1470 .is_err()
1471 {
1472 return Err(RequestError::NodeFenced);
1473 }
1474 let mut cancel = RouteCancelGuard::new(self.tx.clone(), request);
1475 let result = crate::asyncrt::select_biased! {
1476 "a completed route wins a tie so current ownership precedes the accept acknowledgement";
1477 routed = &mut route_receive => match routed
1478 .unwrap_or(Err(RequestError::NodeFenced))?
1479 {
1480 Routed {
1481 request,
1482 route: Route::Local,
1483 } => {
1484 // A repeated request can find the cell published already.
1485 drop(self.activity(request, cell.clone()));
1486 self.resident_epoch(cell)
1487 .await
1488 .filter(|epoch| *epoch > released_epoch)
1489 .map(|epoch| HandoffAttempt::Accepted(AdoptedCell {
1490 node: self.peer_auth.source().to_string(),
1491 addr: self.advertise.clone(),
1492 epoch,
1493 peer_protocol: peer_auth::PROTOCOL_VERSION,
1494 }))
1495 .ok_or(RequestError::AcquireFailed)
1496 }
1497 Routed {
1498 route: Route::Remote {
1499 node,
1500 addr,
1501 epoch,
1502 peer_protocol,
1503 },
1504 ..
1505 } => Ok(HandoffAttempt::CurrentOwner(AdoptedCell {
1506 node,
1507 addr,
1508 epoch,
1509 peer_protocol,
1510 })),
1511 },
1512 accepted = &mut accept_receive => accepted
1513 .map(HandoffAttempt::Accepted)
1514 .map_err(|_| RequestError::NodeFenced),
1515 };
1516 // The ownership acknowledgement deliberately leaves no route waiter:
1517 // real traffic, not this synthetic request, starts materialization.
1518 cancel.disarm();
1519 let _ = self.tx.send(Message::CancelRoute { request });
1520 result
1521 }
1522
1523 // Orphaned by the always-pool Worker entry below. What remains of the
1524 // landing-cell machinery -- this, `Message::WorkerRequest`, `WorkerRouted`,
1525 // `fetch_worker_on_cell`, `CellJob::WorkerFetch`, and the logic
1526 // `worker_request` -- is kept together so it can be removed in one piece
1527 // rather than unpicked here. The in-isolate dispatch it was paired with is
1528 // already gone, and with it the gate that path needed.
1529 #[allow(dead_code)]
1530 async fn worker_route(&self) -> anyhow::Result<WorkerRouted> {
1531 let (reply, receive) = oneshot::channel();
1532 self.tx
1533 .send(Message::WorkerRequest { reply })
1534 .map_err(|_| anyhow::anyhow!("core stopped before Worker routing"))?;
1535 receive
1536 .await
1537 .context("core stopped while routing Worker request")
1538 }
1539
1540 pub async fn fetch_worker(
1541 &self,
1542 url: String,
1543 method: String,
1544 body: crate::js::RequestBody,
1545 headers: Vec<(String, String)>,
1546 connection: ConnectionWorkerRequests,
1547 ) -> anyhow::Result<HttpResponse> {
1548 let runtime = self
1549 .runtime
1550 .as_ref()
1551 .ok_or_else(|| anyhow::anyhow!("Worker runtime unavailable"))?;
1552 // Admission happens in the runtime, against the pool that actually
1553 // holds the requests. It used to be duplicated here against an empty
1554 // `PoolLoad` — a snapshot with no isolates and no affiliations, which
1555 // could only ever answer "yes" once pressure stopped refusing
1556 // outright. A decision made against a fake reading is not a fast path.
1557 let cancellation = crate::runtime::RequestCancellationLifetime::stateless();
1558 // The Worker entry is stateless — run it in the pool, always. Routing it
1559 // to a "landing cell" existed only to make an `env.NS.get(id)` call
1560 // resolve inline; but a cell runs one fetch at a time, so under any real
1561 // concurrency the entry can't be on the cell it calls, and the routing
1562 // round-trip is paid for nothing — on top of the DO call's own routing.
1563 // A DO call reaches its owning cell (with fencing and the output gate) on
1564 // the host path, so one routing round-trip per request, never two.
1565 let fetching = runtime.fetch_worker_pool(url, method, body, headers, cancellation.clone());
1566 let mut abort = IngressAbortGuard::new(cancellation, connection);
1567 let result = fetching.await;
1568 abort.disarm();
1569 result
1570 }
1571
1572 pub(crate) fn execution_host(&self) -> Option<CellHost> {
1573 let host = self.runtime.clone().map(CellHost::Engine);
1574 #[cfg(all(test, celld_internal_tests))]
1575 let host = host.or_else(|| self.scripted_activity_host.clone().map(CellHost::Scripted));
1576 host
1577 }
1578
1579 pub fn activity(&self, request: u64, cell: String) -> ActivityGuard {
1580 self.activity_for(request, cell, None, "local")
1581 }
1582
1583 pub fn activity_for(
1584 &self,
1585 request: u64,
1586 cell: String,
1587 request_id: Option<crate::js::RequestId>,
1588 origin: &'static str,
1589 ) -> ActivityGuard {
1590 let cancellation = self.drain_pins.begin(request, request_id, origin);
1591 let host = self.execution_host();
1592 ActivityGuard {
1593 tx: self.tx.clone(),
1594 request,
1595 host,
1596 cell,
1597 drain_pins: self.drain_pins.clone(),
1598 cancellation,
1599 }
1600 }
1601
1602 /// Hold a response until every write it can reveal is durable. A write
1603 /// supplies its ending position. A read supplies `None` and trails the
1604 /// newest outstanding write on the same cell, if one exists. A ticket
1605 /// whose position was sampled before `request` pinned the cell supplies
1606 /// the epoch it sampled at, and the core refuses it when the cell has
1607 /// since moved to another epoch.
1608 pub async fn gate_output(&self, request: u64, ticket: GateTicket) -> Result<(), RequestError> {
1609 match self.gate_output_path(request, ticket).await {
1610 OutputGateOutcome::Returned(result) => result,
1611 OutputGateOutcome::SubmissionFailure | OutputGateOutcome::ReplyChannelClosed => {
1612 Err(RequestError::NodeFenced)
1613 }
1614 }
1615 }
1616
1617 async fn gate_output_path(&self, request: u64, ticket: GateTicket) -> OutputGateOutcome {
1618 let started_mono_ms = crate::asyncrt::mono_ms();
1619 let (reply, receive) = oneshot::channel();
1620 if self
1621 .tx
1622 .send(Message::Output {
1623 request,
1624 ticket,
1625 reply,
1626 })
1627 .is_err()
1628 {
1629 return OutputGateOutcome::SubmissionFailure;
1630 }
1631 let outcome = match receive.await {
1632 Ok(result) => OutputGateOutcome::Returned(result),
1633 Err(_) => OutputGateOutcome::ReplyChannelClosed,
1634 };
1635 tracing::debug!(
1636 target: "timing",
1637 event = "gate_write_timing",
1638 request,
1639 total_us = mono_elapsed_us(started_mono_ms),
1640 "output gate resolved"
1641 );
1642 outcome
1643 }
1644
1645 /// Run one test output gate without collapsing its two channel failures
1646 /// into a returned engine rejection. The request travels in every arm, so
1647 /// a consumer cannot attach the receipt to another caller.
1648 #[cfg(all(test, celld_internal_tests))]
1649 pub(crate) async fn gate_output_with_receipt_for_test(
1650 &self,
1651 request: u64,
1652 ticket: GateTicket,
1653 ) -> OutputGateReceiptForTest {
1654 match self.gate_output_path(request, ticket).await {
1655 OutputGateOutcome::SubmissionFailure => {
1656 OutputGateReceiptForTest::SubmissionFailure { request }
1657 }
1658 OutputGateOutcome::ReplyChannelClosed => {
1659 OutputGateReceiptForTest::ReplyChannelClosed { request }
1660 }
1661 OutputGateOutcome::Returned(result) => {
1662 OutputGateReceiptForTest::Returned { request, result }
1663 }
1664 }
1665 }
1666
1667 pub async fn gate_write(&self, request: u64, position: u64) -> Result<(), RequestError> {
1668 self.gate_output(request, GateTicket::response(Some(position), None))
1669 .await
1670 }
1671
1672 /// Hand a finished `webSocketMessage`'s frames to the cell's output gate.
1673 /// Awaited so the request stays pinned until the actor has registered the
1674 /// gate (the core reads the still-active request when it opens); frames flush
1675 /// or fail asynchronously as durability resolves, not here.
1676 ///
1677 /// An error means the actor has stopped and registered nothing: no
1678 /// barrier opened, so a caller that relied on one for an unproven write
1679 /// must not treat the write as covered.
1680 pub async fn ws_output(
1681 &self,
1682 request: u64,
1683 scope: String,
1684 frames: impl Into<WsBatch>,
1685 write_position: Option<u64>,
1686 observed: Option<u64>,
1687 ) -> Result<(), ActorStopped> {
1688 let (reply, receive) = oneshot::channel();
1689 self.tx
1690 .send(Message::WsOutput {
1691 request,
1692 scope,
1693 frames: frames.into(),
1694 write_position,
1695 observed,
1696 reply,
1697 })
1698 .map_err(|_| ActorStopped)?;
1699 receive.await.map_err(|_| ActorStopped)
1700 }
1701
1702 pub async fn websocket_opened(
1703 &self,
1704 cell: String,
1705 websocket: u64,
1706 kind: WebSocketKind,
1707 ) -> anyhow::Result<()> {
1708 let (reply, receive) = oneshot::channel();
1709 self.tx
1710 .send(Message::WebSocketOpened {
1711 cell,
1712 websocket,
1713 kind,
1714 reply,
1715 })
1716 .map_err(|_| anyhow::anyhow!("core stopped before WebSocket opened"))?;
1717 let held = receive
1718 .await
1719 .context("core stopped while opening WebSocket")?;
1720 anyhow::ensure!(
1721 held,
1722 "outbound WebSocket refused: the cell is leaving this node, or a cell \
1723 may hold at most {} and a node may pin at most {}% of its residency \
1724 ceiling",
1725 self.max_outbound_websockets,
1726 celld_logic::pressure::MAX_OUTBOUND_PIN_PERCENT,
1727 );
1728 Ok(())
1729 }
1730
1731 pub fn websocket_closed(&self, cell: String, websocket: u64) {
1732 let _ = self.tx.send(Message::WebSocketClosed { cell, websocket });
1733 }
1734
1735 /// Try eviction now, or join the eviction already running on this node.
1736 /// Success confirms that operation or settled local absence; later demand
1737 /// can activate the cell again before the caller receives the reply.
1738 pub async fn evict(&self, cell: CellId) -> Result<EvictSuccess, EvictError> {
1739 let (reply, receive) = oneshot::channel();
1740 self.tx
1741 .send(Message::Evict { cell, reply })
1742 .map_err(|_| EvictError::Failed(EvictFailure::ActorUnavailable))?;
1743 receive
1744 .await
1745 .map_err(|_| EvictError::Failed(EvictFailure::ReplyLost))?
1746 }
1747
1748 pub async fn invalidate_remote(&self, cell: String, node: String, epoch: u64) {
1749 let (reply, receive) = oneshot::channel();
1750 if self
1751 .tx
1752 .send(Message::InvalidateRemote {
1753 cell,
1754 node,
1755 epoch,
1756 reply,
1757 })
1758 .is_ok()
1759 {
1760 let _ = receive.await;
1761 }
1762 }
1763
1764 pub async fn snapshot(&self) -> String {
1765 let (reply, receive) = oneshot::channel();
1766 if self.tx.send(Message::Snapshot { reply }).is_err() {
1767 return "{\"error\":\"actor_stopped\"}".into();
1768 }
1769 let Ok((state, pins, census)) = receive.await else {
1770 return "{\"error\":\"actor_stopped\"}".into();
1771 };
1772 let pins = self.drain_pins.snapshot(pins);
1773 let Ok(mut state) = serde_json::from_str::<serde_json::Value>(&state) else {
1774 return state;
1775 };
1776 if !pins.is_empty() {
1777 state["drainPins"] =
1778 serde_json::to_value(pins).unwrap_or_else(|_| serde_json::json!([]));
1779 }
1780 // Which deployment this node serves, and which ones it is still
1781 // draining. Nothing else in the process records the version, so
1782 // this is how an operator learns whether a deploy took.
1783 if let Some(runtime) = &self.runtime {
1784 let generation = runtime.generation();
1785 state["deployment"] = serde_json::json!({
1786 "version": generation.version(),
1787 "prefix": generation.prefix(),
1788 "generation": generation.id(),
1789 "draining": runtime
1790 .draining_generations()
1791 .into_iter()
1792 .map(|generation| {
1793 serde_json::json!({
1794 "generation": generation.id(),
1795 "version": generation.version(),
1796 "isolates": generation.isolate_census(),
1797 })
1798 })
1799 .collect::<Vec<_>>(),
1800 // The V8 heaps behind the counters above. A dormant cell
1801 // keeps no isolate of its own, so a cell pool whose
1802 // `live_empty` persists across maintenance passes, or whose
1803 // `retiring` never frees, is memory the node holds for
1804 // nothing -- the residual GCE measured at about 160 KB per
1805 // hibernated cell (measured 2026-09-03).
1806 "isolates": generation.isolate_census(),
1807 // Resident cells moving to the current generation right now,
1808 // and the generation each resident cell runs: the two numbers
1809 // an operator watches while a deployment converges.
1810 "swapping": census.swapping,
1811 "cells": census
1812 .generations
1813 .into_iter()
1814 .map(|(cell, generation)| (cell, serde_json::Value::from(generation)))
1815 .collect::<serde_json::Map<_, _>>(),
1816 });
1817 }
1818 state.to_string()
1819 }
1820
1821 pub fn is_draining(&self) -> bool {
1822 self.draining.load(std::sync::atomic::Ordering::Relaxed)
1823 }
1824
1825 pub fn fleet_ready(&self) -> bool {
1826 self.fleet_ready.load(std::sync::atomic::Ordering::Relaxed)
1827 }
1828
1829 /// Atomically cross the public shutdown gate. The second draining read
1830 /// closes the race where shutdown stores the flag between the first read
1831 /// and the counter increment: that request backs out before user code runs.
1832 pub fn admit_public(&self) -> Option<PublicRequestGuard> {
1833 if self.draining.load(Ordering::SeqCst) {
1834 return None;
1835 }
1836 self.public_in_flight.fetch_add(1, Ordering::SeqCst);
1837 if self.draining.load(Ordering::SeqCst) {
1838 self.public_in_flight.fetch_sub(1, Ordering::SeqCst);
1839 return None;
1840 }
1841 Some(PublicRequestGuard {
1842 in_flight: self.public_in_flight.clone(),
1843 })
1844 }
1845
1846 pub fn public_in_flight(&self) -> usize {
1847 self.public_in_flight.load(Ordering::SeqCst)
1848 }
1849
1850 /// A dead actor has nothing left to hand off, so channel failure
1851 /// reports drained rather than wedging shutdown.
1852 pub async fn drain_status(&self) -> DrainStatus {
1853 let (reply, receive) = oneshot::channel();
1854 if self.tx.send(Message::Drained { reply }).is_err() {
1855 return DrainStatus::default();
1856 }
1857 receive.await.unwrap_or_default()
1858 }
1859
1860 pub async fn healthy(&self) -> bool {
1861 let (reply, receive) = oneshot::channel();
1862 if self.tx.send(Message::Health { reply }).is_err() {
1863 return false;
1864 }
1865 receive.await.unwrap_or(false)
1866 }
1867
1868 pub async fn presence(&self) -> Option<celld_logic::PresenceSnapshot> {
1869 let (reply, receive) = oneshot::channel();
1870 self.tx.send(Message::Presence { reply }).ok()?;
1871 receive.await.ok()
1872 }
1873
1874 async fn resident_epoch(&self, cell: String) -> Option<u64> {
1875 let (reply, receive) = oneshot::channel();
1876 self.tx.send(Message::ResidentEpoch { cell, reply }).ok()?;
1877 receive.await.ok().flatten()
1878 }
1879}
1880
1881/// One cell's WebSocket output gate: an ordered queue of write barriers.
1882#[derive(Default)]
1883struct WsGate {
1884 barriers: VecDeque<WsBarrier>,
1885}
1886
1887/// One `webSocketMessage` batch and the outbound frames held behind it.
1888/// `settled` is `None` while the verdict is outstanding, `Some(true)` once the
1889/// core proved every write the frames can reveal (they may flush when this
1890/// barrier reaches the front), `Some(false)` on failure (the gate breaks).
1891///
1892/// Every batch gets its own barrier, including one that wrote nothing: the core
1893/// decides what it trails, because only the core knows the writes other
1894/// channels have outstanding on this cell. The queue keeps them in arrival
1895/// order and drains only from the front, so a barrier settled early cannot
1896/// overtake one still waiting.
1897struct WsBarrier {
1898 request: u64,
1899 settled: Option<bool>,
1900 frames: WsBatch,
1901}
1902
1903/// The actor stopped before it answered: its channel is closed, and nothing
1904/// it was asked to register exists.
1905#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1906pub struct ActorStopped;
1907
1908impl std::fmt::Display for ActorStopped {
1909 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1910 f.write_str("the cell actor stopped before it registered the output")
1911 }
1912}
1913
1914impl std::error::Error for ActorStopped {}
1915
1916/// What one output-gate ticket asks: the route it holds, the committed-write
1917/// position it must see proven, and the activation epoch that position was
1918/// sampled at.
1919///
1920/// One value rather than three arguments, because a position without its
1921/// epoch is a ticket a reset can satisfy at the wrong epoch (see
1922/// `Event::Output`): the routed path samples in the handler's turn and only
1923/// then acquires the request that pins the cell, and a caller that could pass
1924/// the position alone would drop the epoch without the compiler noticing.
1925#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1926pub struct GateTicket {
1927 pub channel: Channel,
1928 pub position: Option<u64>,
1929 /// The committed-write position a read-only output observed above the
1930 /// cell's published baseline, when a handler had advanced it. The core
1931 /// holds the output until a verified proof covers it, whether or not the
1932 /// handler that wrote has taken a ticket yet. Read only when `position`
1933 /// is `None`.
1934 pub observed: Option<u64>,
1935 pub epoch: Option<u64>,
1936}
1937
1938impl GateTicket {
1939 /// The handler's own response. Its request was active on the cell before
1940 /// the positions were sampled, and a reset deactivates every request of
1941 /// the cell it discards, so the core already refuses a stale one: no
1942 /// epoch needs to travel. Both positions come from one sample, so a
1943 /// read-only response cannot leave its observed position behind.
1944 pub const fn response(position: Option<u64>, observed: Option<u64>) -> Self {
1945 Self {
1946 channel: Channel::Response,
1947 position,
1948 observed,
1949 epoch: None,
1950 }
1951 }
1952}
1953
1954/// The shell identity for one output held by the core.
1955///
1956/// One request can hold output on multiple channels. Keeping both values in
1957/// the map key prevents a later channel from replacing the first channel's
1958/// waiter before the core releases it.
1959#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
1960struct HeldOutputKey {
1961 request: u64,
1962 channel: Channel,
1963}
1964
1965impl HeldOutputKey {
1966 const fn websocket(request: u64) -> Self {
1967 Self {
1968 request,
1969 channel: Channel::WsHibernatable,
1970 }
1971 }
1972}
1973
1974pub struct Actor {
1975 state: ActorState,
1976 pub ownership: Ownership,
1977 peer_http: reqwest::Client,
1978 peer_auth: Arc<PeerAuth>,
1979 operation_deadline_ms: u64,
1980 /// The abandon signal of every eviction stop now in flight, by its op.
1981 ///
1982 /// Only a bounded eviction has an entry, because only a bounded eviction
1983 /// can be given back. The entry is removed when the stop reports either
1984 /// ending, so a late `AbandonEvictionStop` for a finished op finds
1985 /// nothing and does nothing.
1986 eviction_abandons: BTreeMap<OpId, Arc<crate::replication::EvictionAbandon>>,
1987 handoff_directory: Arc<Mutex<HandoffDirectory>>,
1988 host: Option<CellHost>,
1989 drain_pins: DrainPinRegistry,
1990 /// Per-cell handoff pipeline timings, one entry per quiesce nomination.
1991 /// Each phase is measured from effect dispatch to its answering event,
1992 /// so queue time counts because that is the serial cost of the drain.
1993 handoff_timings: HashMap<String, HandoffCellTiming>,
1994 /// The in-flight pipeline step for each timed handoff operation.
1995 handoff_phase_ops: HashMap<OpId, (String, HandoffPhase, u64)>,
1996 /// The node-log manager, filled at boot once the log tier exists:
1997 /// the executor's RecoverNodeLog effect runs through it directly.
1998 pub node_log: Arc<std::sync::Mutex<Option<Arc<crate::node_log::NodeLogManager>>>>,
1999 region: String,
2000 pending: BTreeMap<u64, oneshot::Sender<Result<Routed, RequestError>>>,
2001 request_cells: BTreeMap<u64, String>,
2002 handoff_accepts: BTreeMap<u64, (String, HandoffAcceptWaiter)>,
2003 route_timings: BTreeMap<String, CellRouteTiming>,
2004 pending_workers: BTreeMap<u64, oneshot::Sender<WorkerRouted>>,
2005 pending_evictions: BTreeMap<u64, EvictionReply>,
2006 /// Outputs held by the gate, keyed by request and channel. Every output but
2007 /// a captured `WsHibernatable` frame waits here for the core's `Release`.
2008 gated_responses: BTreeMap<HeldOutputKey, oneshot::Sender<Result<(), RequestError>>>,
2009 /// Per-cell WebSocket output gate: a FIFO of write barriers, each holding
2010 /// the outbound frames produced up to it. The front drains in write order as
2011 /// durability proves, so no client ever sees a frame that trails an
2012 /// unproven write (the Cloudflare per-object output gate).
2013 ws_gates: BTreeMap<String, WsGate>,
2014 /// Gated `webSocketMessage` batches map each request-channel pair to its
2015 /// cell, so `Release` routes to the barrier queue rather than a oneshot.
2016 ws_gated: BTreeMap<HeldOutputKey, String>,
2017 published: BTreeSet<String>,
2018 fail_publish_once: bool,
2019 publishes: u64,
2020 stops: u64,
2021 pub lease_spec: NodeLeaseSpec,
2022 /// Whether to re-check every core invariant after every event.
2023 ///
2024 /// The check is a full scan of the cell table, so its cost grows with
2025 /// residency: roughly 800us per event at ten thousand resident cells,
2026 /// which would cap a busy node at about a thousand events a second in
2027 /// assertion code alone. It is a model-checking assertion, and the place
2028 /// it earns its keep is simulation, which can afford to run it after
2029 /// every event over far more schedules than production will ever see.
2030 /// Debug builds keep it. Release builds rely on the deterministic model,
2031 /// because this full-table scan is too expensive for production traffic.
2032 validate_invariants: bool,
2033 /// Keep a sample for `/state` even without a bucket to publish it to.
2034 live_load: Arc<crate::ownership_store::LiveLoad>,
2035 /// The shed reason last reported to the log, so a latch that holds for
2036 /// minutes is reported once rather than on every sample.
2037 logged_shed_reason: Option<&'static str>,
2038 fence: mpsc::UnboundedSender<i32>,
2039 timer_slots: TimerSlots<()>,
2040 started: bool,
2041 preserving: bool,
2042}
2043
2044/// One handoff pipeline step whose dispatch-to-completion time is measured.
2045#[derive(Clone, Copy, PartialEq)]
2046enum HandoffPhase {
2047 Durability,
2048 Stop,
2049 Release,
2050 Adopt,
2051}
2052
2053/// The accumulating phase durations for one quiescing cell's handoff.
2054struct HandoffCellTiming {
2055 nominated_mono_ms: u64,
2056 quiesce_us: Option<u64>,
2057 durability_us: Option<u64>,
2058 stop_us: Option<u64>,
2059 release_us: Option<u64>,
2060}
2061
2062#[derive(Default)]
2063struct HandoffDirectory {
2064 sampled_at_mono_ms: Option<u64>,
2065 peers: Vec<CapacityPeer>,
2066}
2067
2068const HANDOFF_DIRECTORY_MAX_AGE_MS: u64 = 500;
2069const HANDOFF_RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(250);
2070
2071/// A deterministic final tie-break spreads peers whose projected load is equal.
2072fn handoff_tie_break(cell: &str, node: &str) -> u64 {
2073 let mut hash = 0xcbf2_9ce4_8422_2325_u64;
2074 for byte in cell
2075 .as_bytes()
2076 .iter()
2077 .copied()
2078 .chain(std::iter::once(0xff))
2079 .chain(node.as_bytes().iter().copied())
2080 {
2081 hash ^= u64::from(byte);
2082 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
2083 }
2084 hash
2085}
2086
2087async fn handoff_candidates(
2088 ownership: &Ownership,
2089 directory: &Arc<Mutex<HandoffDirectory>>,
2090 source: &str,
2091 cell: &str,
2092 rebalance: bool,
2093) -> Result<Vec<CapacityPeer>, Failure> {
2094 let mut directory = directory.lock().await;
2095 let now_mono_ms = crate::asyncrt::mono_ms();
2096 let stale = directory
2097 .sampled_at_mono_ms
2098 .is_none_or(|sampled| now_mono_ms.saturating_sub(sampled) >= HANDOFF_DIRECTORY_MAX_AGE_MS);
2099 if stale {
2100 directory.peers = ownership.read_capacity_peers().await?;
2101 directory.sampled_at_mono_ms = Some(now_mono_ms);
2102 }
2103 let peers = directory.peers.clone();
2104 let current_ms = now_ms();
2105 let mut ranked = rank_handoff_candidates(peers, source, cell, current_ms);
2106 // Several cells share this directory between refreshes. Emit one peer
2107 // list per scan, so a blocked drain does not repeat it for every cell.
2108 if stale && ranked.is_empty() && tracing::enabled!(tracing::Level::DEBUG) {
2109 tracing::debug!(
2110 event = "handoff_no_candidate",
2111 %source,
2112 %cell,
2113 excluded_peers = %serde_json::Value::Array(directory.peers.iter().map(|peer| {
2114 serde_json::json!({
2115 "node": peer.node,
2116 "excluded_by": handoff_exclusions(peer, source, current_ms).collect::<Vec<_>>(),
2117 "pressured": peer.pressured,
2118 "memory_headroom": peer.memory_headroom,
2119 "sampled_ms": peer.sampled_ms,
2120 "addr": peer.addr,
2121 "protocol": peer.peer_protocol,
2122 "paced_handoff": peer.paced_handoff,
2123 "expires_ms": peer.expires_ms,
2124 })
2125 }).collect()),
2126 "no peer can adopt a released cell"
2127 );
2128 }
2129 if rebalance {
2130 // A drain takes any peer with room. A balancing move takes only a
2131 // peer below its ownership target, least dense first; a fuller peer
2132 // would hand the cell straight back on its own next sample.
2133 let receivers = celld_logic::rebalance::receivers(
2134 &directory.peers,
2135 source,
2136 now_ms(),
2137 crate::machine::lease_ttl_ms_from_environment(),
2138 );
2139 ranked.retain(|peer| receivers.contains(&peer.node));
2140 ranked.sort_by_key(|peer| receivers.iter().position(|node| *node == peer.node));
2141 if ranked.is_empty() {
2142 // The plan saw room that this sample does not. The adoption
2143 // retries until its deadline, so this repeats; without it a
2144 // failed balancing move left no trace of why.
2145 tracing::debug!(
2146 event = "rebalance_no_receiver",
2147 %cell,
2148 below_target = receivers.len(),
2149 "no peer below its target can take the cell"
2150 );
2151 }
2152 }
2153 Ok(ranked)
2154}
2155
2156/// Names every reason a peer cannot adopt a handoff. Candidate selection and
2157/// the no-candidate diagnostic both use it, so a logged reason cannot drift
2158/// from the rule that actually excluded the peer.
2159fn handoff_exclusions(
2160 peer: &CapacityPeer,
2161 source: &str,
2162 current_ms: u64,
2163) -> impl Iterator<Item = &'static str> {
2164 [
2165 (peer.node == source, "source"),
2166 (peer.expires_ms <= current_ms, "expiry"),
2167 (peer.addr.is_empty(), "addr"),
2168 (
2169 peer.peer_protocol != peer_auth::PROTOCOL_VERSION,
2170 "protocol",
2171 ),
2172 (peer.sampled_ms == 0, "sampled_ms"),
2173 (
2174 !peer.reports_adoption_capacity(),
2175 "reports_adoption_capacity",
2176 ),
2177 (!peer.paced_handoff, "paced_handoff"),
2178 ]
2179 .into_iter()
2180 .filter_map(|(excluded, reason)| excluded.then_some(reason))
2181}
2182
2183fn rank_handoff_candidates(
2184 peers: Vec<CapacityPeer>,
2185 source: &str,
2186 cell: &str,
2187 current_ms: u64,
2188) -> Vec<CapacityPeer> {
2189 let mut peers: Vec<_> = peers
2190 .into_iter()
2191 .filter(|peer| {
2192 handoff_exclusions(peer, source, current_ms)
2193 .next()
2194 .is_none()
2195 })
2196 .collect();
2197 peers.sort_by_key(|peer| {
2198 (
2199 peer.resident_cells,
2200 peer.host_websockets,
2201 peer.in_use_bytes.unwrap_or(peer.rss_bytes),
2202 handoff_tie_break(cell, &peer.node),
2203 peer.node.clone(),
2204 )
2205 });
2206 peers
2207}
2208
2209pub enum HandoffAttempt {
2210 Accepted(AdoptedCell),
2211 CurrentOwner(AdoptedCell),
2212 Refused,
2213}
2214
2215async fn request_peer_handoff(
2216 http: &reqwest::Client,
2217 auth: &PeerAuth,
2218 peer: &AdoptedCell,
2219 request: &HandoffRequest,
2220) -> anyhow::Result<HandoffAttempt> {
2221 let path = "/peer/handoff";
2222 let body = serde_json::to_vec(request)?;
2223 let outbound = auth.sign(
2224 http.post(format!("http://{}{path}", peer.addr)),
2225 "POST",
2226 path,
2227 &body,
2228 &peer.node,
2229 )?;
2230 let request = outbound.body(body).build()?;
2231 // Keep response decoding after transport selection so a test transport
2232 // cannot bypass the donor contract with an invented typed acceptance.
2233 #[cfg(all(test, celld_internal_tests))]
2234 let response = match crate::asyncrt::services().handoff_transport_for_test() {
2235 Some(transport) => transport.send(request).await?,
2236 None => http.execute(request).await?,
2237 };
2238 #[cfg(not(all(test, celld_internal_tests)))]
2239 let response = http.execute(request).await?;
2240 peer_auth::validate_response(response.headers())?;
2241 let status = response.status();
2242 let response: HandoffResponse = match response.json().await {
2243 Ok(response) => response,
2244 Err(_) => return Ok(HandoffAttempt::Refused),
2245 };
2246 let owner = AdoptedCell {
2247 node: response.node,
2248 addr: response.addr,
2249 epoch: response.epoch,
2250 peer_protocol: response.peer_protocol,
2251 };
2252 if status == reqwest::StatusCode::OK && response.published {
2253 Ok(HandoffAttempt::Accepted(owner))
2254 } else if status == reqwest::StatusCode::CONFLICT && !response.published {
2255 Ok(HandoffAttempt::CurrentOwner(owner))
2256 } else {
2257 Ok(HandoffAttempt::Refused)
2258 }
2259}
2260
2261pub struct AdmissionLimits {
2262 pub resident: usize,
2263 pub activations: usize,
2264 // Private worlds vary admission pressure; production fixes this in the core config.
2265 #[cfg(all(test, celld_internal_tests))]
2266 pub evictions: usize,
2267 pub releases: usize,
2268 /// The ownership share this node publishes for rebalancing.
2269 pub placement_weight: u64,
2270}
2271
2272pub struct ActorIdentity {
2273 pub node: String,
2274 pub advertise: String,
2275 pub region: String,
2276}
2277
2278/// The test-only decision state that must be installed as one unit.
2279///
2280/// A scripted Actor cannot read process-wide configuration while concurrent
2281/// Worlds construct other nodes. The resume generation and the core
2282/// configuration therefore travel together to the private constructor.
2283#[cfg(all(test, celld_internal_tests))]
2284pub(crate) struct ScriptedActorDecisionState {
2285 pub(crate) resume_generation: Option<String>,
2286 pub(crate) placement_weight: u64,
2287 pub(crate) config: Config,
2288}
2289
2290pub struct ActorServices {
2291 pub runtime: Option<RuntimeManager>,
2292 pub drain_pins: DrainPinRegistry,
2293 pub ownership: Option<Ownership>,
2294 pub peer_http: reqwest::Client,
2295 pub peer_auth: Arc<PeerAuth>,
2296}
2297
2298struct ActorHostServices {
2299 host: Option<CellHost>,
2300 drain_pins: DrainPinRegistry,
2301 ownership: Option<Ownership>,
2302 peer_http: reqwest::Client,
2303 peer_auth: Arc<PeerAuth>,
2304}
2305
2306impl Actor {
2307 fn schedule_wake_maintenance(&self, cell: String, alarm: celld_logic::wake::AlarmSnapshot) {
2308 let Some(host) = self.host.clone() else {
2309 return;
2310 };
2311 let ownership = self.ownership.clone();
2312 let node = self.state.node().to_string();
2313 let deadline = std::time::Duration::from_millis(self.operation_deadline_ms);
2314 crate::asyncrt::spawn(async move {
2315 match crate::asyncrt::timeout(
2316 deadline,
2317 crate::js::maintain_wake_entry(&cell, alarm, &host, &ownership, &node),
2318 )
2319 .await
2320 {
2321 Ok(Ok(())) => {}
2322 Ok(Err(error)) => tracing::warn!(%cell, %error, "wake maintenance deferred"),
2323 Err(_) => tracing::warn!(%cell, "wake maintenance timed out; a later scan retries"),
2324 }
2325 })
2326 .detach();
2327 }
2328
2329 pub async fn from_environment(
2330 limits: AdmissionLimits,
2331 fail_publish_once: bool,
2332 fence: mpsc::UnboundedSender<i32>,
2333 runtime: Option<RuntimeManager>,
2334 ownership: Option<Ownership>,
2335 identity: ActorIdentity,
2336 resume_generation: Option<String>,
2337 ) -> anyhow::Result<Self> {
2338 let peer_auth = Arc::new(PeerAuth::new([0; 32], identity.node.clone())?);
2339 Self::from_environment_with_cell_host(
2340 limits,
2341 fail_publish_once,
2342 fence,
2343 ActorHostServices {
2344 host: runtime.map(CellHost::Engine),
2345 drain_pins: DrainPinRegistry::default(),
2346 ownership,
2347 peer_http: reqwest::Client::new(),
2348 peer_auth,
2349 },
2350 identity,
2351 resume_generation,
2352 )
2353 .await
2354 }
2355
2356 pub async fn from_environment_with_services(
2357 limits: AdmissionLimits,
2358 fail_publish_once: bool,
2359 fence: mpsc::UnboundedSender<i32>,
2360 services: ActorServices,
2361 identity: ActorIdentity,
2362 resume_generation: Option<String>,
2363 ) -> anyhow::Result<Self> {
2364 let ActorServices {
2365 runtime,
2366 drain_pins,
2367 ownership,
2368 peer_http,
2369 peer_auth,
2370 } = services;
2371 Self::from_environment_with_cell_host(
2372 limits,
2373 fail_publish_once,
2374 fence,
2375 ActorHostServices {
2376 host: runtime.map(CellHost::Engine),
2377 drain_pins,
2378 ownership,
2379 peer_http,
2380 peer_auth,
2381 },
2382 identity,
2383 resume_generation,
2384 )
2385 .await
2386 }
2387
2388 /// Build an Actor on the scripted cell host with the caller's peer client.
2389 ///
2390 /// `main` passes one client to both the Actor and the AppHandle of a node,
2391 /// and the caller of this constructor can do the same. The arguments are
2392 /// those of `from_environment`, with the scripted host in place of the
2393 /// runtime and with that client added. The added client puts the
2394 /// constructor one argument over the Clippy limit.
2395 #[cfg(all(test, celld_internal_tests))]
2396 #[allow(clippy::too_many_arguments)]
2397 pub(crate) async fn from_environment_with_scripted_host(
2398 limits: AdmissionLimits,
2399 fail_publish_once: bool,
2400 fence: mpsc::UnboundedSender<i32>,
2401 host: crate::conformance_sim_cell_host::SimCellHost,
2402 ownership: Option<Ownership>,
2403 peer_http: reqwest::Client,
2404 identity: ActorIdentity,
2405 resume_generation: Option<String>,
2406 ) -> anyhow::Result<Self> {
2407 let peer_auth = Arc::new(PeerAuth::new([0; 32], identity.node.clone())?);
2408 Self::from_environment_with_cell_host(
2409 limits,
2410 fail_publish_once,
2411 fence,
2412 ActorHostServices {
2413 host: Some(CellHost::Scripted(host)),
2414 drain_pins: DrainPinRegistry::default(),
2415 ownership,
2416 peer_http,
2417 peer_auth,
2418 },
2419 identity,
2420 resume_generation,
2421 )
2422 .await
2423 }
2424
2425 /// Build the scripted Actor with one recorded core configuration.
2426 ///
2427 /// Concurrent node construction cannot safely mutate process-wide
2428 /// environment variables. Build the ordinary scripted shell first, then
2429 /// install the supplied configuration in both the unstarted decision core
2430 /// and the shell fields that consume it. The shell services, ownership,
2431 /// and host boundary stay identical to the ordinary constructor.
2432 #[cfg(all(test, celld_internal_tests))]
2433 pub(crate) async fn from_environment_with_scripted_host_and_config(
2434 fail_publish_once: bool,
2435 fence: mpsc::UnboundedSender<i32>,
2436 host: crate::conformance_sim_cell_host::SimCellHost,
2437 ownership: Option<Ownership>,
2438 peer_http: reqwest::Client,
2439 identity: ActorIdentity,
2440 decision_state: ScriptedActorDecisionState,
2441 ) -> anyhow::Result<Self> {
2442 let ScriptedActorDecisionState {
2443 resume_generation,
2444 placement_weight,
2445 config,
2446 } = decision_state;
2447 let operation_deadline_ms = config
2448 .operation_deadline_ms
2449 .filter(|deadline| *deadline > 0)
2450 .ok_or_else(|| {
2451 anyhow::anyhow!(
2452 "the scripted Actor configuration requires a positive operation deadline"
2453 )
2454 })?;
2455 let limits = AdmissionLimits {
2456 resident: config.max_resident,
2457 activations: config.max_activations,
2458 evictions: config.max_evictions,
2459 releases: config.max_releases,
2460 placement_weight,
2461 };
2462 let node = identity.node.clone();
2463 let mut actor = Self::from_environment_with_scripted_host(
2464 limits,
2465 fail_publish_once,
2466 fence,
2467 host,
2468 ownership,
2469 peer_http,
2470 identity,
2471 resume_generation,
2472 )
2473 .await?;
2474 // The shell uses this deadline for handoff and stop retries while the
2475 // core uses the same value to arm operation timers. Installing only
2476 // the core configuration creates two different clocks in one Actor.
2477 actor.operation_deadline_ms = operation_deadline_ms;
2478 actor.state = ActorState::from(State::new(node, config));
2479 Ok(actor)
2480 }
2481
2482 async fn from_environment_with_cell_host(
2483 limits: AdmissionLimits,
2484 fail_publish_once: bool,
2485 fence: mpsc::UnboundedSender<i32>,
2486 services: ActorHostServices,
2487 identity: ActorIdentity,
2488 resume_generation: Option<String>,
2489 ) -> anyhow::Result<Self> {
2490 let ActorHostServices {
2491 host,
2492 drain_pins,
2493 ownership,
2494 peer_http,
2495 peer_auth,
2496 } = services;
2497 let ActorIdentity {
2498 node,
2499 advertise,
2500 region,
2501 } = identity;
2502 let ownership = if let Some(ownership) = ownership {
2503 ownership
2504 } else {
2505 Ownership::Memory(Arc::new(Mutex::new(MemoryOwnership {
2506 node: node.clone(),
2507 owners: BTreeMap::new(),
2508 leases: BTreeMap::new(),
2509 next_etag: 1,
2510 })))
2511 };
2512 let live_load = match &ownership {
2513 Ownership::Bucket(bucket) => bucket.live(),
2514 Ownership::Memory(_) => Arc::new(crate::ownership_store::LiveLoad::default()),
2515 };
2516 live_load
2517 .placement_weight
2518 .store(limits.placement_weight.max(1), Ordering::Relaxed);
2519 if matches!(&ownership, Ownership::Bucket(_)) {
2520 crate::ownership_store::set_node_load(live_load.clone());
2521 }
2522 let process_generation = match &ownership {
2523 Ownership::Bucket(bucket) => bucket
2524 .process_generation()
2525 .map(str::to_owned)
2526 .unwrap_or_else(random_process_generation),
2527 Ownership::Memory(_) => random_process_generation(),
2528 };
2529 let ttl_ms = crate::env_vars::positive_or("CELLD_TTL_MS", 10_000)?;
2530 let operation_deadline_ms = operation_deadline_ms()?;
2531 let lease_spec = NodeLeaseSpec {
2532 // Startup has already resolved the environment and CLI settings
2533 // into this validated internal address. Reading the environment
2534 // again would let CELLD_ADVERTISE override a later CLI option and
2535 // publish an address that the bound listener did not validate.
2536 addr: advertise,
2537 peer_protocol: peer_auth::PROTOCOL_VERSION,
2538 generation: std::env::var("CELLD_TEST_GENERATION").unwrap_or(process_generation),
2539 resume_generation,
2540 ttl_ms,
2541 };
2542 Ok(Self {
2543 node_log: Arc::new(std::sync::Mutex::new(None)),
2544 state: ActorState::from(State::new(
2545 node,
2546 Config {
2547 max_resident: limits.resident,
2548 max_activations: limits.activations,
2549 // Each eviction proves durability, so bound background bucket I/O.
2550 #[cfg(not(all(test, celld_internal_tests)))]
2551 max_evictions: 4,
2552 #[cfg(all(test, celld_internal_tests))]
2553 max_evictions: limits.evictions,
2554 max_releases: limits.releases,
2555 alarm_resident_ms: crate::wake::resident_ms().max(0) as u64,
2556 require_node_lease: true,
2557 peer_protocol: crate::peer_auth::PROTOCOL_VERSION,
2558 operation_deadline_ms: Some(operation_deadline_ms),
2559 owner_log_recovery_backoff_ms: crate::env_vars::positive_or(
2560 "CELLD_RECOVERY_RETRY_MS",
2561 DEFAULT_OWNER_LOG_RECOVERY_BACKOFF_MS,
2562 )?,
2563 owner_log_recovery_attempts: crate::env_vars::positive_or(
2564 "CELLD_RECOVERY_RETRIES",
2565 DEFAULT_OWNER_LOG_RECOVERY_ATTEMPTS,
2566 )?,
2567 idle_evict_ms: crate::env_vars::positive::<u64>("CELLD_IDLE_EVICT_S")?
2568 .map(|seconds| seconds.saturating_mul(1_000)),
2569 pressure: pressure_config_from_environment()?,
2570 max_outbound_websockets: crate::env_vars::positive_or(
2571 "CELLD_MAX_OUTBOUND_WEBSOCKETS",
2572 DEFAULT_MAX_OUTBOUND_WEBSOCKETS,
2573 )?,
2574 ownership_on_evict: match &ownership {
2575 // Releasing a cell says "any node may take this
2576 // one", which is only true if some other node could
2577 // restore it. Without a bucket the sole copy is this
2578 // node's disk, keyed to an epoch a re-acquire will
2579 // step past, so releasing would lose the cell.
2580 Ownership::Memory(_) => OwnershipOnEvict::Sticky,
2581 Ownership::Bucket(_) => ownership_on_evict_from_environment()?,
2582 },
2583 },
2584 )),
2585 ownership,
2586 peer_http,
2587 peer_auth,
2588 operation_deadline_ms,
2589 eviction_abandons: BTreeMap::new(),
2590 handoff_directory: Arc::new(Mutex::new(HandoffDirectory::default())),
2591 host,
2592 drain_pins,
2593 handoff_timings: HashMap::new(),
2594 handoff_phase_ops: HashMap::new(),
2595 region,
2596 pending: BTreeMap::new(),
2597 request_cells: BTreeMap::new(),
2598 handoff_accepts: BTreeMap::new(),
2599 route_timings: BTreeMap::new(),
2600 pending_workers: BTreeMap::new(),
2601 pending_evictions: BTreeMap::new(),
2602 gated_responses: BTreeMap::new(),
2603 ws_gates: BTreeMap::new(),
2604 ws_gated: BTreeMap::new(),
2605 published: BTreeSet::new(),
2606 fail_publish_once,
2607 publishes: 0,
2608 stops: 0,
2609 lease_spec,
2610 live_load,
2611 logged_shed_reason: None,
2612 validate_invariants: cfg!(debug_assertions),
2613 fence,
2614 timer_slots: TimerSlots::default(),
2615 started: false,
2616 preserving: false,
2617 })
2618 }
2619
2620 /// Stores a host sample for `/state` and the node lease.
2621 pub fn store_load_sample(&self, sample: crate::host_services::HostMetricsSample) {
2622 // Bucket mode shares this Arc with bucket.live(), so this also seeds the lease.
2623 self.live_load.store_sample(sample);
2624 }
2625
2626 /// Emits the exactly-once pre-loop node-lease transition.
2627 pub fn start(&mut self, out: &mut StepOutput) {
2628 assert!(!self.started, "Actor::start was called more than once");
2629 self.started = true;
2630 // A later sample does not rewrite the lease. Fold a sample before the
2631 // first CAS can publish defaults, which otherwise reject healthy
2632 // handoff targets or hide pressure until a renewal. Production seeds
2633 // one off the core before the core thread starts; the fallback serves
2634 // deterministic worlds, whose scripted services read no host files.
2635 let metrics = self
2636 .live_load
2637 .stored_sample()
2638 .unwrap_or_else(|| crate::asyncrt::services().sample_metrics());
2639 self.sample_load(metrics, out);
2640 self.drive(
2641 Event::StartNodeLease {
2642 now_ms: now_ms(),
2643 now_mono_ms: crate::asyncrt::mono_ms(),
2644 spec: self.lease_spec.clone(),
2645 },
2646 out,
2647 );
2648 }
2649
2650 /// Folds one load sample into the core and publishes it to the lease
2651 /// adapter. `start` calls it before the first lease; the periodic sampler
2652 /// message calls it afterwards. The caller supplies the sample, so the
2653 /// core itself reads no host files.
2654 fn sample_load(
2655 &mut self,
2656 metrics: crate::host_services::HostMetricsSample,
2657 out: &mut StepOutput,
2658 ) {
2659 // Counted once: it is a walk of every cell, and the latch and
2660 // the number peers rank this node by must agree anyway.
2661 let occupied = self.state.occupied();
2662 let load = celld_logic::pressure::Load {
2663 resident_cells: occupied,
2664 rss_bytes: metrics.rss_bytes,
2665 in_use_bytes: metrics.in_use_bytes,
2666 cgroup_working_set_bytes: metrics.cgroup_working_set_bytes,
2667 cgroup_current_bytes: metrics.cgroup_current_bytes,
2668 };
2669 let now_mono_ms = crate::asyncrt::mono_ms();
2670 self.drive(Event::LoadSampled { load, now_mono_ms }, out);
2671 // Report a change of shed reason once. `rss-hard` retains its
2672 // established name, but in a Linux cgroup it says
2673 // `memory.current` crossed the absolute cap.
2674 let reason = self.state.shed_reason();
2675 if reason != self.logged_shed_reason {
2676 self.logged_shed_reason = reason;
2677 // How many V8 heaps the resident cells hold open. Most of
2678 // what a cell costs is its heap, and a heap comes back
2679 // only when its last cell goes, so cells alone do not say
2680 // how much a walk down can still return.
2681 let heaps = self
2682 .state
2683 .resident_isolates()
2684 .into_iter()
2685 .collect::<BTreeSet<_>>()
2686 .len();
2687 match reason {
2688 Some(celld_logic::pressure::SHED_RSS_HARD) => tracing::warn!(
2689 rss_bytes = load.rss_bytes,
2690 in_use_bytes = load.in_use_bytes,
2691 cgroup_working_set_bytes = load.cgroup_working_set_bytes,
2692 cgroup_current_bytes = load.cgroup_current_bytes,
2693 heaps,
2694 "shedding on the absolute memory cap"
2695 ),
2696 Some(reason) => tracing::info!(
2697 reason,
2698 rss_bytes = load.rss_bytes,
2699 in_use_bytes = load.in_use_bytes,
2700 cgroup_working_set_bytes = load.cgroup_working_set_bytes,
2701 cgroup_current_bytes = load.cgroup_current_bytes,
2702 heaps,
2703 "shedding"
2704 ),
2705 None => tracing::info!("no longer shedding"),
2706 }
2707 }
2708 // Republish what peers rank this node by. The same numbers the
2709 // latch just saw: a node that reports last tick's residency
2710 // attracts work it has already refused.
2711 let live = &self.live_load;
2712 live.owned_cells
2713 .store(self.state.owned_cells(), Ordering::Relaxed);
2714 live.ownership_confirmed
2715 .store(self.state.ownership_confirmed(), Ordering::Relaxed);
2716 live.resident_cells.store(occupied, Ordering::Relaxed);
2717 live.host_websockets
2718 .store(self.state.host_websockets(), Ordering::Relaxed);
2719 live.pressured
2720 .store(self.state.shedding(), Ordering::Relaxed);
2721 live.memory_headroom
2722 .store(self.state.memory_headroom(), Ordering::Relaxed);
2723 live.restoring
2724 .store(self.state.activation_backlog() as u64, Ordering::Relaxed);
2725 live.draining
2726 .store(self.state.draining(), Ordering::Relaxed);
2727 live.store_sample(metrics);
2728 }
2729
2730 /// Handles exactly one ready mailbox item, completion, or timer.
2731 pub fn step(&mut self, input: ActorInput, out: &mut StepOutput) {
2732 assert!(self.started, "Actor::step was called before Actor::start");
2733 match input {
2734 ActorInput::Message(message) => self.handle_message(message, out),
2735 ActorInput::Completed(completed) => {
2736 let route_cell = completed.timing.as_ref().map(|timing| timing.cell.clone());
2737 if let Some(timing) = completed.timing {
2738 self.record_effect_timing(timing);
2739 }
2740 self.drive(completed.event, out);
2741 if let Some(cell) = route_cell {
2742 self.observe_capacity_wait(&cell);
2743 }
2744 }
2745 ActorInput::TimerFired(timer) => {
2746 self.timer_slots.clear_slot(&TimerSlot::of(&timer));
2747 if self.preserving && matches!(timer, Timer::CellAlarm { .. }) {
2748 return;
2749 }
2750 self.drive(
2751 Event::TimerFired {
2752 timer,
2753 now_ms: now_ms(),
2754 now_mono_ms: crate::asyncrt::mono_ms(),
2755 },
2756 out,
2757 );
2758 }
2759 }
2760 }
2761
2762 fn handle_message(&mut self, message: Message, out: &mut StepOutput) {
2763 match message {
2764 Message::BeginPreserve => {
2765 self.preserving = true;
2766 self.drive(Event::BeginPreserve, out);
2767 }
2768 Message::Request { reply, .. } if self.preserving => {
2769 let _ = reply.send(Err(RequestError::NodeFenced));
2770 }
2771 Message::Request {
2772 request,
2773 cell,
2774 capacity_handoff,
2775 handoff_accept,
2776 resident_work,
2777 reply,
2778 } => {
2779 self.pending.insert(request, reply);
2780 let ownership_handoff = handoff_accept.is_some();
2781 if let Some(waiter) = handoff_accept {
2782 self.handoff_accepts.insert(request, (cell.clone(), waiter));
2783 }
2784 self.begin_route_if_cold(&cell);
2785 self.request_cells.insert(request, cell.clone());
2786 self.drive(
2787 if let Some(ResidentWork::WebSocket(websocket)) = resident_work {
2788 Event::WebSocketRequestAt {
2789 request,
2790 cell: cell.clone(),
2791 websocket,
2792 now_ms: now_ms(),
2793 now_mono_ms: crate::asyncrt::mono_ms(),
2794 }
2795 } else if resident_work == Some(ResidentWork::OutputGate) {
2796 Event::GateRequestAt {
2797 request,
2798 cell: cell.clone(),
2799 now_mono_ms: crate::asyncrt::mono_ms(),
2800 }
2801 } else if ownership_handoff {
2802 Event::HandoffRequestAt {
2803 request,
2804 cell: cell.clone(),
2805 now_ms: now_ms(),
2806 now_mono_ms: crate::asyncrt::mono_ms(),
2807 }
2808 } else if capacity_handoff {
2809 Event::CapacityRequestAt {
2810 request,
2811 cell: cell.clone(),
2812 now_mono_ms: crate::asyncrt::mono_ms(),
2813 }
2814 } else {
2815 Event::RequestAt {
2816 request,
2817 cell: cell.clone(),
2818 now_mono_ms: crate::asyncrt::mono_ms(),
2819 }
2820 },
2821 out,
2822 );
2823 self.observe_capacity_wait(&cell);
2824 }
2825 Message::CancelRoute { request } => {
2826 self.pending.remove(&request);
2827 self.handoff_accepts.remove(&request);
2828 if let Some(cell) = self.request_cells.remove(&request) {
2829 self.finish_route(&cell, "cancelled", "caller_disconnected", None);
2830 }
2831 self.drive(Event::Cancel { request }, out);
2832 }
2833 Message::WorkerRequest { reply } if self.preserving => {
2834 let _ = reply.send(WorkerRouted {
2835 request: crate::asyncrt::next_core_request(),
2836 route: None,
2837 });
2838 }
2839 Message::WorkerRequest { reply } => {
2840 let request = crate::asyncrt::next_core_request();
2841 self.pending_workers.insert(request, reply);
2842 self.drive(Event::WorkerRequest { request }, out);
2843 }
2844 Message::ReleaseAll => self.drive(Event::ReleaseAll, out),
2845 Message::Rebalance { .. } if self.preserving => {}
2846 Message::Rebalance { cells } => self.drive(Event::Rebalance { cells }, out),
2847 Message::GenerationChanged {
2848 generation,
2849 max_age_ms,
2850 eager_classes,
2851 } => self.drive(
2852 Event::GenerationChanged {
2853 generation,
2854 now_mono_ms: crate::asyncrt::mono_ms(),
2855 max_age_ms,
2856 eager_classes,
2857 },
2858 out,
2859 ),
2860 Message::Drained { reply } => {
2861 let _ = reply.send(DrainStatus {
2862 occupied: self.state.occupied(),
2863 activating: self.state.activating(),
2864 quiescing: self.state.quiescing(),
2865 evicting: self.state.evicting(),
2866 releasing: self.state.releasing(),
2867 adopting: self.state.adopting(),
2868 handed_off: self.state.handed_off(),
2869 });
2870 }
2871 Message::ResidentEpoch { cell, reply } => {
2872 let epoch = match self.state.phase(&cell) {
2873 Some(Phase::Resident { epoch })
2874 | Some(Phase::EnsuringDurability { epoch, .. }) => Some(*epoch),
2875 _ => None,
2876 };
2877 let _ = reply.send(epoch);
2878 }
2879 Message::SampleLoad(metrics) if self.preserving => self.live_load.store_sample(metrics),
2880 Message::SampleLoad(metrics) => self.sample_load(metrics, out),
2881 Message::Output {
2882 request,
2883 ticket,
2884 reply,
2885 } => {
2886 self.gated_responses.insert(
2887 HeldOutputKey {
2888 request,
2889 channel: ticket.channel,
2890 },
2891 reply,
2892 );
2893 self.drive(
2894 Event::OutputAt {
2895 request,
2896 channel: ticket.channel,
2897 position: ticket.position,
2898 observed: ticket.observed,
2899 epoch: ticket.epoch,
2900 now_mono_ms: crate::asyncrt::mono_ms(),
2901 },
2902 out,
2903 );
2904 }
2905 Message::WsOutput {
2906 request,
2907 scope,
2908 frames,
2909 write_position,
2910 observed,
2911 reply,
2912 } => {
2913 // Open a barrier for every batch, then let the core decide
2914 // what it trails: its own write when the handler wrote, and
2915 // otherwise the newest write still outstanding on this cell,
2916 // whichever channel made it. The queue consulted here before
2917 // was filled in one place -- the arm below that writes -- so it
2918 // held only writes a `webSocketMessage` handler made itself,
2919 // and an HTTP, RPC, or peer write on the same cell was
2920 // invisible to a batch that only read.
2921 //
2922 // Both registrations happen before the drive, and must: `drive`
2923 // runs the effects it produces synchronously, so a read with no
2924 // barrier open on its cell is released inside the call below.
2925 // Moved after it, that `Effect::Release` would find no
2926 // `ws_gated` entry, fall through to the `gated_responses` map,
2927 // match nothing, and strand these frames behind a barrier that
2928 // nothing will ever settle.
2929 self.ws_gates
2930 .entry(scope.clone())
2931 .or_default()
2932 .barriers
2933 .push_back(WsBarrier {
2934 request,
2935 settled: None,
2936 frames,
2937 });
2938 self.ws_gated
2939 .insert(HeldOutputKey::websocket(request), scope);
2940 // The core answers for every writer on the cell, including an
2941 // alarm: its consuming commit opens a barrier of its own, so a
2942 // read-only batch trails that too.
2943 self.drive(
2944 Event::OutputAt {
2945 request,
2946 channel: Channel::WsHibernatable,
2947 position: write_position,
2948 observed,
2949 epoch: None,
2950 now_mono_ms: crate::asyncrt::mono_ms(),
2951 },
2952 out,
2953 );
2954 let _ = reply.send(());
2955 }
2956 Message::ActivityFinished {
2957 request,
2958 cell,
2959 alarm,
2960 alarm_covered,
2961 } => {
2962 // Observe the alarm before releasing the activity. The core
2963 // reports whether that observation cancels an eviction proof.
2964 self.drive(
2965 Event::AlarmObserved {
2966 cell,
2967 alarm,
2968 covered: alarm_covered,
2969 now_ms: now_ms(),
2970 now_mono_ms: crate::asyncrt::mono_ms(),
2971 },
2972 out,
2973 );
2974 self.drive(Event::ActivityFinished { request }, out);
2975 }
2976 Message::WebSocketOpened {
2977 cell,
2978 websocket,
2979 kind,
2980 reply,
2981 } => {
2982 self.drive(
2983 Event::WebSocketOpened {
2984 cell: cell.clone(),
2985 websocket,
2986 kind,
2987 },
2988 out,
2989 );
2990 // The core may decline to hold the transport. Say so, rather
2991 // than acknowledging an open and closing the socket a moment
2992 // later: an application that hit a ceiling deserves to be
2993 // told which one, not left watching a socket disappear.
2994 // Only an outbound socket can be declined, and only for a
2995 // cell the core knows: an inbound transport is never refused,
2996 // and reporting one as refused fails opens that succeeded.
2997 let refused = kind == WebSocketKind::Outbound
2998 && !self.state.holds_websocket(&cell, websocket);
2999 let _ = reply.send(!refused);
3000 }
3001 Message::WebSocketClosed { cell, websocket } => {
3002 self.drive(Event::WebSocketClosed { cell, websocket }, out);
3003 }
3004 Message::AlarmObserved {
3005 cell,
3006 alarm,
3007 covered,
3008 } => {
3009 self.drive(
3010 Event::AlarmObserved {
3011 cell,
3012 alarm,
3013 covered,
3014 now_ms: now_ms(),
3015 now_mono_ms: crate::asyncrt::mono_ms(),
3016 },
3017 out,
3018 );
3019 }
3020 Message::NudgeNodeLease => {
3021 self.drive(
3022 Event::NudgeNodeLease {
3023 now_ms: now_ms(),
3024 now_mono_ms: crate::asyncrt::mono_ms(),
3025 },
3026 out,
3027 );
3028 }
3029 Message::MaintainWake { cell } => {
3030 if let Some(host) = &self.host {
3031 let alarm = host.with_alarm(&cell, |alarm, _| alarm);
3032 self.schedule_wake_maintenance(cell, alarm);
3033 }
3034 }
3035 Message::WakeHint { .. } if self.preserving => {}
3036 Message::WakeHint {
3037 cell,
3038 entry_ms,
3039 scope,
3040 } => {
3041 self.drive(
3042 Event::WakeHintAt {
3043 cell,
3044 entry_ms,
3045 scope,
3046 now_mono_ms: crate::asyncrt::mono_ms(),
3047 },
3048 out,
3049 );
3050 }
3051 Message::Evict { reply, .. } if self.preserving => {
3052 let _ = reply.send(Err(EvictError::Refused(EvictRefusal::NodeUnavailable)));
3053 }
3054 Message::Evict { cell, reply } => {
3055 let request = crate::asyncrt::next_core_request();
3056 self.pending_evictions.insert(request, reply);
3057 self.drive(
3058 Event::EvictRequested {
3059 request,
3060 cell,
3061 now_mono_ms: crate::asyncrt::mono_ms(),
3062 },
3063 out,
3064 );
3065 }
3066 Message::InvalidateRemote {
3067 cell,
3068 node,
3069 epoch,
3070 reply,
3071 } => {
3072 self.drive(Event::InvalidateRemote { cell, node, epoch }, out);
3073 let _ = reply.send(());
3074 }
3075 Message::Snapshot { reply } => {
3076 let generations = self
3077 .state
3078 .residents()
3079 .into_iter()
3080 .map(|cell| {
3081 let generation = self.state.cell_generation(&cell).unwrap_or(0);
3082 (cell, generation)
3083 })
3084 .collect();
3085 let census = SwapCensus {
3086 swapping: self.state.swapping(),
3087 generations,
3088 };
3089 let _ = reply.send((self.state_json(), self.state.drain_pins(), census));
3090 }
3091 Message::Health { reply } => {
3092 let _ = reply.send(self.state.ready_to_serve());
3093 }
3094 Message::Presence { reply } => {
3095 let _ = reply.send(self.state.presence_snapshot());
3096 }
3097 }
3098 }
3099
3100 /// Settle a gated `webSocketMessage`'s durability. On success mark its
3101 /// barrier durable and flush the durable prefix in write order; on failure
3102 /// break the whole cell gate — drop every held frame and reset its sockets,
3103 /// since an unproven write must never leave an acknowledged trace.
3104 fn ws_release(&mut self, held: HeldOutputKey, ok: bool) {
3105 let Some(scope) = self.ws_gated.remove(&held) else {
3106 return;
3107 };
3108 let mut flush = Vec::new();
3109 let broke = {
3110 let Some(gate) = self.ws_gates.get_mut(&scope) else {
3111 return;
3112 };
3113 if let Some(barrier) = gate.barriers.iter_mut().find(|b| b.request == held.request) {
3114 barrier.settled = Some(ok);
3115 }
3116 if gate.barriers.iter().any(|b| b.settled == Some(false)) {
3117 true
3118 } else {
3119 while gate
3120 .barriers
3121 .front()
3122 .is_some_and(|b| b.settled == Some(true))
3123 {
3124 flush.push(gate.barriers.pop_front().unwrap().frames);
3125 }
3126 false
3127 }
3128 };
3129 if broke {
3130 // Close before the barriers drop. A captured batch that drops
3131 // unreleased closes its sockets with its own reason, and a socket
3132 // writer stops after the first close, so dropping the gate first
3133 // would replace this reason on every socket that had a frame held.
3134 let gate = self.ws_gates.remove(&scope);
3135 self.ws_gated.retain(|_, s| *s != scope);
3136 crate::js::ws_close_scope(&scope, 1011, "durability unproven");
3137 drop(gate);
3138 return;
3139 }
3140 for frames in flush {
3141 crate::js::ws_emit_batch(frames);
3142 }
3143 if self
3144 .ws_gates
3145 .get(&scope)
3146 .is_some_and(|g| g.barriers.is_empty())
3147 {
3148 self.ws_gates.remove(&scope);
3149 }
3150 }
3151
3152 /// Close a timed handoff pipeline step when its answering event arrives,
3153 /// and emit the cell's aggregate timing once adoption succeeds. A failed
3154 /// adoption keeps the cell entry so its retry accumulates on the same
3155 /// record; an expired operation abandons its pipeline entirely.
3156 fn close_handoff_phase(&mut self, event: &Event) {
3157 let (op, adopted) = match event {
3158 Event::DurabilityChecked { op, .. }
3159 | Event::RuntimeStopped { op }
3160 | Event::OwnerReleased { op, .. } => (*op, None),
3161 Event::SuccessorAdopted { op, result } => (*op, Some(result.is_ok())),
3162 Event::TimerFired {
3163 timer: Timer::OperationDeadline { op },
3164 ..
3165 } => {
3166 if let Some((cell, _, _)) = self.handoff_phase_ops.remove(op) {
3167 self.handoff_timings.remove(&cell);
3168 }
3169 return;
3170 }
3171 _ => return,
3172 };
3173 let Some((cell, phase, started_mono_ms)) = self.handoff_phase_ops.remove(&op) else {
3174 return;
3175 };
3176 let elapsed = mono_elapsed_us(started_mono_ms);
3177 if phase == HandoffPhase::Adopt {
3178 if adopted == Some(true) {
3179 if let Some(timing) = self.handoff_timings.remove(&cell) {
3180 tracing::info!(
3181 event = "cell_handoff_timing",
3182 %cell,
3183 quiesce_us = timing.quiesce_us.unwrap_or(0),
3184 durability_us = timing.durability_us.unwrap_or(0),
3185 stop_us = timing.stop_us.unwrap_or(0),
3186 release_us = timing.release_us.unwrap_or(0),
3187 adopt_us = elapsed,
3188 total_us = mono_elapsed_us(timing.nominated_mono_ms),
3189 "handoff pipeline completed"
3190 );
3191 }
3192 }
3193 return;
3194 }
3195 let Some(timing) = self.handoff_timings.get_mut(&cell) else {
3196 return;
3197 };
3198 match phase {
3199 HandoffPhase::Durability => timing.durability_us = Some(elapsed),
3200 HandoffPhase::Stop => timing.stop_us = Some(elapsed),
3201 HandoffPhase::Release => timing.release_us = Some(elapsed),
3202 HandoffPhase::Adopt => {}
3203 }
3204 }
3205
3206 fn drive(&mut self, first: Event, out: &mut StepOutput) {
3207 let mut events = VecDeque::from([first]);
3208 while let Some(event) = events.pop_front() {
3209 self.close_handoff_phase(&event);
3210 if let Event::RuntimeStopped { op }
3211 | Event::RuntimeStopFailed { op }
3212 | Event::RuntimeStopCancelled { op } = &event
3213 {
3214 self.eviction_abandons.remove(op);
3215 }
3216 let effects = apply_core_event(&mut self.state, event);
3217 for effect in effects {
3218 self.execute(effect, &mut events, out);
3219 }
3220 self.settle_handoff_accepts();
3221 if self.validate_invariants {
3222 self.state.validate().expect("celld core invariant");
3223 }
3224 }
3225 }
3226
3227 fn settle_handoff_accepts(&mut self) {
3228 let accepted: Vec<_> = self
3229 .handoff_accepts
3230 .iter()
3231 .filter_map(|(request, (cell, waiter))| {
3232 self.state
3233 .accepted_epoch(cell)
3234 .filter(|epoch| *epoch > waiter.released_epoch)
3235 .map(|epoch| (*request, epoch))
3236 })
3237 .collect();
3238 for (request, epoch) in accepted {
3239 let Some((_, waiter)) = self.handoff_accepts.remove(&request) else {
3240 continue;
3241 };
3242 let _ = waiter.reply.send(AdoptedCell {
3243 node: self.state.node().to_string(),
3244 addr: self.lease_spec.addr.clone(),
3245 epoch,
3246 peer_protocol: peer_auth::PROTOCOL_VERSION,
3247 });
3248 }
3249 }
3250
3251 fn execute(&mut self, effect: Effect, immediate: &mut VecDeque<Event>, out: &mut StepOutput) {
3252 match effect {
3253 Effect::ScheduleTimer { timer, at_mono_ms } => {
3254 let (arm, _) = self.timer_slots.arm(timer, at_mono_ms, ());
3255 out.timers.push(arm);
3256 }
3257 Effect::ReadSelfNodeLease { op } => {
3258 out.lease(
3259 LeaseRequest::ReadSelf {
3260 op,
3261 node: self.state.node().to_string(),
3262 },
3263 &self.ownership,
3264 );
3265 }
3266 Effect::CasNodeLease {
3267 op,
3268 guard,
3269 record,
3270 authority_expires_ms,
3271 } => {
3272 out.lease(
3273 LeaseRequest::Cas {
3274 op,
3275 guard,
3276 record,
3277 authority_expires_ms,
3278 },
3279 &self.ownership,
3280 );
3281 }
3282 Effect::ReadLocalCells => {
3283 let runtime = self.host.clone();
3284 out.spawn_scoped(async move {
3285 let result = match runtime {
3286 // The host runtime's blocking pool, not a second
3287 // pool on the core's current-thread runtime.
3288 Some(runtime) => crate::asyncrt::blocking(move || {
3289 runtime.local_reload_cells().map_err(|error| {
3290 eprintln!("celld local reload scan failed: {error:#}");
3291 Failure::Definite
3292 })
3293 })
3294 .await
3295 .unwrap_or(Err(Failure::Definite)),
3296 None => Err(Failure::Definite),
3297 };
3298 CompletedEffect::plain(Event::LocalCellsRead { result })
3299 });
3300 }
3301 Effect::ReadOwner { op, cell } => {
3302 self.route_effect_started(&cell);
3303 let ownership = self.ownership.clone();
3304 let timing_cell = cell.clone();
3305 out.spawn_scoped(async move {
3306 let started = crate::asyncrt::mono_ms();
3307 let result = ownership.read_owner_for_claim(&cell).await;
3308 CompletedEffect::timed(
3309 Event::OwnerRead {
3310 op,
3311 now_ms: now_ms(),
3312 result,
3313 },
3314 timing_cell,
3315 RouteStage::OwnershipRead,
3316 started,
3317 )
3318 });
3319 }
3320 Effect::ReadNodeLease { op, cell, owner } => {
3321 self.route_effect_started(&cell);
3322 let ownership = self.ownership.clone();
3323 let timing_cell = cell;
3324 out.spawn_scoped(async move {
3325 let started = crate::asyncrt::mono_ms();
3326 let result = ownership.read_node_lease(&owner).await;
3327 CompletedEffect::timed(
3328 Event::NodeLeaseRead {
3329 op,
3330 now_ms: now_ms(),
3331 result,
3332 },
3333 timing_cell,
3334 RouteStage::NodeLeaseLookup,
3335 started,
3336 )
3337 });
3338 }
3339 Effect::RecoverNodeLog { op, cell, owner } => {
3340 self.route_effect_started(&cell);
3341 let interlock = self.node_log.lock().unwrap().clone();
3342 let timing_cell = cell.clone();
3343 out.spawn_scoped(async move {
3344 let started = crate::asyncrt::mono_ms();
3345 let result = match interlock {
3346 // No log tier on this node (no bucket): nothing to
3347 // recover, and the claim proceeds as before.
3348 None => Ok(()),
3349 Some(interlock) => interlock
3350 .ensure_recovered(Some(&owner))
3351 .await
3352 .map_err(|error| {
3353 eprintln!(
3354 "celld node-log recovery for takeover of {cell} failed: {error:#}"
3355 );
3356 Failure::Ambiguous
3357 }),
3358 };
3359 CompletedEffect::timed(
3360 Event::NodeLogRecovered { op, result },
3361 timing_cell,
3362 RouteStage::NodeLeaseLookup,
3363 started,
3364 )
3365 });
3366 }
3367 Effect::ReadCapacityPeers { op, cell } => {
3368 self.route_effect_started(&cell);
3369 let ownership = self.ownership.clone();
3370 let timing_cell = cell;
3371 out.spawn_scoped(async move {
3372 let started = crate::asyncrt::mono_ms();
3373 // The shared sample, judged at the instant it was taken:
3374 // its leases are copies that age while the nodes renew.
3375 let (now_ms, result) = match ownership.read_capacity_view().await {
3376 Ok((view_ms, peers)) => (view_ms, Ok(peers)),
3377 Err(error) => (now_ms(), Err(error)),
3378 };
3379 CompletedEffect::timed(
3380 Event::CapacityPeersRead { op, now_ms, result },
3381 timing_cell,
3382 RouteStage::CapacityLookup,
3383 started,
3384 )
3385 });
3386 }
3387 Effect::CasOwner {
3388 op,
3389 cell,
3390 guard,
3391 epoch,
3392 takeover,
3393 } => {
3394 self.route_effect_started(&cell);
3395 if let Some(timing) = self.route_timings.get_mut(&cell) {
3396 timing
3397 .fresh
3398 .get_or_insert(!takeover && matches!(guard, CasGuard::Absent));
3399 }
3400 let ownership = self.ownership.clone();
3401 let timing_cell = cell.clone();
3402 out.spawn_scoped(async move {
3403 let started = crate::asyncrt::mono_ms();
3404 let result = ownership.cas_owner(&cell, guard, epoch).await;
3405 CompletedEffect::timed(
3406 Event::OwnerCasCompleted { op, result },
3407 timing_cell,
3408 RouteStage::OwnershipAcquire,
3409 started,
3410 )
3411 });
3412 }
3413 Effect::ReconcileWakeEntry { cell, alarm } => {
3414 self.schedule_wake_maintenance(cell, alarm);
3415 }
3416 Effect::ReleaseOwner { op, cell, epoch } => {
3417 if self.handoff_timings.contains_key(&cell) {
3418 self.handoff_phase_ops.insert(
3419 op,
3420 (
3421 cell.clone(),
3422 HandoffPhase::Release,
3423 crate::asyncrt::mono_ms(),
3424 ),
3425 );
3426 }
3427 let ownership = self.ownership.clone();
3428 out.spawn_scoped(async move {
3429 let result = ownership.release_owner(&cell, epoch).await;
3430 CompletedEffect::plain(Event::OwnerReleased { op, result })
3431 });
3432 }
3433 Effect::AdoptReleased {
3434 op,
3435 cell,
3436 released_epoch,
3437 rebalance,
3438 } => {
3439 // The in-memory adapter is one process, so it has no successor
3440 // to acknowledge a handoff.
3441 if matches!(&self.ownership, Ownership::Memory(_)) {
3442 immediate.push_back(Event::SuccessorAdopted {
3443 op,
3444 result: Err(Failure::Definite),
3445 });
3446 return;
3447 }
3448 if self.handoff_timings.contains_key(&cell) {
3449 self.handoff_phase_ops.insert(
3450 op,
3451 (cell.clone(), HandoffPhase::Adopt, crate::asyncrt::mono_ms()),
3452 );
3453 }
3454 let ownership = self.ownership.clone();
3455 let directory = self.handoff_directory.clone();
3456 let http = self.peer_http.clone();
3457 let auth = self.peer_auth.clone();
3458 let source = self.state.node().to_string();
3459 // A drain retries until the process deadline ends it. A
3460 // balancing move has no such end, so it fails after the
3461 // operation deadline and the cell stays unowned for the
3462 // next request to claim.
3463 let deadline =
3464 rebalance.then(|| std::time::Duration::from_millis(self.operation_deadline_ms));
3465 out.spawn_scoped(async move {
3466 let started_mono_ms = crate::asyncrt::mono_ms();
3467 let request = HandoffRequest {
3468 cell: cell.clone(),
3469 released_epoch,
3470 };
3471 let mut attempts = 0_u64;
3472 let adoption = async { loop {
3473 let peers =
3474 handoff_candidates(&ownership, &directory, &source, &cell, rebalance)
3475 .await
3476 .unwrap_or_default();
3477 for peer in peers {
3478 let mut target = AdoptedCell {
3479 node: peer.node,
3480 addr: peer.addr,
3481 epoch: 0,
3482 peer_protocol: peer.peer_protocol,
3483 };
3484 let mut visited = BTreeSet::new();
3485 for _ in 0..4 {
3486 if target.node == source
3487 || target.addr.is_empty()
3488 || target.peer_protocol != peer_auth::PROTOCOL_VERSION
3489 || !visited.insert(target.node.clone())
3490 {
3491 break;
3492 }
3493 attempts = attempts.saturating_add(1);
3494 match request_peer_handoff(&http, &auth, &target, &request).await {
3495 Ok(HandoffAttempt::Accepted(adopted))
3496 if adopted.epoch > released_epoch =>
3497 {
3498 tracing::info!(
3499 event = "cell_handoff_accepted",
3500 %cell,
3501 released_epoch,
3502 successor = %adopted.node,
3503 successor_epoch = adopted.epoch,
3504 attempts,
3505 elapsed_ms = crate::asyncrt::mono_ms()
3506 .saturating_sub(started_mono_ms),
3507 "successor acquired a released cell for demand-driven restore"
3508 );
3509 return CompletedEffect::plain(Event::SuccessorAdopted {
3510 op,
3511 result: Ok(adopted),
3512 });
3513 }
3514 Ok(HandoffAttempt::CurrentOwner(owner)) => {
3515 target = owner;
3516 }
3517 Ok(HandoffAttempt::Accepted(adopted)) => {
3518 tracing::debug!(
3519 event = "cell_handoff_stale_epoch",
3520 %cell,
3521 released_epoch,
3522 successor = %adopted.node,
3523 successor_epoch = adopted.epoch,
3524 attempts,
3525 "successor acknowledged an obsolete ownership epoch"
3526 );
3527 break;
3528 }
3529 Ok(HandoffAttempt::Refused) => {
3530 tracing::debug!(
3531 event = "cell_handoff_refused",
3532 %cell,
3533 released_epoch,
3534 successor = %target.node,
3535 successor_addr = %target.addr,
3536 attempts,
3537 "successor refused a released cell"
3538 );
3539 break;
3540 }
3541 Err(error) => {
3542 tracing::debug!(
3543 event = "cell_handoff_failed",
3544 %cell,
3545 released_epoch,
3546 successor = %target.node,
3547 successor_addr = %target.addr,
3548 attempts,
3549 %error,
3550 "successor handoff request failed"
3551 );
3552 break;
3553 }
3554 }
3555 }
3556 }
3557 // No peer can accept yet. Retain the core permit and
3558 // retry until the process-wide shutdown deadline.
3559 crate::asyncrt::sleep(HANDOFF_RETRY_DELAY).await;
3560 } };
3561 match deadline {
3562 Some(deadline) => crate::asyncrt::timeout(deadline, adoption)
3563 .await
3564 .unwrap_or_else(|_| {
3565 // The cell is left unowned and its next request
3566 // re-reads ownership; the donor's counter shows
3567 // it, and this names the cell and the wait.
3568 tracing::warn!(
3569 event = "rebalance_adoption_timed_out",
3570 %cell,
3571 released_epoch,
3572 deadline_ms = deadline.as_millis() as u64,
3573 "no peer acquired a balanced cell before the deadline"
3574 );
3575 CompletedEffect::plain(Event::SuccessorAdopted {
3576 op,
3577 result: Err(Failure::Definite),
3578 })
3579 }),
3580 None => adoption.await,
3581 }
3582 });
3583 }
3584 Effect::CancelCellActivity {
3585 cell,
3586 requests,
3587 websockets,
3588 alarm,
3589 keep_hibernatable,
3590 } => {
3591 self.handoff_timings
3592 .entry(cell.clone())
3593 .or_insert(HandoffCellTiming {
3594 nominated_mono_ms: crate::asyncrt::mono_ms(),
3595 quiesce_us: None,
3596 durability_us: None,
3597 stop_us: None,
3598 release_us: None,
3599 });
3600 for request in requests {
3601 if let Some((request_id, _)) = self
3602 .drain_pins
3603 .cancel_core_request(request, "shutdown_quiesce")
3604 {
3605 // The handler can answer before its output gate or
3606 // waitUntil work settles. Cancel every pinned phase,
3607 // or that background work can outlive the donor.
3608 if let (Some(runtime), Some(request_id)) = (&self.host, request_id) {
3609 runtime.abort_activity(request_id);
3610 }
3611 }
3612 }
3613 if let (Some(runtime), Some(op)) = (&self.host, alarm) {
3614 runtime.abort_alarm(&cell, op);
3615 }
3616 if !websockets.is_empty() {
3617 if keep_hibernatable {
3618 for websocket in &websockets {
3619 crate::js::ws_close(*websocket, 1012, "service restart");
3620 }
3621 } else {
3622 crate::js::ws_close_scope(&cell, 1012, "service restart");
3623 }
3624 for websocket in websockets {
3625 crate::js::ws_unregister(websocket);
3626 immediate.push_back(Event::WebSocketClosed {
3627 cell: cell.clone(),
3628 websocket,
3629 });
3630 }
3631 }
3632 // The arm gate can finish after the core's earlier alarm
3633 // observation. Refresh once when the cell enters the handoff
3634 // cohort, under the same registry ordering as the reporter.
3635 // An uncovered alarm needs more than another cache read: the
3636 // successor stays dormant after adoption, so await the wake
3637 // entry PUT before telling the core this cell can leave.
3638 if let Some(runtime) = self.host.clone() {
3639 match runtime.alarm_observation(&cell) {
3640 Some((mut alarm, false)) if alarm.at_ms().is_some() => {
3641 let at_ms = alarm.at_ms().unwrap();
3642 out.spawn_scoped(async move {
3643 let started = crate::asyncrt::mono_ms();
3644 // One refresh is not enough for an object
3645 // that re-arms its alarm continuously (the
3646 // `@cloudflare/containers` class does, every
3647 // second on the Sandbox SDK): a completed
3648 // PUT can cover the previous installation
3649 // while the latest remains uncovered. A
3650 // single attempt could hold the cell for
3651 // the whole drain window. Keep refreshing
3652 // the latest snapshot until it is covered.
3653 let mut attempts = 0u32;
3654 let (observed, covered) = loop {
3655 attempts += 1;
3656 let (observed, covered) = runtime
3657 .refresh_handoff_alarm_coverage(&cell, alarm)
3658 .await
3659 .unwrap_or((alarm, false));
3660 let settled = covered || observed.at_ms().is_none();
3661 if settled
3662 || crate::asyncrt::mono_ms().saturating_sub(started)
3663 >= HANDOFF_ALARM_COVERAGE_MS
3664 {
3665 break (observed, covered);
3666 }
3667 crate::asyncrt::sleep(std::time::Duration::from_millis(100))
3668 .await;
3669 alarm = runtime
3670 .alarm_observation(&cell)
3671 .map_or(alarm, |(alarm, _)| alarm);
3672 };
3673 tracing::info!(
3674 event = "handoff_alarm_coverage",
3675 %cell,
3676 at_ms,
3677 covered,
3678 attempts,
3679 elapsed_ms = crate::asyncrt::mono_ms().saturating_sub(started),
3680 "refreshed alarm coverage for graceful handoff"
3681 );
3682 CompletedEffect::plain(Event::AlarmObserved {
3683 cell,
3684 alarm: observed,
3685 covered,
3686 now_ms: now_ms(),
3687 now_mono_ms: crate::asyncrt::mono_ms(),
3688 })
3689 });
3690 }
3691 Some((alarm, covered)) => immediate.push_back(Event::AlarmObserved {
3692 cell,
3693 alarm,
3694 covered,
3695 now_ms: now_ms(),
3696 now_mono_ms: crate::asyncrt::mono_ms(),
3697 }),
3698 None => {}
3699 }
3700 }
3701 }
3702 Effect::Restore { op, cell, spec } => {
3703 self.route_effect_started(&cell);
3704 if let Some(runtime) = self.host.clone() {
3705 let timing_cell = cell.clone();
3706 // A restore downloads, merges, and fsyncs a whole database.
3707 // The drain runs it off the core, which owns the node lease timer.
3708 // Choosing `spawn_detached` over `spawn_scoped` only keeps this
3709 // arm's seeded DST schedule stable (see `StepOutput::spawn_detached`).
3710 out.spawn_detached(async move {
3711 let started = crate::asyncrt::mono_ms();
3712 let result = runtime.restore_cell(&cell, &spec).await.map_err(|error| {
3713 eprintln!("celld restore failed for {cell}: {error:#}");
3714 Failure::Definite
3715 });
3716 CompletedEffect::timed(
3717 Event::RestoreCompleted { op, result },
3718 timing_cell,
3719 RouteStage::Restore,
3720 started,
3721 )
3722 });
3723 } else {
3724 self.record_effect_timing(EffectTiming {
3725 cell,
3726 stage: RouteStage::Restore,
3727 elapsed_us: 0,
3728 });
3729 immediate.push_back(Event::RestoreCompleted {
3730 op,
3731 result: Ok(celld_logic::RestoreOutcome {
3732 restored: false,
3733 alarm: None,
3734 }),
3735 });
3736 }
3737 }
3738 Effect::StartRuntime { op, cell, epoch } => {
3739 self.route_effect_started(&cell);
3740 if let Some(runtime) = self.host.clone() {
3741 let fresh = self
3742 .route_timings
3743 .get(&cell)
3744 .and_then(|timing| timing.fresh)
3745 .unwrap_or(false);
3746 let timing_cell = cell.clone();
3747 out.spawn_scoped(async move {
3748 let started = crate::asyncrt::mono_ms();
3749 let placed = runtime
3750 .start_cell(cell.clone(), epoch, fresh)
3751 .await
3752 .map_err(|error| {
3753 eprintln!("celld runtime start failed for {cell}: {error:#}");
3754 Failure::Definite
3755 });
3756 let isolate = placed.as_ref().ok().map(|(isolate, _)| *isolate);
3757 let generation = placed
3758 .as_ref()
3759 .ok()
3760 .map_or(0, |(_, generation)| *generation);
3761 CompletedEffect::timed(
3762 Event::RuntimeStarted {
3763 op,
3764 isolate,
3765 generation,
3766 result: placed.map(|_| ()),
3767 },
3768 timing_cell,
3769 RouteStage::IsolateStartup,
3770 started,
3771 )
3772 });
3773 } else {
3774 self.record_effect_timing(EffectTiming {
3775 cell,
3776 stage: RouteStage::IsolateStartup,
3777 elapsed_us: 0,
3778 });
3779 immediate.push_back(Event::RuntimeStarted {
3780 op,
3781 isolate: None,
3782 generation: 0,
3783 result: Ok(()),
3784 });
3785 }
3786 }
3787 Effect::Publish { op, cell, epoch } => {
3788 self.route_effect_started(&cell);
3789 let publish_started = crate::asyncrt::mono_ms();
3790 self.publishes += 1;
3791 let result = if self.fail_publish_once {
3792 self.fail_publish_once = false;
3793 Err(Failure::Ambiguous)
3794 } else {
3795 self.host
3796 .as_ref()
3797 .map_or(Ok(()), |runtime| runtime.publish_cell(&cell, epoch))
3798 .map_err(|error| {
3799 eprintln!("celld runtime publication failed for {cell}: {error:#}");
3800 Failure::Definite
3801 })
3802 };
3803 if result.is_ok() {
3804 self.published.insert(cell.clone());
3805 }
3806 self.record_effect_timing(EffectTiming {
3807 cell: cell.clone(),
3808 stage: RouteStage::RegistryInsert,
3809 elapsed_us: mono_elapsed_us(publish_started),
3810 });
3811 if result.is_ok() {
3812 let node = self.state.node().to_string();
3813 self.finish_route(&cell, "activated", "", Some((&node, epoch)));
3814 }
3815 immediate.push_back(Event::Published { op, result });
3816 }
3817 Effect::EvictionAdmission { request, result } => {
3818 let result = match result {
3819 Ok(EvictionAdmission::Pending) => return,
3820 Ok(EvictionAdmission::Absent) => Ok(EvictSuccess::AlreadyAbsent),
3821 Err(error) => Err(error),
3822 };
3823 if let Some(reply) = self.pending_evictions.remove(&request) {
3824 let _ = reply.send(result);
3825 }
3826 }
3827 Effect::EvictionFinished { request, result } => {
3828 if let Some(reply) = self.pending_evictions.remove(&request) {
3829 let _ = reply.send(result);
3830 }
3831 }
3832 Effect::EnsureDurable {
3833 op,
3834 cell,
3835 epoch,
3836 revocable,
3837 } => {
3838 if let Some(timing) = self.handoff_timings.get_mut(&cell) {
3839 if timing.quiesce_us.is_none() {
3840 timing.quiesce_us = Some(mono_elapsed_us(timing.nominated_mono_ms));
3841 }
3842 self.handoff_phase_ops.insert(
3843 op,
3844 (
3845 cell.clone(),
3846 HandoffPhase::Durability,
3847 crate::asyncrt::mono_ms(),
3848 ),
3849 );
3850 }
3851 if let Some(runtime) = self.host.clone() {
3852 // This durability wait runs during a graceful handoff.
3853 // The drain keeps it off the core, which owns the lease timers.
3854 // `spawn_detached` only keeps the seeded DST schedule stable
3855 // (see `StepOutput::spawn_detached`).
3856 out.spawn_detached(async move {
3857 let proved = runtime.ensure_durable(&cell, epoch, revocable).await;
3858 let result = proved.map_err(|error| {
3859 eprintln!(
3860 "celld durability proof failed for {cell} epoch {epoch}: {error:#}"
3861 );
3862 Failure::Ambiguous
3863 });
3864 CompletedEffect::plain(Event::DurabilityChecked { op, result })
3865 });
3866 } else {
3867 immediate.push_back(Event::DurabilityChecked { op, result: Ok(()) });
3868 }
3869 }
3870 // The output gate: prove the cell durable, then let the core release
3871 // the held write response. Reuses the same recency-proving primitive
3872 // as EnsureDurable — a proof issued after the write covers it.
3873 Effect::AwaitDurable {
3874 op,
3875 cell,
3876 epoch,
3877 position,
3878 } => {
3879 if let Some(runtime) = self.host.clone() {
3880 out.spawn_scoped(async move {
3881 // The replicator reports the position it actually
3882 // proved durable and which mechanism proved it; the
3883 // core acks only if the position covers this write,
3884 // and decides per source whether ownership
3885 // verification must run first (Effect::VerifyOwnership).
3886 let (result, source) =
3887 match runtime.await_durable(&cell, epoch, position).await {
3888 Ok((durable, source)) => (Ok(durable), source),
3889 Err(error) => {
3890 eprintln!(
3891 "celld output-gate durability proof failed for {cell} \
3892 epoch {epoch}: {error:#}"
3893 );
3894 (Err(Failure::Ambiguous), celld_logic::ProofSource::Bucket)
3895 }
3896 };
3897 CompletedEffect::plain(Event::DurableReached { op, result, source })
3898 });
3899 } else {
3900 immediate.push_back(Event::DurableReached {
3901 op,
3902 result: Ok(position),
3903 source: celld_logic::ProofSource::Fleet,
3904 });
3905 }
3906 }
3907 Effect::VerifyOwnership { op, cell, epoch } => {
3908 // Verify ownership for bucket-proof acks. Durable in
3909 // `e<epoch>/` is not the same as durable: if the cell has been taken over, that
3910 // prefix is orphaned — the next owner restores a higher
3911 // epoch and this write is gone. A read is enough, and is why
3912 // this is one GET rather than a compare-and-swap: if the
3913 // record still names us, no takeover linearised before this
3914 // read; the LTX went up before it; so any later takeover
3915 // restores from a lineage that already contains the write.
3916 let ownership = self.ownership.clone();
3917 let node = self.state.node().to_string();
3918 out.spawn_scoped(async move {
3919 let result = match ownership.read_owner(&cell).await {
3920 Ok(Some(record))
3921 if record.node.as_deref() == Some(node.as_str())
3922 && record.epoch == epoch =>
3923 {
3924 Ok(())
3925 }
3926 Ok(record) => {
3927 eprintln!(
3928 "celld output gate: {cell} epoch {epoch} is no longer ours \
3929 (record: {record:?}); refusing to acknowledge a write in an \
3930 orphaned epoch"
3931 );
3932 Err(Failure::Definite)
3933 }
3934 Err(failure) => Err(failure),
3935 };
3936 CompletedEffect::plain(Event::OwnershipVerified { op, result })
3937 });
3938 }
3939 // The shell's only per-channel code: how the effect was held, and
3940 // how it is released. Every channel but one takes a durability
3941 // ticket and waits on a oneshot, so they collapse onto one adapter;
3942 // `Sync` holds nothing but the ticket itself, because the effect it
3943 // releases is the handler's promise. Only `WsHibernatable` needs
3944 // another, and only because a socket is an ordered stream whose
3945 // frames must drain in barrier order.
3946 //
3947 // The channel says which way the effect leaves; `ws_gated` says how
3948 // this one is being held. They agree except in one case, and there
3949 // the holding mechanism decides: a frame for a hibernatable socket
3950 // raised OUTSIDE a `webSocketMessage` handler -- from `fetch`, an
3951 // alarm, or `webSocketClose` -- is never captured, so it waits on a
3952 // ticket like every other channel rather than in the cell's barrier
3953 // queue. Routing it to the barrier queue would find no entry and
3954 // strand the task waiting on the ticket.
3955 Effect::Release {
3956 request,
3957 channel,
3958 result,
3959 } => {
3960 let held = HeldOutputKey { request, channel };
3961 match channel {
3962 Channel::WsHibernatable if self.ws_gated.contains_key(&held) => {
3963 self.ws_release(held, result.is_ok())
3964 }
3965 Channel::Response
3966 | Channel::Fetch
3967 | Channel::WsHibernatable
3968 | Channel::WsSelf
3969 | Channel::Service
3970 | Channel::CellRpc
3971 | Channel::R2
3972 | Channel::Tcp
3973 | Channel::Queue
3974 | Channel::Sync => {
3975 if let Some(reply) = self.gated_responses.remove(&held) {
3976 let _ = reply.send(result);
3977 }
3978 }
3979 }
3980 }
3981 Effect::StopRuntime {
3982 op,
3983 cell,
3984 epoch,
3985 cause,
3986 bounded,
3987 } => {
3988 if self.handoff_timings.contains_key(&cell) {
3989 self.handoff_phase_ops.insert(
3990 op,
3991 (cell.clone(), HandoffPhase::Stop, crate::asyncrt::mono_ms()),
3992 );
3993 }
3994 self.stops += 1;
3995 if matches!(cause, StopCause::Swap) {
3996 // A generation swap: the cell leaves its isolate and
3997 // nothing else changes. No durability barrier, no
3998 // replica release, no local unlink -- the same epoch
3999 // starts again on the current generation as soon as the
4000 // core hears the stop.
4001 self.published.remove(&cell);
4002 if let Some(runtime) = self.host.clone() {
4003 let released = cell.clone();
4004 out.spawn_detached(report_stopped_when_released(
4005 op,
4006 cell,
4007 epoch,
4008 "generation_swap_out_retry",
4009 None,
4010 move || {
4011 let runtime = runtime.clone();
4012 let cell = released.clone();
4013 async move { runtime.swap_out_cell(&cell, epoch).await }
4014 },
4015 ));
4016 } else {
4017 immediate.push_back(Event::RuntimeStopped { op });
4018 }
4019 } else {
4020 let evicting = matches!(cause, StopCause::Evict { .. });
4021 if matches!(cause, StopCause::Fence) {
4022 // A fenced cell's wake entry belongs to whoever takes the
4023 // cell over; a retained local belief would collide with
4024 // the new owner's arm/consume traffic on the same key.
4025 crate::js::forget_wake_entry(&cell);
4026 }
4027 // Keep the persistence decision whole. A cleanup still has
4028 // authority, so it makes the closed image a proved local
4029 // base. A fence can only close in place, and a reset must
4030 // discard the database that failed its durability proof.
4031 // Only a bounded eviction gets a signal. A drain or a
4032 // fence has nowhere to put the cell back, so an abandon
4033 // request could change nothing, and the core does not send
4034 // one for either.
4035 let abandon = (evicting && bounded).then(|| {
4036 let signal = Arc::new(crate::replication::EvictionAbandon::default());
4037 self.eviction_abandons.insert(op, signal.clone());
4038 signal
4039 });
4040 let stop_mode = match cause {
4041 StopCause::Evict { rebalance } => crate::runtime::StopMode::Evict {
4042 preserve_local: !rebalance,
4043 abandon,
4044 },
4045 StopCause::Cleanup => crate::runtime::StopMode::Rebase,
4046 StopCause::Fence => crate::runtime::StopMode::CloseInPlace,
4047 StopCause::Reset => crate::runtime::StopMode::Discard,
4048 StopCause::Swap => unreachable!("generation swaps return above"),
4049 };
4050 if evicting {
4051 self.live_load.shed_cells.fetch_add(1, Ordering::Relaxed);
4052 }
4053 self.published.remove(&cell);
4054 if let Some(runtime) = self.host.clone() {
4055 // The drain keeps the stop off the core and its lease timers.
4056 // `spawn_detached` only keeps the seeded DST schedule stable.
4057 // `remove_local` still runs a SQLite close and a rename or unlink
4058 // synchronously on a host runtime worker. Unlike `close_in_place`,
4059 // which uses `asyncrt::blocking`, this work is off the core but
4060 // not isolated from other runtime work.
4061 let released = cell.clone();
4062 let deadline_mono_ms = bounded.then(|| {
4063 crate::asyncrt::mono_ms().saturating_add(self.operation_deadline_ms)
4064 });
4065 out.spawn_detached(report_stopped_when_released(
4066 op,
4067 cell,
4068 epoch,
4069 "stop_runtime_retry",
4070 deadline_mono_ms,
4071 move || {
4072 let runtime = runtime.clone();
4073 let cell = released.clone();
4074 let stop_mode = stop_mode.clone();
4075 async move { runtime.stop_cell(&cell, epoch, stop_mode).await }
4076 },
4077 ));
4078 } else {
4079 immediate.push_back(Event::RuntimeStopped { op });
4080 }
4081 }
4082 }
4083 Effect::AbandonEvictionStop { op, cell } => {
4084 // The stop may already have passed the point where it can
4085 // stop, or may already have finished. Either way this only
4086 // sets a bit that `LtxRepl::evict` reads at the points where
4087 // it can still act on it.
4088 if let Some(signal) = self.eviction_abandons.get(&op) {
4089 signal.request();
4090 tracing::info!(
4091 event = "eviction_abandon_requested",
4092 %cell,
4093 "a request reached a cell whose eviction is stopping it"
4094 );
4095 }
4096 }
4097 Effect::FireAlarm {
4098 op,
4099 cell,
4100 epoch,
4101 scheduled_ms,
4102 } => {
4103 if let Some(runtime) = self.host.clone() {
4104 out.spawn_scoped(async move {
4105 // The shell reports the firing raw: the deadline that
4106 // stands after the handler, whether a wake entry
4107 // covers it, and the position of the consuming
4108 // commit. Proving that commit durable — and this node
4109 // still the owner — is the core's job: it opens the
4110 // same output gate a request's write gets, so one
4111 // question answers for every egress on the cell, and
4112 // the consume-side wake-entry delete leaves only from
4113 // the far side of the proof. On failure the core
4114 // re-arms or resets; either way the entry stays
4115 // discoverable and at-least-once holds.
4116 let result = runtime
4117 .fire_alarm(op, cell.clone(), scheduled_ms)
4118 .await
4119 .map_err(|error| {
4120 eprintln!("celld alarm dispatch failed: {error:#}");
4121 Failure::Definite
4122 });
4123 CompletedEffect::plain(Event::AlarmFinished {
4124 op,
4125 cell,
4126 epoch,
4127 now_ms: now_ms(),
4128 now_mono_ms: crate::asyncrt::mono_ms(),
4129 result,
4130 })
4131 });
4132 } else {
4133 immediate.push_back(Event::AlarmFinished {
4134 op,
4135 cell,
4136 epoch,
4137 now_ms: now_ms(),
4138 now_mono_ms: crate::asyncrt::mono_ms(),
4139 result: Ok((
4140 celld_logic::wake::AlarmSnapshot::without_wake(None),
4141 true,
4142 None,
4143 )),
4144 });
4145 }
4146 }
4147 Effect::Complete { request, result } => {
4148 if let Some(cell) = self.request_cells.remove(&request) {
4149 match &result {
4150 Ok(Route::Remote { node, epoch, .. }) => {
4151 self.finish_route(&cell, "remote_owner", "", Some((node, *epoch)));
4152 // The cell lives elsewhere: its wake entry is no
4153 // longer this node's to track, and a stale local
4154 // belief would collide with the owner's own
4155 // arm/consume traffic on the same key.
4156 crate::js::forget_wake_entry(&cell);
4157 }
4158 Ok(Route::Local) => {
4159 self.finish_route(&cell, "resident_after_wait", "", None);
4160 }
4161 Err(error) => {
4162 self.finish_route(
4163 &cell,
4164 "route_error",
4165 request_error_phase(*error),
4166 None,
4167 );
4168 }
4169 }
4170 }
4171 if let Some(reply) = self.pending.remove(&request) {
4172 let local = result == Ok(Route::Local);
4173 if reply
4174 .send(result.map(|route| Routed { request, route }))
4175 .is_err()
4176 && local
4177 {
4178 immediate.push_back(Event::ActivityFinished { request });
4179 }
4180 }
4181 }
4182 Effect::CompleteWorker { request, route } => {
4183 if let Some(reply) = self.pending_workers.remove(&request) {
4184 let reserved = route.is_some();
4185 if reply.send(WorkerRouted { request, route }).is_err() && reserved {
4186 immediate.push_back(Event::ActivityFinished { request });
4187 }
4188 }
4189 }
4190 Effect::CloseWebSocket { cell, websocket } => {
4191 // The core declined to hold this transport. Drop it and tell
4192 // the core it is gone, so the cell is not left believing it
4193 // has a socket the node already closed.
4194 eprintln!(
4195 "celld refused an outbound WebSocket for {cell}: the cell is \
4196 leaving this node or the node's outbound pin budget is spent"
4197 );
4198 crate::js::ws_unregister(websocket);
4199 immediate.push_back(Event::WebSocketClosed { cell, websocket });
4200 }
4201 Effect::Halt { code, reason } => {
4202 // Say why before going. Self-fencing is the most drastic thing
4203 // this process does, and an exit code on its own leaves an
4204 // operator to guess between a lease it could not renew, a
4205 // replicator that died, and a crash.
4206 match reason {
4207 celld_logic::HaltReason::NodeLeaseExpired => tracing::warn!(
4208 event = "node_lease_watchdog_fence",
4209 code,
4210 "SELF-FENCE: node lease not renewed within TTL — halting"
4211 ),
4212 celld_logic::HaltReason::NodeLeaseMissing => tracing::warn!(
4213 event = "node_lease_record_missing_fence",
4214 code,
4215 "SELF-FENCE: node lease record is missing — halting"
4216 ),
4217 celld_logic::HaltReason::NodeLeaseMismatch => tracing::warn!(
4218 event = "node_lease_record_mismatch_fence",
4219 code,
4220 "SELF-FENCE: node lease record no longer matches this process — halting"
4221 ),
4222 }
4223 let _ = self.fence.send(code);
4224 }
4225 }
4226 }
4227
4228 fn state_json(&self) -> String {
4229 // The lease sample reads counts the load tick last stored. Store them
4230 // now, so the sample below agrees with the state beside it.
4231 let live = &self.live_load;
4232 live.owned_cells
4233 .store(self.state.owned_cells(), Ordering::Relaxed);
4234 live.ownership_confirmed
4235 .store(self.state.ownership_confirmed(), Ordering::Relaxed);
4236 live.resident_cells
4237 .store(self.state.occupied(), Ordering::Relaxed);
4238 live.host_websockets
4239 .store(self.state.host_websockets(), Ordering::Relaxed);
4240 // Keep the raw RSS/in-use pair from one stored sample; a gap can reflect
4241 // allocator retention. The allocator and libc statistics below are read
4242 // live, so they can describe a later instant.
4243 let sample = live.sample();
4244 let load = crate::ownership_store::process_load(live);
4245 let node_load = matches!(&self.ownership, Ownership::Bucket(_))
4246 .then(|| serde_json::to_string(&load).expect("node load serializes"));
4247 let activity = self.state.presence_snapshot().activity;
4248 let residents = self
4249 .state
4250 .residents()
4251 .into_iter()
4252 .map(|cell| format!("{cell:?}"))
4253 .collect::<Vec<_>>()
4254 .join(",");
4255 let published = self
4256 .published
4257 .iter()
4258 .map(|cell| format!("{cell:?}"))
4259 .collect::<Vec<_>>()
4260 .join(",");
4261 // `restoring` is a sum, and a node that refuses cells for a quarter of
4262 // an hour needs its parts. `activating` holds a permit and is doing
4263 // work; `activation_waiting` is queued behind the activation ceiling;
4264 // `capacity_waiting` is queued behind residency. The census says where
4265 // every cell is, which `occupied` cannot: it counts residency, so a
4266 // node part-way through thousands of cold starts reports almost none.
4267 let phases = self
4268 .state
4269 .phase_census()
4270 .into_iter()
4271 .map(|(phase, count)| format!("{phase:?}:{count}"))
4272 .collect::<Vec<_>>()
4273 .join(",");
4274 format!(
4275 "{{\"ownership\":{:?},\"owned_cells\":{},\"occupied\":{},\"quiescing\":{},\"evicting\":{},\"releasing\":{},\"adopting\":{},\"restoring\":{},\"activating\":{},\"activation_waiting\":{},\"capacity_waiting\":{},\"phases\":{{{}}},\"handed_off\":{},\"handoff_failed\":{},\"rebalanced\":{},\"rebalance_failed\":{},\"remote_route_refreshes\":{},\"shedding\":{},\"rss_bytes\":{},\"in_use_bytes\":{},\"allocator\":{},\"libc_malloc\":{},\"cgroup_working_set_bytes\":{},\"cgroup_current_bytes\":{},\"node_load\":{},\"residents\":[{}],\"published\":[{}],\"publishes\":{},\"stops\":{}}}",
4276 self.ownership.name(),
4277 self.state.owned_cells(),
4278 self.state.occupied(),
4279 self.state.quiescing(),
4280 self.state.evicting(),
4281 self.state.releasing(),
4282 self.state.adopting(),
4283 self.state.activation_backlog(),
4284 self.state.activating(),
4285 self.state.activation_waiting().len(),
4286 self.state.waiting().len(),
4287 phases,
4288 activity.handed_off,
4289 activity.handoff_failed,
4290 activity.rebalanced,
4291 activity.rebalance_failed,
4292 activity.remote_route_refreshes,
4293 self.state
4294 .shed_reason()
4295 .map_or_else(|| "null".to_string(), |reason| format!("{reason:?}")),
4296 sample.rss_bytes,
4297 sample.in_use_bytes,
4298 // Read allocator details live. `None` serializes as null, so a
4299 // failed read leaves the rest intact.
4300 serde_json::to_string(&crate::memory::allocator_stats())
4301 .unwrap_or_else(|_| "null".to_string()),
4302 serde_json::to_string(&crate::memory::libc_malloc_stats())
4303 .unwrap_or_else(|_| "null".to_string()),
4304 sample
4305 .cgroup_working_set_bytes
4306 .map_or_else(|| "null".to_string(), |bytes| bytes.to_string()),
4307 sample
4308 .cgroup_current_bytes
4309 .map_or_else(|| "null".to_string(), |bytes| bytes.to_string()),
4310 node_load.unwrap_or_else(|| "null".to_string()),
4311 residents,
4312 published,
4313 self.publishes,
4314 self.stops
4315 )
4316 }
4317
4318 fn begin_route_if_cold(&mut self, cell: &str) {
4319 if !matches!(
4320 self.state.phase(cell),
4321 Some(Phase::Resident { .. } | Phase::EnsuringDurability { .. } | Phase::Remote { .. })
4322 ) {
4323 self.route_timings
4324 .entry(cell.to_string())
4325 .or_insert_with(CellRouteTiming::new);
4326 }
4327 }
4328
4329 fn route_effect_started(&mut self, cell: &str) {
4330 if let Some(timing) = self.route_timings.get_mut(cell) {
4331 timing.effect_started();
4332 }
4333 }
4334
4335 fn observe_capacity_wait(&mut self, cell: &str) {
4336 if matches!(self.state.phase(cell), Some(Phase::WaitingCapacity)) {
4337 if let Some(timing) = self.route_timings.get_mut(cell) {
4338 timing
4339 .capacity_wait_started_mono_ms
4340 .get_or_insert_with(crate::asyncrt::mono_ms);
4341 }
4342 }
4343 }
4344
4345 fn record_effect_timing(&mut self, completed: EffectTiming) {
4346 if let Some(timing) = self.route_timings.get_mut(&completed.cell) {
4347 timing.record(completed.stage, completed.elapsed_us);
4348 }
4349 }
4350
4351 fn finish_route(
4352 &mut self,
4353 cell: &str,
4354 outcome: &str,
4355 failure_phase: &str,
4356 owner: Option<(&str, u64)>,
4357 ) {
4358 let Some(mut timing) = self.route_timings.remove(cell) else {
4359 return;
4360 };
4361 if let Some(started) = timing.capacity_wait_started_mono_ms.take() {
4362 timing.capacity_wait_us = timing
4363 .capacity_wait_us
4364 .saturating_add(mono_elapsed_us(started));
4365 }
4366 let (owner_node, epoch) = owner.unwrap_or(("", 0));
4367 tracing::debug!(
4368 target: "timing",
4369 event = "cell_route_timing",
4370 outcome,
4371 failure_phase,
4372 scope = %cell,
4373 node = %self.state.node(),
4374 region = %self.region,
4375 runtime_version = env!("CARGO_PKG_VERSION"),
4376 owner_node,
4377 epoch,
4378 fresh = timing.fresh.unwrap_or(false),
4379 total_us = mono_elapsed_us(timing.started_mono_ms),
4380 latch_wait_us = timing.latch_wait_us,
4381 ownership_read_us = timing.ownership_read_us,
4382 node_lease_lookup_us = timing.node_lease_lookup_us,
4383 capacity_lookup_us = timing.capacity_lookup_us,
4384 capacity_wait_us = timing.capacity_wait_us,
4385 activation_slot_wait_us = timing.activation_slot_wait_us,
4386 lease_permit_us = timing.lease_permit_us,
4387 ownership_acquire_us = timing.ownership_acquire_us,
4388 replica_discovery_us = timing.replica_discovery_us,
4389 restore_us = timing.restore_us,
4390 isolate_startup_us = timing.isolate_startup_us,
4391 registry_insert_us = timing.registry_insert_us,
4392 "cell route resolved"
4393 );
4394 }
4395}
4396
4397fn request_error_phase(error: RequestError) -> &'static str {
4398 match error {
4399 RequestError::NodeUnavailable | RequestError::NodeFenced => "node_authority",
4400 RequestError::ResolveFailed | RequestError::PeerIncompatible => "ownership_lookup",
4401 RequestError::CapacityExhausted => "capacity_wait",
4402 RequestError::AcquireFailed => "ownership_acquire",
4403 RequestError::RestoreFailed => "restore",
4404 RequestError::RuntimeFailed => "isolate_startup",
4405 RequestError::PublishFailed => "registry_insert",
4406 RequestError::DurabilityUnproven => "output_gate",
4407 }
4408}
4409
4410#[cfg(not(all(test, celld_internal_tests)))]
4411type ActorState = State;
4412
4413#[cfg(not(all(test, celld_internal_tests)))]
4414fn apply_core_event(state: &mut ActorState, event: Event) -> Vec<Effect> {
4415 on_event(state, event)
4416}
4417
4418#[cfg(all(test, celld_internal_tests))]
4419include!(env!("CELLD_INTERNAL_ACTOR_OBSERVERS"));