Diffinery

homeflare/celldpublic

celld/crates/logic/types.rs
1296 lines · 52.2 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 stop returned an error after its retry 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. A pending stop emits no result.
832 RuntimeStopFailed {
833 op: OpId,
834 },
835 /// The host rescued the database for new activity instead of completing
836 /// the eviction. The runtime restarts through the failed-stop path.
837 RuntimeStopCancelled {
838 op: OpId,
839 },
840 /// Attempt a policy eviction without a caller result. Deterministic
841 /// policy drivers use this input; the Actor uses `EvictRequested` so a
842 /// refusal or an interrupted operation cannot look like success.
843 Evict {
844 cell: CellId,
845 },
846 /// Try an explicit eviction now and report admission before its effects
847 /// run, so the executor can bind the caller to the accepted operation.
848 EvictRequested {
849 request: RequestId,
850 cell: CellId,
851 now_mono_ms: u64,
852 },
853 /// A periodic resource sample from the edge.
854 ///
855 /// The core never reads a clock or a proc file; the shell measures and
856 /// hands the numbers over, and every decision that follows -- whether the
857 /// node is overloaded, whether the latch stays hot, how far to shed --
858 /// happens here where a schedule can replay it.
859 LoadSampled {
860 load: pressure::Load,
861 now_mono_ms: u64,
862 },
863 /// Retire an exact cached remote route after a dispatch failure which is
864 /// known not to have executed the request. Newer route generations are
865 /// unaffected by delayed failure reports.
866 InvalidateRemote {
867 cell: CellId,
868 node: NodeId,
869 epoch: Epoch,
870 },
871 NodeFenced,
872 /// The node is shutting down: release every resident cell and wait for a
873 /// successor to publish it. Unlike an on-demand evict this always
874 /// releases, whatever `ownership_on_evict` is set to. Complete handoffs
875 /// run at most `max_releases` at a time, and a cell that is active when
876 /// the drain begins is picked up once its activity finishes.
877 ReleaseAll,
878 /// Give up to `cells` idle cells to the fleet through the shutdown
879 /// handoff pipeline without draining. The core picks dormant cells
880 /// first, then hibernatable residents, and skips any cell with work.
881 Rebalance {
882 cells: usize,
883 },
884}
885
886#[derive(Clone, Debug, PartialEq, Eq)]
887pub enum Route {
888 Local,
889 Remote {
890 node: NodeId,
891 addr: String,
892 epoch: Epoch,
893 peer_protocol: u16,
894 },
895}
896
897/// Exact resident isolate reserved for a top-level Worker request.
898#[derive(Clone, Debug, PartialEq, Eq)]
899pub struct WorkerRoute {
900 pub cell: CellId,
901 pub epoch: Epoch,
902}
903
904#[derive(Clone, Copy, Debug, PartialEq, Eq)]
905pub enum RequestError {
906 NodeUnavailable,
907 ResolveFailed,
908 AcquireFailed,
909 RestoreFailed,
910 RuntimeFailed,
911 PublishFailed,
912 NodeFenced,
913 PeerIncompatible,
914 CapacityExhausted,
915 /// A local write ran but its durability could not be proven, so the
916 /// response must fail rather than falsely acknowledge the write.
917 DurabilityUnproven,
918}
919
920/// A successful local eviction request. A later request can reactivate the cell.
921#[derive(Debug, Clone, Copy, PartialEq, Eq)]
922pub enum EvictSuccess {
923 /// The awaited eviction completes its runtime stop, including for joined callers.
924 Evicted,
925 /// The Actor finds settled local absence without a pending lifecycle transition.
926 AlreadyAbsent,
927}
928
929/// An eviction refused before an operation starts.
930#[derive(Clone, Copy, Debug, PartialEq, Eq)]
931pub enum EvictRefusal {
932 NodeUnavailable,
933 CellActive,
934 CellTransitioning,
935 AlarmImminent,
936 AlarmUncovered,
937 ConcurrencyLimit,
938}
939
940/// An accepted eviction interrupted by a later lifecycle decision.
941#[derive(Clone, Copy, Debug, PartialEq, Eq)]
942pub enum EvictCancellation {
943 Activity,
944 Alarm,
945 NodeFenced,
946}
947
948/// An eviction whose completion could not be established.
949#[derive(Clone, Copy, Debug, PartialEq, Eq)]
950pub enum EvictFailure {
951 Durability,
952 DurabilityTimeout,
953 RuntimeStop,
954 ActorUnavailable,
955 ReplyLost,
956}
957
958/// Refusal and cancellation are expected outcomes, not node malfunctions.
959#[derive(Clone, Copy, Debug, PartialEq, Eq)]
960pub enum EvictError {
961 Refused(EvictRefusal),
962 Cancelled(EvictCancellation),
963 Failed(EvictFailure),
964}
965
966impl EvictError {
967 /// Stable category shared by Rust diagnostics and HTTP responses.
968 pub const fn kind(&self) -> &'static str {
969 match self {
970 Self::Refused(_) => "refused",
971 Self::Cancelled(_) => "cancelled",
972 Self::Failed(_) => "failed",
973 }
974 }
975
976 /// Stable reason code. Debug output cannot define the wire contract,
977 /// because a Rust variant rename must not change operator clients.
978 pub const fn reason(&self) -> &'static str {
979 match self {
980 Self::Refused(EvictRefusal::NodeUnavailable) => "node_unavailable",
981 Self::Refused(EvictRefusal::CellActive) => "cell_active",
982 Self::Refused(EvictRefusal::CellTransitioning) => "cell_transitioning",
983 Self::Refused(EvictRefusal::AlarmImminent) => "alarm_imminent",
984 Self::Refused(EvictRefusal::AlarmUncovered) => "alarm_uncovered",
985 Self::Refused(EvictRefusal::ConcurrencyLimit) => "eviction_limit",
986 Self::Cancelled(EvictCancellation::Activity) => "new_activity",
987 Self::Cancelled(EvictCancellation::Alarm) => "alarm_activity",
988 Self::Cancelled(EvictCancellation::NodeFenced) => "node_fenced",
989 Self::Failed(EvictFailure::Durability) => "durability_failed",
990 Self::Failed(EvictFailure::DurabilityTimeout) => "durability_timeout",
991 Self::Failed(EvictFailure::RuntimeStop) => "runtime_stop_failed",
992 Self::Failed(EvictFailure::ActorUnavailable) => "actor_unavailable",
993 Self::Failed(EvictFailure::ReplyLost) => "reply_lost",
994 }
995 }
996}
997
998impl std::fmt::Display for EvictError {
999 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1000 write!(f, "{}: {}", self.kind(), self.reason())
1001 }
1002}
1003
1004impl std::error::Error for EvictError {}
1005
1006/// Admission of an explicit caller. The core keeps its operation binding.
1007#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1008pub enum EvictionAdmission {
1009 Absent,
1010 Pending,
1011}
1012
1013/// Work performed outside the core. Every asynchronous effect is versioned;
1014/// completion events with an obsolete `op` are ignored.
1015#[derive(Clone, Debug, PartialEq, Eq)]
1016pub enum Effect {
1017 EvictionAdmission {
1018 request: RequestId,
1019 result: Result<EvictionAdmission, EvictError>,
1020 },
1021 /// Settle a caller bound to the completed operation. A later activation
1022 /// or eviction of the same cell cannot change this result.
1023 EvictionFinished {
1024 request: RequestId,
1025 result: Result<EvictSuccess, EvictError>,
1026 },
1027 ScheduleTimer {
1028 timer: Timer,
1029 at_mono_ms: u64,
1030 },
1031 ReadSelfNodeLease {
1032 op: OpId,
1033 },
1034 CasNodeLease {
1035 op: OpId,
1036 guard: CasGuard,
1037 record: NodeLeaseRecord,
1038 /// The prior record's peer-visible expiry for a renewal. The shell
1039 /// uses it to report how much authority remained when the attempt
1040 /// completed. An initial acquisition has no prior authority.
1041 authority_expires_ms: Option<u64>,
1042 },
1043 /// Read the local cell inventory. This is emitted only after the initial
1044 /// node lease CAS replaced the exact certified predecessor generation.
1045 ReadLocalCells,
1046 ReadOwner {
1047 op: OpId,
1048 cell: CellId,
1049 },
1050 ReadNodeLease {
1051 op: OpId,
1052 cell: CellId,
1053 owner: NodeId,
1054 },
1055 /// The takeover interlock, as a core decision (lease-fold): the dead
1056 /// owner's folded log state was not sealed, so its acked tail may
1057 /// exist only on its followers. The executor recovers every
1058 /// non-sealed session of `owner` into the bucket and reports
1059 /// `NodeLogRecovered`; only then does the claim proceed.
1060 RecoverNodeLog {
1061 op: OpId,
1062 cell: CellId,
1063 owner: NodeId,
1064 },
1065 /// Enumerate recent node leases and return their advisory load records.
1066 /// Listing and bounded parallel reads are adapter mechanics; selection,
1067 /// reservations, and exclusions are deterministic core policy.
1068 ReadCapacityPeers {
1069 op: OpId,
1070 cell: CellId,
1071 },
1072 CasOwner {
1073 op: OpId,
1074 cell: CellId,
1075 guard: CasGuard,
1076 epoch: Epoch,
1077 takeover: bool,
1078 },
1079 /// Bring the bucket's wake entry for this cell into line with its alarm.
1080 ///
1081 /// Emitted wherever the alarm settles, which is the only place that
1082 /// knows. An arm needs an entry; a consumed alarm needs its entry gone,
1083 /// or every later due scan finds a hint for an alarm that already fired
1084 /// and wakes a cell with nothing to do. The snapshot retains its source
1085 /// revision through the proof that permits this effect.
1086 ReconcileWakeEntry {
1087 cell: CellId,
1088 alarm: wake::AlarmSnapshot,
1089 },
1090 /// Publish an evicted cell as unowned, keeping its epoch, so the next
1091 /// node to want it can take it without waiting for this one to notice.
1092 ReleaseOwner {
1093 op: OpId,
1094 cell: CellId,
1095 epoch: Epoch,
1096 },
1097 /// Ask a compatible peer to acquire a cell whose owner record was just
1098 /// released. The result acknowledges authority acquisition. Replica
1099 /// restore and runtime publication continue outside the donor's shutdown
1100 /// critical path.
1101 AdoptReleased {
1102 op: OpId,
1103 cell: CellId,
1104 released_epoch: Epoch,
1105 /// A balancing move rather than a drain: the successor must be a
1106 /// peer below its ownership target, and the search is bounded by
1107 /// the operation deadline instead of the process exit.
1108 rebalance: bool,
1109 },
1110 /// Interrupt the activity which existed when a cell entered its shutdown
1111 /// handoff batch. The shell maps core request IDs to handler/body aborts
1112 /// and closes sockets with a restart status.
1113 CancelCellActivity {
1114 cell: CellId,
1115 requests: Vec<RequestId>,
1116 websockets: Vec<WebSocketId>,
1117 /// A firing alarm is a handler without a routed request id. Its exact
1118 /// operation identifies the shell task to cancel, so a late cancel
1119 /// cannot affect the next alarm firing for this cell.
1120 alarm: Option<OpId>,
1121 /// A forced generation swap lists only the regular and outbound
1122 /// sockets, and the cell stays on this node: its hibernatable sockets
1123 /// and auto-response pair survive. A shutdown handoff lists every
1124 /// socket and forgets the pair, because the cell is leaving.
1125 keep_hibernatable: bool,
1126 },
1127 Restore {
1128 op: OpId,
1129 cell: CellId,
1130 spec: RestoreSpec,
1131 },
1132 StartRuntime {
1133 op: OpId,
1134 cell: CellId,
1135 epoch: Epoch,
1136 },
1137 Publish {
1138 op: OpId,
1139 cell: CellId,
1140 epoch: Epoch,
1141 },
1142 /// Prove that every commit made before this effect is recoverable from
1143 /// replica authority. Voluntary eviction cannot begin until this succeeds.
1144 EnsureDurable {
1145 op: OpId,
1146 cell: CellId,
1147 epoch: Epoch,
1148 /// Whether a request that arrives during this proof puts the cell back
1149 /// into service instead of waiting for a successor. The cell still
1150 /// serves while the proof runs, so an arriving request can cancel the
1151 /// eviction. A revocable proof is therefore the last point at which
1152 /// the node can change its mind, so the shell finishes every remote
1153 /// check it needs here rather than after it takes close exclusion. A
1154 /// drain has nowhere to put the cell back, so it pays for no check it
1155 /// does not need.
1156 ///
1157 /// The two cancel sites do not test the same thing, which is worth
1158 /// knowing before either one changes. `request_authorized` refuses to
1159 /// rescue a cell while the node drains. `worker_request` cancels an
1160 /// `EnsuringDurability` eviction with no drain test at all. That
1161 /// asymmetry is safe only because a drain sets this field false: the
1162 /// shell then does no revocable work, so a rescue costs a cancelled
1163 /// proof and nothing more, and `LtxRepl::evict` remains the final
1164 /// authority on whether the cell may be given up.
1165 revocable: bool,
1166 },
1167 /// The output gate: prove the cell's committed `position` is replicated so
1168 /// a withheld local write response can be released. Unlike
1169 /// [`Effect::EnsureDurable`] this is per-request and changes no cell phase,
1170 /// so the cell keeps serving co-resident requests while one response waits.
1171 AwaitDurable {
1172 op: OpId,
1173 cell: CellId,
1174 epoch: Epoch,
1175 position: u64,
1176 },
1177 /// For bucket-proof acknowledgements, read `own.json` and answer whether it
1178 /// still names this node at this epoch. The core holds the gated write
1179 /// until `Event::OwnershipVerified` returns. Fleet-proof acks never
1180 /// emit this — the ensemble seal is their fence.
1181 VerifyOwnership {
1182 op: OpId,
1183 cell: CellId,
1184 epoch: Epoch,
1185 },
1186 StopRuntime {
1187 op: OpId,
1188 cell: CellId,
1189 epoch: Epoch,
1190 cause: StopCause,
1191 /// After a returned error, the shell stops retrying at its deadline
1192 /// and reports `RuntimeStopFailed`. An in-flight release has no
1193 /// timeout. A drain and a fence keep retrying returned errors until
1194 /// the process ends, because their node is leaving.
1195 bounded: bool,
1196 },
1197 /// Give the cell back instead of finishing this eviction stop.
1198 ///
1199 /// A request is waiting on a cell in `Phase::Cleaning`, and the stop that
1200 /// holds it is a bounded eviction, so the node has somewhere to put the
1201 /// cell back. The shell abandons the stop if it can still do so, and it
1202 /// reports `RuntimeStopCancelled`, which restarts the cell on its open
1203 /// database at the epoch it already had.
1204 ///
1205 /// The shell decides whether it is still able to. An eviction that has
1206 /// made its handoff snapshot visible cannot be abandoned: the snapshot is
1207 /// a full image at one txid and it is the successor's restore artifact, so
1208 /// a cell that served past it would leave a later restore reading a
1209 /// complete database that stops short of an acknowledged write. This
1210 /// effect is therefore a request and not an instruction, and a stop that
1211 /// declines it reports `RuntimeStopped` as before.
1212 AbandonEvictionStop {
1213 op: OpId,
1214 cell: CellId,
1215 },
1216 FireAlarm {
1217 op: OpId,
1218 cell: CellId,
1219 epoch: Epoch,
1220 scheduled_ms: i64,
1221 },
1222 Complete {
1223 request: RequestId,
1224 result: Result<Route, RequestError>,
1225 },
1226 /// Release a withheld output now that the writes it can reveal are
1227 /// decided: `Ok` lets it leave, `Err` refuses it. Emitted only for an
1228 /// output the shell held open via [`Event::OutputAt`].
1229 ///
1230 /// `channel` is the one the shell supplied, returned unchanged. It selects
1231 /// which adapter holds this effect and is the only thing the shell needs
1232 /// in order to route the release. No operation id rides along: the shell
1233 /// never learns the one the core assigned, and `(request, channel)` is
1234 /// unique by construction — `State::validate` enforces it.
1235 Release {
1236 request: RequestId,
1237 channel: Channel,
1238 result: Result<(), RequestError>,
1239 },
1240 /// Complete the synchronous resident-selection decision. `None` means
1241 /// the executor must use the ordinary stateless Worker pool.
1242 CompleteWorker {
1243 request: RequestId,
1244 route: Option<WorkerRoute>,
1245 },
1246 /// Refuse a transport the node cannot afford to hold. The shell closes it;
1247 /// the cell carries on without it.
1248 CloseWebSocket {
1249 cell: CellId,
1250 websocket: WebSocketId,
1251 },
1252 Halt {
1253 code: i32,
1254 reason: HaltReason,
1255 },
1256}
1257
1258/// One database encoded by the local cell path.
1259#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
1260pub struct LocalCell {
1261 pub id: CellId,
1262 pub epoch: Epoch,
1263 /// The epoch's database is open-able as it stands, so a clean reload
1264 /// resumes it in place. False for the copy an eviction preserved: it
1265 /// proves the node held the cell, which is what the ownership
1266 /// confirmation after a restart needs, but it is not a resumable
1267 /// epoch. Without it a restarted node confirmed only the cells that
1268 /// were resident when it died and hid every hibernated one.
1269 pub live: bool,
1270}
1271
1272#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1273pub enum StopCause {
1274 Cleanup,
1275 /// `rebalance` means this eviction hands the cell to the fleet: its
1276 /// ownership record is released and the local replica is not worth
1277 /// keeping. An idle eviction is the opposite on both counts -- it
1278 /// keeps the record so the next activation here renames the file into
1279 /// place instead of paying a full remote restore.
1280 Evict {
1281 rebalance: bool,
1282 },
1283 Fence,
1284 /// A durability proof came back negative, so this runtime's memory and its
1285 /// local database may hold writes the bucket does not. celld has just told
1286 /// the caller those writes failed; continuing to serve them is the
1287 /// divergence, not the failure. Stop, keep no local snapshot, and let the
1288 /// next activation restore from the bucket.
1289 Reset,
1290 /// The cell moves to the current application generation. The runtime
1291 /// leaves its isolate and is started again at the same epoch on an
1292 /// isolate of the new generation: no ownership change, no restore, no
1293 /// replication release. The stop reaches the shell as `Cleaning`, and the
1294 /// core answers the stop with `StartRuntime` instead of a terminal phase.
1295 Swap,
1296}