Diffinery

homeflare/celldpublic

celld/crates/logic/types.rs
1184 lines · 48.4 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3//! The vocabulary the core is written in: what it is told, what it
4//! answers with, and the records it reads and writes.
5//!
6//! Everything here is data. `Event` is the only way in, `Effect` the only
7//! way out, and the rest are the shapes those two carry. No decision is
8//! made in this file — that is `State` in the crate root.
9use super::*;
10
11pub type Ms = i64;
12
13pub type CellId = String;
14pub type NodeId = String;
15pub type RequestId = u64;
16pub type WebSocketId = u64;
17pub type OpId = u64;
18pub type Epoch = u64;
19
20/// One runtime that this node can currently serve locally.
21///
22/// Presence is a read-only projection of the decision core, not a second
23/// inventory maintained by an adapter. Keeping the epoch beside the cell ID
24/// lets management and inspection traffic identify the exact fenced runtime.
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub struct PresenceCell {
27 pub id: CellId,
28 pub epoch: Epoch,
29}
30
31/// Cumulative lifecycle decisions exposed to management from the same state
32/// machine that made them. These are advisory counters, but they are not a
33/// second shell-owned model and replay to the same values for the same events.
34#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
35pub struct ActivitySnapshot {
36 pub acquired: u64,
37 pub proxied: u64,
38 pub expired_owner_leases: u64,
39 pub restored: u64,
40 pub advanced_epochs: u64,
41 /// Shutdown handoffs acknowledged after a successor acquired authority.
42 pub handed_off: u64,
43 /// Handoff operations that the executor explicitly rejected. A process
44 /// deadline can terminate before this counter changes.
45 pub handoff_failed: u64,
46 /// Balancing moves a peer acquired. A subset of `handed_off`.
47 pub rebalanced: u64,
48 /// Balancing moves no peer acquired. A subset of `handoff_failed`; the
49 /// cell stayed unowned and its next request re-reads ownership.
50 pub rebalance_failed: u64,
51 /// Cached owner or capacity routes retired after an observed lease
52 /// deadline. Counts one per retirement, including healthy renewals;
53 /// lease-less adoption replies and explicit invalidations do not count.
54 pub remote_route_refreshes: u64,
55}
56
57/// Management-facing lifecycle state derived atomically from [`State`].
58#[derive(Clone, Debug, PartialEq, Eq)]
59pub struct PresenceSnapshot {
60 pub serving: bool,
61 pub cells: Vec<PresenceCell>,
62 pub activity: ActivitySnapshot,
63}
64
65impl PresenceSnapshot {
66 pub fn owned_cells(&self) -> usize {
67 self.cells.len()
68 }
69}
70
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub struct Config {
73 /// Resident cells plus activation reservations may never exceed this.
74 pub max_resident: usize,
75 /// Complete nonresident routes which may be in flight at once.
76 ///
77 /// This is deliberately independent of the stateless Worker pool. A warm
78 /// request consumes no activation slot, while a cold request holds one
79 /// across ownership resolution, capacity waiting, restore, and publish.
80 pub max_activations: usize,
81 /// Evictions that may hold a durability proof in flight at once.
82 ///
83 /// A proof is a round trip to the bucket, so draining a node one cell at a
84 /// time takes the number of cells times that latency -- a node shedding
85 /// five hundred cells against a two hundred millisecond proof refuses
86 /// admission for a minute and a half while it walks down. Bounded
87 /// concurrency is what makes the walk down finish in a time anyone can
88 /// reason about.
89 pub max_evictions: usize,
90 /// Complete cell handoffs in flight at once during shutdown.
91 ///
92 /// `max_evictions` is tuned for a background walk down beside live
93 /// traffic. This permit remains held through durability, release, and
94 /// successor ownership acceptance. The successor's activation ceiling
95 /// bounds the asynchronous restore wave after acceptance.
96 pub max_releases: usize,
97 /// Concurrent outbound WebSockets one cell may hold.
98 ///
99 /// Distinct from the node-wide pin budget, which counts *cells* held
100 /// resident: one socket is enough to pin a cell, so that budget says
101 /// nothing about how many a single cell may open. This bounds what one
102 /// application can consume on its own behalf.
103 pub max_outbound_websockets: usize,
104 /// What an evicted cell's ownership record should say.
105 ///
106 /// Releasing it lets any node take the cell next, which is what makes a
107 /// loaded node shed load rather than merely stop hosting it: keeping the
108 /// record means every later request for that cell still routes here, to a
109 /// node that already decided it has no room. Keeping it is right when the
110 /// local eviction snapshot is the point, because a same-node wake is a
111 /// rename instead of a restore.
112 pub ownership_on_evict: OwnershipOnEvict,
113 /// Production executors require a live self-node lease before serving.
114 /// Deterministic unit slices which do not exercise node authority can
115 /// disable this explicitly.
116 pub require_node_lease: bool,
117 /// Exact cross-node request protocol this process can authenticate and
118 /// understand. A live owner speaking another version is unavailable, not
119 /// stale: incompatibility never authorizes takeover.
120 pub peer_protocol: u16,
121 /// How long an activation effect may remain outstanding before the core
122 /// stops waiting for it.
123 ///
124 /// Without this a swallowed effect is invisible: no event ever arrives, no
125 /// timer is watching, and the request waits forever while every piece of
126 /// state remains perfectly consistent. celld shipped that and parked
127 /// requests past ninety seconds. `None` restores the old behaviour, which
128 /// callers use only when they need to observe an indefinite wait.
129 pub operation_deadline_ms: Option<u64>,
130 /// How long a cell waits after a failed dead-owner log recovery
131 /// before it re-enters ownership resolution.
132 ///
133 /// A recovery fails precisely when the owner just died with a deep
134 /// open log: the survivors' sweep of that log is what the request
135 /// is really waiting for, and a thousand-cell owner measured
136 /// ~155 s of it. Failing the request instead turns that window
137 /// into minutes of hard errors.
138 pub owner_log_recovery_backoff_ms: u64,
139 /// How many failed recovery cycles a cell may retry before its
140 /// requests fail with `ResolveFailed`.
141 ///
142 /// A bound, not a target: the shell's own request lifetimes cut a
143 /// waiting client far earlier. At the default backoff this covers
144 /// the measured sweep above with a wide margin, so the cap only
145 /// fires on a recovery that is truly wedged.
146 pub owner_log_recovery_attempts: u32,
147 /// How close an armed alarm may be before the cell stops being worth
148 /// evicting. Inside this window the wake would cost more than the
149 /// residency it saves, so the cell is held.
150 pub alarm_resident_ms: u64,
151 /// How long a cell may sit unused before the node gives it back, with no
152 /// pressure involved. `None` keeps every cell resident until something
153 /// needs the room.
154 pub idle_evict_ms: Option<u64>,
155 /// Ceilings and low watermarks for load shedding.
156 ///
157 /// `max_resident` is a hard cap on reservations; this is the softer,
158 /// resource-aware question of whether the node is overloaded at all.
159 /// Without it a node has only a cell count to reason about, so it meets
160 /// memory exhaustion by running into it rather than shedding.
161 pub pressure: pressure::PressureConfig,
162}
163
164#[derive(Clone, Debug, PartialEq, Eq)]
165pub struct OwnerRecord {
166 /// `None` is a deliberately released, fenced record. Epochs never reset.
167 pub node: Option<NodeId>,
168 pub epoch: Epoch,
169 pub etag: String,
170}
171
172/// The routing and authority fields read from `nodes/<node>.json`.
173///
174/// The executor samples wall time and returns the verbatim record. The core,
175/// not the storage adapter, decides whether it is live and routable.
176#[derive(Clone, Debug, PartialEq, Eq)]
177pub struct NodeLeaseRecord {
178 pub node: NodeId,
179 pub addr: String,
180 pub expires_ms: u64,
181 pub peer_protocol: u16,
182 /// Per-process generation; production stores this in
183 /// `ownership_index_generation` and, as the same value, in
184 /// `probe_public_key`.
185 pub generation: String,
186 /// The folded node-log state: `None` means this session never opened
187 /// a fleet log — it never acked past the bucket. Anything not sealed
188 /// gates a takeover of this node's cells behind node-log recovery.
189 pub log_state: Option<crate::log_tier::LogState>,
190 /// Object version observed by the read. Empty only in synthetic events.
191 pub etag: String,
192}
193
194/// One advisory fleet-capacity observation returned by the storage shell.
195///
196/// Membership and expiry remain authoritative node-lease facts. Load is only
197/// used to choose where an unowned cell should try to land; the chosen peer
198/// must still atomically admit the handoff before it acquires ownership.
199#[derive(Clone, Debug, PartialEq, Eq)]
200pub struct CapacityPeer {
201 pub node: NodeId,
202 pub addr: String,
203 pub expires_ms: u64,
204 pub peer_protocol: u16,
205 pub sampled_ms: u64,
206 /// Confirmed ownership held by this peer, including dormant cells.
207 /// `None` from a peer that predates this field.
208 pub owned_cells: Option<usize>,
209 /// The share of fleet ownership this peer wants, relative to the other
210 /// weights. `None` from a peer that predates rebalancing.
211 pub placement_weight: Option<u64>,
212 /// The newest bucket format this peer reads (`crate::format`). `None`
213 /// from a peer that predates the field, which reads format 1.
214 pub bucket_format: Option<u16>,
215 pub resident_cells: usize,
216 pub host_websockets: usize,
217 pub rss_bytes: u64,
218 /// The allocator-adjusted RSS fallback for ordinary memory pressure.
219 /// `None` from a peer that predates the field.
220 pub in_use_bytes: Option<u64>,
221 pub pressured: bool,
222 /// Whether every configured memory measurement is below its low
223 /// watermark. `None` from a peer that predates this field.
224 pub memory_headroom: Option<bool>,
225 /// Cold routes that have not finished on this peer.
226 pub restoring: u64,
227 /// This process accepts a signed adoption request and acknowledges it
228 /// after it acquires the cell's next ownership epoch.
229 pub paced_handoff: bool,
230 /// An operator paused balancing on this node. One paused lease stops
231 /// every move in the fleet, so a pause from any node is fleet-wide.
232 pub rebalance_paused: bool,
233 /// This node is handing its cells away. It is not a receiver: for one
234 /// lease lifetime after it empties it would otherwise look like the
235 /// emptiest node in the fleet, and every cell sent to it fails its
236 /// adoption or leaves with the drain.
237 pub draining: bool,
238}
239
240impl CapacityPeer {
241 /// Whether this peer's own load report leaves room for another cell.
242 ///
243 /// The rebalance planner and the handoff executor must return the same
244 /// answer here, so both read this one predicate. The planner counts a
245 /// peer's room before it releases a batch, and the executor offers each
246 /// released cell only to a peer that has room. A peer the planner counts
247 /// and the executor then refuses leaves the cell unowned with its epoch
248 /// retained, because the release CAS runs before the successor acquire
249 /// and nothing puts the record back.
250 ///
251 /// A saturated ingress-only node is the case that breaks a split rule.
252 /// It owns no cells, so it looks like the emptiest receiver in the
253 /// fleet and the planner gives it the largest room, while the executor
254 /// refuses every cell it is offered.
255 pub fn reports_adoption_capacity(&self) -> bool {
256 !self.pressured && self.memory_headroom != Some(false)
257 }
258}
259
260/// A successor that has acquired a released cell.
261///
262/// The executor obtains this only from a signed peer acknowledgement. The
263/// successor can still be restoring the durable replica when it responds.
264#[derive(Clone, Debug, PartialEq, Eq)]
265pub struct AdoptedCell {
266 pub node: NodeId,
267 pub addr: String,
268 pub epoch: Epoch,
269 pub peer_protocol: u16,
270}
271
272#[derive(Clone, Debug, PartialEq, Eq)]
273pub struct NodeLeaseSpec {
274 pub addr: String,
275 pub peer_protocol: u16,
276 pub generation: String,
277 /// The generation named by a clean local reload certificate. An initial
278 /// lease CAS can resume local cells only when it replaces this exact,
279 /// still-live generation.
280 pub resume_generation: Option<String>,
281 pub ttl_ms: u64,
282}
283
284#[derive(Clone, Debug, PartialEq, Eq)]
285pub enum CasGuard {
286 Absent,
287 Match(String),
288}
289
290/// See [`Config::ownership_on_evict`].
291#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
292pub enum OwnershipOnEvict {
293 /// Publish the cell as unowned so any node may take it next.
294 #[default]
295 Release,
296 /// Keep the record, so a same-node wake can reuse the local snapshot.
297 Sticky,
298}
299
300/// Why the node is halting. The shell writes this down: a process that
301/// self-fences and exits without saying why leaves an operator with an exit
302/// code and nothing else.
303#[derive(Clone, Copy, Debug, PartialEq, Eq)]
304pub enum HaltReason {
305 /// The node lease was not renewed inside its TTL, so this node can no
306 /// longer prove it owns anything it is serving.
307 NodeLeaseExpired,
308 /// A renewal readback found no node lease record, so the record that
309 /// published the authority of this process is gone.
310 NodeLeaseMissing,
311 /// A renewal readback found a node lease record that this process can
312 /// neither recognize nor adopt, so it can no longer prove its authority.
313 /// The record can be a foreign replacement, or a late self-authored write
314 /// that carries a stale folded log stamp; the readback cannot tell them
315 /// apart, so the reason names the observation, not an author.
316 NodeLeaseMismatch,
317}
318
319#[derive(Clone, Copy, Debug, PartialEq, Eq)]
320pub enum CasOutcome {
321 Applied,
322 Rejected,
323}
324
325/// Observable result of a successful restore effect. A non-fresh activation
326/// may still discover that no local or replicated database exists; the
327/// adapter reports what happened instead of making the core infer I/O truth.
328#[derive(Clone, Copy, Debug, PartialEq, Eq)]
329pub struct RestoreOutcome {
330 pub restored: bool,
331 /// The alarm the restored database already had armed.
332 ///
333 /// A cell carries its alarm in its own SQLite, so a cell that arrives
334 /// here from another node — or wakes cold — has one the isolate has not
335 /// re-armed yet. Nothing else tells this node about it: the observer
336 /// fires when a *running* isolate calls `setAlarm`, which is exactly the
337 /// case this is not. Without it the mirror reads "no alarm" and every
338 /// residency decision that consults it is wrong in the direction of
339 /// shedding a cell that is about to fire.
340 pub alarm: Option<RestoredAlarm>,
341}
342
343/// See [`RestoreOutcome::alarm`].
344#[derive(Clone, Copy, Debug, PartialEq, Eq)]
345pub struct RestoredAlarm {
346 pub at_ms: i64,
347 /// Whether a durable wake entry already covers it. Read from the same
348 /// flusher the observer consults, not assumed: claiming coverage this
349 /// node cannot prove is how an alarm gets lost across an eviction.
350 pub covered: bool,
351}
352
353#[derive(Clone, Debug, PartialEq, Eq)]
354pub enum LeaseCasOutcome {
355 Applied { etag: String },
356 Rejected,
357}
358
359/// Deterministic timers are versioned effects, not implicit clock reads. A
360/// stale firing from a replaced lease generation is harmless.
361#[derive(Clone, Debug, PartialEq, Eq)]
362pub enum Timer {
363 NodeLeaseRenew {
364 generation: u64,
365 },
366 NodeLeaseFence {
367 generation: u64,
368 },
369 CellAlarm {
370 cell: CellId,
371 generation: u64,
372 },
373 /// Fires if `op` is still outstanding. Identified by operation rather than
374 /// by cell, so a completion that lands first simply leaves a stale timer
375 /// that finds nothing to expire.
376 OperationDeadline {
377 op: OpId,
378 },
379 /// Fires if `cell` is still parked behind the admission gate. Keyed by
380 /// cell because a parked cell has no operation: `OperationDeadline` is
381 /// armed per emitted effect, and parking is the state of having emitted
382 /// none. Without this the queue is the one stall with no bound.
383 QueuedActivation {
384 cell: CellId,
385 generation: u64,
386 },
387 /// Fires to re-enter ownership resolution after a failed dead-owner
388 /// log recovery. Keyed by cell like `QueuedActivation`, because the
389 /// backing-off cell holds no operation; the generation discards a
390 /// stale retry after the cell moved on.
391 OwnerLogRecoveryRetry {
392 cell: CellId,
393 generation: u64,
394 },
395}
396
397/// Every way a cell's state can leave this process, and the one promise the
398/// application treats as if it had.
399///
400/// This enum lists every external route, plus `Sync`. It is deliberately not
401/// `#[non_exhaustive]`, so every exhaustive shell match stops compiling until
402/// somebody decides how a new channel is held and how it is released.
403///
404/// The core stores a channel and hands it back. It never reads it. A `match`
405/// on `Channel` inside `celld-logic` would split one output invariant into a
406/// separate rule for each channel.
407///
408/// An alarm is missing here on purpose, and stays missing. Its consuming
409/// commit does open a barrier -- as `GateOwner::Alarm`, keyed by the cell and
410/// epoch the firing was dispatched against -- but a barrier is not a channel.
411/// The alarm's settlement is not an egress: it is replayed back into the core
412/// rather than released to the shell, it has no request to route by, and the
413/// output gate does not release it to the shell, and it has no request to route
414/// by. A variant here would force the core to match on `Channel` to tell a
415/// release from a replay, which is the one thing this enum exists to prevent.
416#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
417pub enum Channel {
418 /// The answer to the cell event itself: an HTTP response, a cell RPC
419 /// reply, or a peer-served reply. A response whose body streams takes one
420 /// ticket for its head and one more for each chunk, because a chunk the
421 /// producer makes after the release can reveal a later write.
422 Response,
423 /// `fetch()` from a handler to a third party.
424 Fetch,
425 /// A frame from a `webSocketMessage` handler, captured by the host and
426 /// released from the cell's barrier queue.
427 WsHibernatable,
428 /// A frame on a socket the isolate opened and polls itself. It cannot be
429 /// captured, because the handler may be awaiting the reply to the very
430 /// frame being held, so it waits on a durability ticket instead.
431 WsSelf,
432 /// A service-binding call, `env.NAME.fetch()` or its RPC form.
433 Service,
434 /// A call to another cell: its `fetch` or one of its RPC methods.
435 CellRpc,
436 /// An operation that changes an application R2 bucket.
437 R2,
438 /// A connection, write, TLS upgrade, or shutdown on a raw TCP socket.
439 Tcp,
440 /// A leased Queue batch leaving its broker for a consumer Worker.
441 Queue,
442 /// The promise `storage.sync()` returns to the handler. Nothing leaves
443 /// the process on this route, but the application treats the settled
444 /// promise as a durability statement and acts on it through routes the
445 /// gate cannot hold: a log line, local work, or the next checkpoint. A
446 /// promise that settles before the proof lets the application discard a
447 /// recovery path it still needs. So the promise takes the same ticket an
448 /// egress takes, and its release is the promise settling.
449 Sync,
450}
451
452impl Channel {
453 /// Return the diagnostic name for this channel.
454 pub fn as_str(self) -> &'static str {
455 match self {
456 Channel::Response => "response",
457 Channel::Fetch => "fetch",
458 Channel::WsHibernatable => "ws_hibernatable",
459 Channel::WsSelf => "ws_self",
460 Channel::Service => "service",
461 Channel::CellRpc => "cellrpc",
462 Channel::R2 => "r2",
463 Channel::Tcp => "tcp",
464 Channel::Queue => "queue",
465 Channel::Sync => "sync",
466 }
467 }
468}
469
470/// Which mechanism proved a gated write durable. The fences differ: the
471/// fleet's follower ensemble arbitrates (a takeover seals a member first),
472/// the bucket only stores — so bucket proofs verify ownership before any
473/// reveal and fleet proofs do not need that extra read.
474#[derive(Clone, Copy, Debug, PartialEq, Eq)]
475pub enum ProofSource {
476 Fleet,
477 Bucket,
478}
479
480/// Whether a failed operation definitely did not commit or may have committed
481/// before its caller lost the response.
482#[derive(Clone, Copy, Debug, PartialEq, Eq)]
483pub enum Failure {
484 Definite,
485 Ambiguous,
486}
487
488#[derive(Clone, Copy, Debug, PartialEq, Eq)]
489pub enum WebSocketKind {
490 Hibernatable,
491 Regular,
492 /// A transport the cell opened itself with `new WebSocket(url)`. It pins
493 /// its cell exactly as a regular one does -- a live transport cannot move
494 /// with ownership -- but unlike an inbound client socket it is created by
495 /// application code at a rate the application chooses, so how much of the
496 /// node it may hold is budgeted.
497 Outbound,
498}
499
500/// How far a wake hint reaches.
501///
502/// Every node lists the fleet's due wake entries on its tick, but only the
503/// node that holds the advisory waker lease may spend I/O on cells it does not
504/// own. `Owned` is every other node's hint: it wakes a cell this node holds
505/// dormant and does nothing else. `Fleet` is the elected waker's hint (and the
506/// boot scan's): it may probe a cell nobody here owns and take over a dead
507/// owner's cell.
508///
509/// The distinction exists because a hint costs an activation permit and an
510/// owner read before the core can learn the cell is someone else's. The
511/// fleet's due set is O(fleet) while a node's own is O(node), so a node that
512/// probed every fleet entry queued its own alarm wakes behind the fleet's:
513/// measured as a 60 s tail against 32 s on seven nodes (2026-09-01).
514#[derive(Clone, Copy, Debug, PartialEq, Eq)]
515pub enum WakeHintScope {
516 /// Wake a dormant cell this node owns; ignore every other cell.
517 Owned,
518 /// Probe ownership and take over a cell whose owner is gone.
519 Fleet,
520}
521
522#[derive(Clone, Debug, PartialEq, Eq)]
523pub enum Event {
524 StartNodeLease {
525 now_ms: u64,
526 /// The monotonic instant `now_ms` was sampled. The initial lease's
527 /// TTL is anchored here; without it the anchor is 0 and every
528 /// millisecond of pre-actor startup counts against the first
529 /// acquisition (a slow boot then discards a perfectly good lease).
530 now_mono_ms: u64,
531 spec: NodeLeaseSpec,
532 },
533 SelfNodeLeaseRead {
534 op: OpId,
535 now_ms: u64,
536 now_mono_ms: u64,
537 result: Result<Option<NodeLeaseRecord>, Failure>,
538 },
539 NodeLeaseCasCompleted {
540 op: OpId,
541 now_mono_ms: u64,
542 result: Result<LeaseCasOutcome, Failure>,
543 /// The folded log state the shell serialized into THIS attempt's
544 /// body. The shell stamps the body from its own slot at
545 /// serialization time — after the core chose `desired` — so the
546 /// core's readback comparisons must use this value, never its
547 /// pre-attempt belief. `None` means the body carried no log
548 /// object (bucket posture, or a backend that does not fold).
549 stamped_log_state: Option<crate::log_tier::LogState>,
550 },
551 /// The executor scanned the local paths after an exact node-generation
552 /// handoff. These cells retain their existing ownership epochs, so the
553 /// core can materialize them without reading or changing each owner.
554 LocalCellsRead {
555 result: Result<Vec<LocalCell>, Failure>,
556 },
557 TimerFired {
558 timer: Timer,
559 now_ms: u64,
560 now_mono_ms: u64,
561 },
562 Request {
563 request: RequestId,
564 cell: CellId,
565 },
566 /// Production form of [`Event::Request`] with the sampled clocks. Untimed
567 /// model slices retain the compact variant above and use the state's last
568 /// observed clocks.
569 RequestAt {
570 request: RequestId,
571 cell: CellId,
572 now_mono_ms: u64,
573 },
574 /// A peer selected this node as a possible landing place for an unowned
575 /// cell. Unlike ordinary ingress, this request must refuse immediately if
576 /// its advertised capacity has gone stale; waiting here would strand the
577 /// forwarding node instead of letting it traverse another candidate.
578 CapacityRequestAt {
579 request: RequestId,
580 cell: CellId,
581 now_mono_ms: u64,
582 },
583 /// A terminating peer asks this node to acquire an unowned cell. The
584 /// ownership record must move now, but the runtime stays dormant until
585 /// real traffic needs it. This avoids an eager fleet-wide restore wave.
586 HandoffRequestAt {
587 request: RequestId,
588 cell: CellId,
589 now_ms: u64,
590 now_mono_ms: u64,
591 },
592 /// An event from a WebSocket that this cell already owns. A regular or
593 /// outbound WebSocket pins its resident runtime, so its final events must
594 /// still run locally after a shutdown batch marks the cell as quiescing.
595 /// The exact WebSocket identity prevents new traffic from using this path.
596 WebSocketRequestAt {
597 request: RequestId,
598 cell: CellId,
599 websocket: WebSocketId,
600 now_ms: u64,
601 now_mono_ms: u64,
602 },
603 /// Reserve an idle resident isolate for a top-level Worker request. The
604 /// shell falls back to the stateless pool when no resident is available;
605 /// choosing and pinning a resident is lifecycle policy and therefore
606 /// belongs in the replayable core.
607 WorkerRequest {
608 request: RequestId,
609 },
610 /// Stop cold activation work for a planned same-node replacement while
611 /// leaving published runtimes and ownership intact. Late shell completions
612 /// are stale, so a long restore cannot consume the complete shutdown grace
613 /// and disable the certified local-reload path for every resident cell.
614 BeginPreserve,
615 Cancel {
616 request: RequestId,
617 },
618 ActivityFinished {
619 request: RequestId,
620 },
621 /// An effect is ready to leave the process on `channel`, and it can reveal
622 /// this cell's state. The core withholds it until every write it can
623 /// reveal is proven durable. This is the output gate, and the whole of it:
624 /// every channel arrives here and the core does not branch on which.
625 ///
626 /// `position` is `Some` when the event that produced this output advanced
627 /// the cell's committed WAL to it — the output opens its own barrier and
628 /// waits for a proof that covers that position. `position` is `None` when
629 /// the event only read: the output trails the newest barrier already open
630 /// on the cell, because a reader can start after a write commits and
631 /// before its proof lands. Its own start and end positions therefore
632 /// decide nothing. A cell with nothing outstanding releases it at once,
633 /// so an ordinary read pays no durability latency.
634 ///
635 /// `observed` is the committed-write position a read-only output saw when
636 /// it answered, above the cell's published baseline, when a handler had
637 /// advanced it: `None` when the output carries a `position` of its own or
638 /// the cell holds no handler write. The core holds the output until a
639 /// verified proof covers it, so a reader that answers between another
640 /// handler's commit and that handler's ticket waits for the proof the
641 /// writer has not asked for yet.
642 ///
643 /// `epoch` is the activation epoch the shell sampled `position` at, when
644 /// it sampled before the request pinned the cell: an in-handler ticket
645 /// takes its position in the handler's turn and only then acquires a
646 /// request. A reset between the two discards that epoch's unproven writes,
647 /// and the request then activates the next epoch, whose proof cannot cover
648 /// what the ticket asks about. The core refuses a ticket whose epoch is
649 /// not the resident one. `None` when the request was already active on
650 /// the cell at the sample, as the response is: a reset deactivates every
651 /// request of the cell it discards, so a stale one is refused as not
652 /// active rather than by its epoch.
653 Output {
654 request: RequestId,
655 channel: Channel,
656 position: Option<u64>,
657 observed: Option<u64>,
658 epoch: Option<Epoch>,
659 },
660 /// The production output event. The monotonic instant keeps the authority
661 /// decision and the release inseparable when a handler outlives the node
662 /// lease under which it started. Untimed simulations can use [`Event::Output`].
663 ///
664 /// `epoch` and `observed` carry the same values as on [`Event::Output`],
665 /// and the core applies the same rules to them. The production shell sends
666 /// only this variant, so both must travel here too; without them, every
667 /// released ticket in a production build would skip those checks.
668 OutputAt {
669 request: RequestId,
670 channel: Channel,
671 position: Option<u64>,
672 observed: Option<u64>,
673 epoch: Option<Epoch>,
674 now_mono_ms: u64,
675 },
676 /// The shell finished proving a gated write durable. `Ok(position)` reports
677 /// the committed-write position the replica has *actually* proved durable;
678 /// the core acknowledges only when it covers the gated write's position, so
679 /// a replicator that proves less than it was asked to cannot force an early
680 /// ack. `Err` failed the proof outright.
681 ///
682 /// `source` says which mechanism proved it, because the two carry different
683 /// acknowledgement fences. A fleet proof is already arbitrated: a takeover
684 /// seals a follower before restoring, so a stale owner's next ack-all fails
685 /// closed. A bucket proof needs ownership verification before anything
686 /// is revealed.
687 DurableReached {
688 op: OpId,
689 result: Result<u64, Failure>,
690 source: ProofSource,
691 },
692 /// The ownership record still names this node at this epoch
693 /// (`Ok`), or does not, or could not be read.
694 OwnershipVerified {
695 op: OpId,
696 result: Result<(), Failure>,
697 },
698 WebSocketOpened {
699 cell: CellId,
700 websocket: WebSocketId,
701 kind: WebSocketKind,
702 },
703 WebSocketClosed {
704 cell: CellId,
705 websocket: WebSocketId,
706 },
707 AlarmObserved {
708 cell: CellId,
709 alarm: wake::AlarmSnapshot,
710 covered: bool,
711 now_ms: u64,
712 now_mono_ms: u64,
713 },
714 AlarmFinished {
715 op: OpId,
716 /// The cell and epoch the firing was dispatched against. The gate the
717 /// core opens for the consuming commit is keyed by these, and not by
718 /// the alarm's own op: an activity fold can supersede the firing state
719 /// while the handler's write is still unproven, and that write exists
720 /// — and must hold every reader of the cell — regardless.
721 cell: CellId,
722 epoch: Epoch,
723 now_ms: u64,
724 now_mono_ms: u64,
725 /// The deadline standing after the handler ran, whether a wake entry
726 /// covers it, and the position of the consuming commit if the firing
727 /// wrote. The position is sampled last, so it covers the consume
728 /// itself, and the core proves it durable before the alarm settles.
729 result: Result<(wake::AlarmSnapshot, bool, Option<u64>), Failure>,
730 },
731 /// A due wake entry was found for `cell`. `entry_ms` is the minute the
732 /// entry is filed under, so the node that acts on the hint can adopt
733 /// that exact entry; `scope` says how far the hint reaches.
734 WakeHint {
735 cell: CellId,
736 entry_ms: i64,
737 scope: WakeHintScope,
738 },
739 WakeHintAt {
740 cell: CellId,
741 entry_ms: i64,
742 scope: WakeHintScope,
743 now_mono_ms: u64,
744 },
745 OwnerRead {
746 op: OpId,
747 /// Wall-clock observation made when the ownership read completed. It
748 /// bounds reuse of a shared owner-node lease without letting the core
749 /// read a clock itself.
750 now_ms: u64,
751 result: Result<Option<OwnerRecord>, Failure>,
752 },
753 NodeLogRecovered {
754 op: OpId,
755 result: Result<(), Failure>,
756 },
757 /// The log tier changed the folded log object the next lease write
758 /// must carry (lease-fold): renew NOW so the change is durable before
759 /// the caller proceeds. A no-op unless the lease is held.
760 NudgeNodeLease {
761 now_ms: u64,
762 now_mono_ms: u64,
763 },
764 NodeLeaseRead {
765 op: OpId,
766 now_ms: u64,
767 result: Result<Option<NodeLeaseRecord>, Failure>,
768 },
769 CapacityPeersRead {
770 op: OpId,
771 now_ms: u64,
772 result: Result<Vec<CapacityPeer>, Failure>,
773 },
774 OwnerCasCompleted {
775 op: OpId,
776 result: Result<CasOutcome, Failure>,
777 },
778 OwnerReleased {
779 op: OpId,
780 result: Result<CasOutcome, Failure>,
781 },
782 /// A released cell became authoritative on a successor. Its runtime can
783 /// still be warming when this event arrives.
784 SuccessorAdopted {
785 op: OpId,
786 result: Result<AdoptedCell, Failure>,
787 },
788 RestoreCompleted {
789 op: OpId,
790 result: Result<RestoreOutcome, Failure>,
791 },
792 RuntimeStarted {
793 op: OpId,
794 /// The node-wide identity of the V8 heap now holding this cell's
795 /// realm. Placement happens in the shell, so the core has to be told;
796 /// the walk down groups on it to empty a heap rather than scatter its
797 /// cuts across every one. `None` when no runtime placed the cell.
798 isolate: Option<crate::isolate::HeapId>,
799 /// The application generation whose isolate took the cell. The shell
800 /// resolves the generation at placement, and a placement that
801 /// straddled an adoption lands on the previous one; the swap pump
802 /// compares this with the current generation. Zero means the cell
803 /// was never stamped, which the pump treats as stale.
804 generation: u64,
805 result: Result<(), Failure>,
806 },
807 /// The node adopted a new application generation. Every resident cell on
808 /// an older generation moves to it at a safe point, or by force once
809 /// `max_age_ms` has passed since this event. A resident cell whose class
810 /// is in `eager_classes` — the engine's reserved classes, which hold no
811 /// application state worth waiting for — is forced at once.
812 GenerationChanged {
813 generation: u64,
814 now_mono_ms: u64,
815 max_age_ms: u64,
816 eager_classes: Vec<String>,
817 },
818 Published {
819 op: OpId,
820 result: Result<(), Failure>,
821 },
822 DurabilityChecked {
823 op: OpId,
824 result: Result<(), Failure>,
825 },
826 RuntimeStopped {
827 op: OpId,
828 },
829 /// A bounded stop did not complete before its deadline. The runtime is
830 /// gone, the database stays open, and the cell restarts on it at the
831 /// same epoch, as a generation swap does.
832 RuntimeStopFailed {
833 op: OpId,
834 },
835 /// Policy input for this first slice. Later eviction selection emits this
836 /// from the same core rather than an external caller choosing a victim.
837 Evict {
838 cell: CellId,
839 },
840 /// A periodic resource sample from the edge.
841 ///
842 /// The core never reads a clock or a proc file; the shell measures and
843 /// hands the numbers over, and every decision that follows -- whether the
844 /// node is overloaded, whether the latch stays hot, how far to shed --
845 /// happens here where a schedule can replay it.
846 LoadSampled {
847 load: pressure::Load,
848 now_mono_ms: u64,
849 },
850 /// Retire an exact cached remote route after a dispatch failure which is
851 /// known not to have executed the request. Newer route generations are
852 /// unaffected by delayed failure reports.
853 InvalidateRemote {
854 cell: CellId,
855 node: NodeId,
856 epoch: Epoch,
857 },
858 NodeFenced,
859 /// The node is shutting down: release every resident cell and wait for a
860 /// successor to publish it. Unlike an on-demand evict this always
861 /// releases, whatever `ownership_on_evict` is set to. Complete handoffs
862 /// run at most `max_releases` at a time, and a cell that is active when
863 /// the drain begins is picked up once its activity finishes.
864 ReleaseAll,
865 /// Give up to `cells` idle cells to the fleet through the shutdown
866 /// handoff pipeline without draining. The core picks dormant cells
867 /// first, then hibernatable residents, and skips any cell with work.
868 Rebalance {
869 cells: usize,
870 },
871}
872
873#[derive(Clone, Debug, PartialEq, Eq)]
874pub enum Route {
875 Local,
876 Remote {
877 node: NodeId,
878 addr: String,
879 epoch: Epoch,
880 peer_protocol: u16,
881 },
882}
883
884/// Exact resident isolate reserved for a top-level Worker request.
885#[derive(Clone, Debug, PartialEq, Eq)]
886pub struct WorkerRoute {
887 pub cell: CellId,
888 pub epoch: Epoch,
889 /// A pending durability proof made stale by selecting this still-routable
890 /// resident. The executor uses the ID only to release its effect waiter;
891 /// a late completion is ignored by the core's phase check.
892 pub retired_durability: Option<OpId>,
893}
894
895#[derive(Clone, Copy, Debug, PartialEq, Eq)]
896pub enum RequestError {
897 NodeUnavailable,
898 ResolveFailed,
899 AcquireFailed,
900 RestoreFailed,
901 RuntimeFailed,
902 PublishFailed,
903 NodeFenced,
904 PeerIncompatible,
905 CapacityExhausted,
906 /// A local write ran but its durability could not be proven, so the
907 /// response must fail rather than falsely acknowledge the write.
908 DurabilityUnproven,
909}
910
911/// Work performed outside the core. Every asynchronous effect is versioned;
912/// completion events with an obsolete `op` are ignored.
913#[derive(Clone, Debug, PartialEq, Eq)]
914pub enum Effect {
915 ScheduleTimer {
916 timer: Timer,
917 at_mono_ms: u64,
918 },
919 ReadSelfNodeLease {
920 op: OpId,
921 },
922 CasNodeLease {
923 op: OpId,
924 guard: CasGuard,
925 record: NodeLeaseRecord,
926 /// The prior record's peer-visible expiry for a renewal. The shell
927 /// uses it to report how much authority remained when the attempt
928 /// completed. An initial acquisition has no prior authority.
929 authority_expires_ms: Option<u64>,
930 },
931 /// Read the local cell inventory. This is emitted only after the initial
932 /// node lease CAS replaced the exact certified predecessor generation.
933 ReadLocalCells,
934 ReadOwner {
935 op: OpId,
936 cell: CellId,
937 },
938 ReadNodeLease {
939 op: OpId,
940 cell: CellId,
941 owner: NodeId,
942 },
943 /// The takeover interlock, as a core decision (lease-fold): the dead
944 /// owner's folded log state was not sealed, so its acked tail may
945 /// exist only on its followers. The executor recovers every
946 /// non-sealed session of `owner` into the bucket and reports
947 /// `NodeLogRecovered`; only then does the claim proceed.
948 RecoverNodeLog {
949 op: OpId,
950 cell: CellId,
951 owner: NodeId,
952 },
953 /// Enumerate recent node leases and return their advisory load records.
954 /// Listing and bounded parallel reads are adapter mechanics; selection,
955 /// reservations, and exclusions are deterministic core policy.
956 ReadCapacityPeers {
957 op: OpId,
958 cell: CellId,
959 },
960 CasOwner {
961 op: OpId,
962 cell: CellId,
963 guard: CasGuard,
964 epoch: Epoch,
965 takeover: bool,
966 },
967 /// Bring the bucket's wake entry for this cell into line with its alarm.
968 ///
969 /// Emitted wherever the alarm settles, which is the only place that
970 /// knows. An arm needs an entry; a consumed alarm needs its entry gone,
971 /// or every later due scan finds a hint for an alarm that already fired
972 /// and wakes a cell with nothing to do. The snapshot retains its source
973 /// revision through the proof that permits this effect.
974 ReconcileWakeEntry {
975 cell: CellId,
976 alarm: wake::AlarmSnapshot,
977 },
978 /// Publish an evicted cell as unowned, keeping its epoch, so the next
979 /// node to want it can take it without waiting for this one to notice.
980 ReleaseOwner {
981 op: OpId,
982 cell: CellId,
983 epoch: Epoch,
984 },
985 /// Ask a compatible peer to acquire a cell whose owner record was just
986 /// released. The result acknowledges authority acquisition. Replica
987 /// restore and runtime publication continue outside the donor's shutdown
988 /// critical path.
989 AdoptReleased {
990 op: OpId,
991 cell: CellId,
992 released_epoch: Epoch,
993 /// A balancing move rather than a drain: the successor must be a
994 /// peer below its ownership target, and the search is bounded by
995 /// the operation deadline instead of the process exit.
996 rebalance: bool,
997 },
998 /// Interrupt the activity which existed when a cell entered its shutdown
999 /// handoff batch. The shell maps core request IDs to handler/body aborts
1000 /// and closes sockets with a restart status.
1001 CancelCellActivity {
1002 cell: CellId,
1003 requests: Vec<RequestId>,
1004 websockets: Vec<WebSocketId>,
1005 /// A firing alarm is a handler without a routed request id. Its exact
1006 /// operation identifies the shell task to cancel, so a late cancel
1007 /// cannot affect the next alarm firing for this cell.
1008 alarm: Option<OpId>,
1009 /// A forced generation swap lists only the regular and outbound
1010 /// sockets, and the cell stays on this node: its hibernatable sockets
1011 /// and auto-response pair survive. A shutdown handoff lists every
1012 /// socket and forgets the pair, because the cell is leaving.
1013 keep_hibernatable: bool,
1014 },
1015 Restore {
1016 op: OpId,
1017 cell: CellId,
1018 spec: RestoreSpec,
1019 },
1020 StartRuntime {
1021 op: OpId,
1022 cell: CellId,
1023 epoch: Epoch,
1024 },
1025 Publish {
1026 op: OpId,
1027 cell: CellId,
1028 epoch: Epoch,
1029 },
1030 /// Prove that every commit made before this effect is recoverable from
1031 /// replica authority. Voluntary eviction cannot begin until this succeeds.
1032 EnsureDurable {
1033 op: OpId,
1034 cell: CellId,
1035 epoch: Epoch,
1036 /// Whether a request that arrives during this proof puts the cell back
1037 /// into service instead of waiting for a successor. The cell still
1038 /// serves while the proof runs, so an arriving request can cancel the
1039 /// eviction. A revocable proof is therefore the last point at which
1040 /// the node can change its mind, so the shell finishes every remote
1041 /// check it needs here rather than after it takes close exclusion. A
1042 /// drain has nowhere to put the cell back, so it pays for no check it
1043 /// does not need.
1044 ///
1045 /// The two cancel sites do not test the same thing, which is worth
1046 /// knowing before either one changes. `request_authorized` refuses to
1047 /// rescue a cell while the node drains. `worker_request` cancels an
1048 /// `EnsuringDurability` eviction with no drain test at all. That
1049 /// asymmetry is safe only because a drain sets this field false: the
1050 /// shell then does no revocable work, so a rescue costs a cancelled
1051 /// proof and nothing more, and `LtxRepl::evict` remains the final
1052 /// authority on whether the cell may be given up.
1053 revocable: bool,
1054 },
1055 /// The output gate: prove the cell's committed `position` is replicated so
1056 /// a withheld local write response can be released. Unlike
1057 /// [`Effect::EnsureDurable`] this is per-request and changes no cell phase,
1058 /// so the cell keeps serving co-resident requests while one response waits.
1059 AwaitDurable {
1060 op: OpId,
1061 cell: CellId,
1062 epoch: Epoch,
1063 position: u64,
1064 },
1065 /// For bucket-proof acknowledgements, read `own.json` and answer whether it
1066 /// still names this node at this epoch. The core holds the gated write
1067 /// until `Event::OwnershipVerified` returns. Fleet-proof acks never
1068 /// emit this — the ensemble seal is their fence.
1069 VerifyOwnership {
1070 op: OpId,
1071 cell: CellId,
1072 epoch: Epoch,
1073 },
1074 StopRuntime {
1075 op: OpId,
1076 cell: CellId,
1077 epoch: Epoch,
1078 cause: StopCause,
1079 /// The shell gives up after its operation deadline and reports
1080 /// `RuntimeStopFailed`. A drain and a fence retry until the process
1081 /// ends, because their node is leaving; an eviction on a serving
1082 /// node is not worth a cell that never answers again.
1083 bounded: bool,
1084 },
1085 /// Give the cell back instead of finishing this eviction stop.
1086 ///
1087 /// A request is waiting on a cell in `Phase::Cleaning`, and the stop that
1088 /// holds it is a bounded eviction, so the node has somewhere to put the
1089 /// cell back. The shell abandons the stop if it can still do so, and it
1090 /// reports `RuntimeStopFailed`, which restarts the cell on its open
1091 /// database at the epoch it already had.
1092 ///
1093 /// The shell decides whether it is still able to. An eviction that has
1094 /// made its handoff snapshot visible cannot be abandoned: the snapshot is
1095 /// a full image at one txid and it is the successor's restore artifact, so
1096 /// a cell that served past it would leave a later restore reading a
1097 /// complete database that stops short of an acknowledged write. This
1098 /// effect is therefore a request and not an instruction, and a stop that
1099 /// declines it reports `RuntimeStopped` as before.
1100 AbandonEvictionStop {
1101 op: OpId,
1102 cell: CellId,
1103 },
1104 FireAlarm {
1105 op: OpId,
1106 cell: CellId,
1107 epoch: Epoch,
1108 scheduled_ms: i64,
1109 },
1110 Complete {
1111 request: RequestId,
1112 result: Result<Route, RequestError>,
1113 },
1114 /// Release a withheld output now that the writes it can reveal are
1115 /// decided: `Ok` lets it leave, `Err` refuses it. Emitted only for an
1116 /// output the shell held open via [`Event::OutputAt`].
1117 ///
1118 /// `channel` is the one the shell supplied, returned unchanged. It selects
1119 /// which adapter holds this effect and is the only thing the shell needs
1120 /// in order to route the release. No operation id rides along: the shell
1121 /// never learns the one the core assigned, and `(request, channel)` is
1122 /// unique by construction — `State::validate` enforces it.
1123 Release {
1124 request: RequestId,
1125 channel: Channel,
1126 result: Result<(), RequestError>,
1127 },
1128 /// Complete the synchronous resident-selection decision. `None` means
1129 /// the executor must use the ordinary stateless Worker pool.
1130 CompleteWorker {
1131 request: RequestId,
1132 route: Option<WorkerRoute>,
1133 },
1134 /// Refuse a transport the node cannot afford to hold. The shell closes it;
1135 /// the cell carries on without it.
1136 CloseWebSocket {
1137 cell: CellId,
1138 websocket: WebSocketId,
1139 },
1140 Halt {
1141 code: i32,
1142 reason: HaltReason,
1143 },
1144}
1145
1146/// One database encoded by the local cell path.
1147#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
1148pub struct LocalCell {
1149 pub id: CellId,
1150 pub epoch: Epoch,
1151 /// The epoch's database is open-able as it stands, so a clean reload
1152 /// resumes it in place. False for the copy an eviction preserved: it
1153 /// proves the node held the cell, which is what the ownership
1154 /// confirmation after a restart needs, but it is not a resumable
1155 /// epoch. Without it a restarted node confirmed only the cells that
1156 /// were resident when it died and hid every hibernated one.
1157 pub live: bool,
1158}
1159
1160#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1161pub enum StopCause {
1162 Cleanup,
1163 /// `rebalance` means this eviction hands the cell to the fleet: its
1164 /// ownership record is released and the local replica is not worth
1165 /// keeping. An idle eviction is the opposite on both counts -- it
1166 /// keeps the record so the next activation here renames the file into
1167 /// place instead of paying a full remote restore.
1168 Evict {
1169 rebalance: bool,
1170 },
1171 Fence,
1172 /// A durability proof came back negative, so this runtime's memory and its
1173 /// local database may hold writes the bucket does not. celld has just told
1174 /// the caller those writes failed; continuing to serve them is the
1175 /// divergence, not the failure. Stop, keep no local snapshot, and let the
1176 /// next activation restore from the bucket.
1177 Reset,
1178 /// The cell moves to the current application generation. The runtime
1179 /// leaves its isolate and is started again at the same epoch on an
1180 /// isolate of the new generation: no ownership change, no restore, no
1181 /// replication release. The stop reaches the shell as `Cleaning`, and the
1182 /// core answers the stop with `StartRuntime` instead of a terminal phase.
1183 Swap,
1184}