Diffinery

homeflare/celldpublic

celld/crates/logic/types.rs
1305 lines · 52.6 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 /// The output gate for an effect that work already running on this cell
604 /// raised. Only the cell's own isolate raises one, so it belongs to
605 /// admitted work and must not queue behind a swap that waits for that
606 /// same work to finish.
607 GateRequestAt {
608 request: RequestId,
609 cell: CellId,
610 now_mono_ms: u64,
611 },
612 /// Reserve an idle resident isolate for a top-level Worker request. The
613 /// shell falls back to the stateless pool when no resident is available;
614 /// choosing and pinning a resident is lifecycle policy and therefore
615 /// belongs in the replayable core.
616 WorkerRequest {
617 request: RequestId,
618 },
619 /// Stop cold activation work for a planned same-node replacement while
620 /// leaving published runtimes and ownership intact. Late shell completions
621 /// are stale, so a long restore cannot consume the complete shutdown grace
622 /// and disable the certified local-reload path for every resident cell.
623 BeginPreserve,
624 Cancel {
625 request: RequestId,
626 },
627 ActivityFinished {
628 request: RequestId,
629 },
630 /// An effect is ready to leave the process on `channel`, and it can reveal
631 /// this cell's state. The core withholds it until every write it can
632 /// reveal is proven durable. This is the output gate, and the whole of it:
633 /// every channel arrives here and the core does not branch on which.
634 ///
635 /// `position` is `Some` when the event that produced this output advanced
636 /// the cell's committed WAL to it — the output opens its own barrier and
637 /// waits for a proof that covers that position. `position` is `None` when
638 /// the event only read: the output trails the newest barrier already open
639 /// on the cell, because a reader can start after a write commits and
640 /// before its proof lands. Its own start and end positions therefore
641 /// decide nothing. A cell with nothing outstanding releases it at once,
642 /// so an ordinary read pays no durability latency.
643 ///
644 /// `observed` is the committed-write position a read-only output saw when
645 /// it answered, above the cell's published baseline, when a handler had
646 /// advanced it: `None` when the output carries a `position` of its own or
647 /// the cell holds no handler write. The core holds the output until a
648 /// verified proof covers it, so a reader that answers between another
649 /// handler's commit and that handler's ticket waits for the proof the
650 /// writer has not asked for yet.
651 ///
652 /// `epoch` is the activation epoch the shell sampled `position` at, when
653 /// it sampled before the request pinned the cell: an in-handler ticket
654 /// takes its position in the handler's turn and only then acquires a
655 /// request. A reset between the two discards that epoch's unproven writes,
656 /// and the request then activates the next epoch, whose proof cannot cover
657 /// what the ticket asks about. The core refuses a ticket whose epoch is
658 /// not the resident one. `None` when the request was already active on
659 /// the cell at the sample, as the response is: a reset deactivates every
660 /// request of the cell it discards, so a stale one is refused as not
661 /// active rather than by its epoch.
662 Output {
663 request: RequestId,
664 channel: Channel,
665 position: Option<u64>,
666 observed: Option<u64>,
667 epoch: Option<Epoch>,
668 },
669 /// The production output event. The monotonic instant keeps the authority
670 /// decision and the release inseparable when a handler outlives the node
671 /// lease under which it started. Untimed simulations can use [`Event::Output`].
672 ///
673 /// `epoch` and `observed` carry the same values as on [`Event::Output`],
674 /// and the core applies the same rules to them. The production shell sends
675 /// only this variant, so both must travel here too; without them, every
676 /// released ticket in a production build would skip those checks.
677 OutputAt {
678 request: RequestId,
679 channel: Channel,
680 position: Option<u64>,
681 observed: Option<u64>,
682 epoch: Option<Epoch>,
683 now_mono_ms: u64,
684 },
685 /// The shell finished proving a gated write durable. `Ok(position)` reports
686 /// the committed-write position the replica has *actually* proved durable;
687 /// the core acknowledges only when it covers the gated write's position, so
688 /// a replicator that proves less than it was asked to cannot force an early
689 /// ack. `Err` failed the proof outright.
690 ///
691 /// `source` says which mechanism proved it, because the two carry different
692 /// acknowledgement fences. A fleet proof is already arbitrated: a takeover
693 /// seals a follower before restoring, so a stale owner's next ack-all fails
694 /// closed. A bucket proof needs ownership verification before anything
695 /// is revealed.
696 DurableReached {
697 op: OpId,
698 result: Result<u64, Failure>,
699 source: ProofSource,
700 },
701 /// The ownership record still names this node at this epoch
702 /// (`Ok`), or does not, or could not be read.
703 OwnershipVerified {
704 op: OpId,
705 result: Result<(), Failure>,
706 },
707 WebSocketOpened {
708 cell: CellId,
709 websocket: WebSocketId,
710 kind: WebSocketKind,
711 },
712 WebSocketClosed {
713 cell: CellId,
714 websocket: WebSocketId,
715 },
716 AlarmObserved {
717 cell: CellId,
718 alarm: wake::AlarmSnapshot,
719 covered: bool,
720 now_ms: u64,
721 now_mono_ms: u64,
722 },
723 AlarmFinished {
724 op: OpId,
725 /// The cell and epoch the firing was dispatched against. The gate the
726 /// core opens for the consuming commit is keyed by these, and not by
727 /// the alarm's own op: an activity fold can supersede the firing state
728 /// while the handler's write is still unproven, and that write exists
729 /// — and must hold every reader of the cell — regardless.
730 cell: CellId,
731 epoch: Epoch,
732 now_ms: u64,
733 now_mono_ms: u64,
734 /// The deadline standing after the handler ran, whether a wake entry
735 /// covers it, and the position of the consuming commit if the firing
736 /// wrote. The position is sampled last, so it covers the consume
737 /// itself, and the core proves it durable before the alarm settles.
738 result: Result<(wake::AlarmSnapshot, bool, Option<u64>), Failure>,
739 },
740 /// A due wake entry was found for `cell`. `entry_ms` is the minute the
741 /// entry is filed under, so the node that acts on the hint can adopt
742 /// that exact entry; `scope` says how far the hint reaches.
743 WakeHint {
744 cell: CellId,
745 entry_ms: i64,
746 scope: WakeHintScope,
747 },
748 WakeHintAt {
749 cell: CellId,
750 entry_ms: i64,
751 scope: WakeHintScope,
752 now_mono_ms: u64,
753 },
754 OwnerRead {
755 op: OpId,
756 /// Wall-clock observation made when the ownership read completed. It
757 /// bounds reuse of a shared owner-node lease without letting the core
758 /// read a clock itself.
759 now_ms: u64,
760 result: Result<Option<OwnerRecord>, Failure>,
761 },
762 NodeLogRecovered {
763 op: OpId,
764 result: Result<(), Failure>,
765 },
766 /// The log tier changed the folded log object the next lease write
767 /// must carry (lease-fold): renew NOW so the change is durable before
768 /// the caller proceeds. A no-op unless the lease is held.
769 NudgeNodeLease {
770 now_ms: u64,
771 now_mono_ms: u64,
772 },
773 NodeLeaseRead {
774 op: OpId,
775 now_ms: u64,
776 result: Result<Option<NodeLeaseRecord>, Failure>,
777 },
778 CapacityPeersRead {
779 op: OpId,
780 now_ms: u64,
781 result: Result<Vec<CapacityPeer>, Failure>,
782 },
783 OwnerCasCompleted {
784 op: OpId,
785 result: Result<CasOutcome, Failure>,
786 },
787 OwnerReleased {
788 op: OpId,
789 result: Result<CasOutcome, Failure>,
790 },
791 /// A released cell became authoritative on a successor. Its runtime can
792 /// still be warming when this event arrives.
793 SuccessorAdopted {
794 op: OpId,
795 result: Result<AdoptedCell, Failure>,
796 },
797 RestoreCompleted {
798 op: OpId,
799 result: Result<RestoreOutcome, Failure>,
800 },
801 RuntimeStarted {
802 op: OpId,
803 /// The node-wide identity of the V8 heap now holding this cell's
804 /// realm. Placement happens in the shell, so the core has to be told;
805 /// the walk down groups on it to empty a heap rather than scatter its
806 /// cuts across every one. `None` when no runtime placed the cell.
807 isolate: Option<crate::isolate::HeapId>,
808 /// The application generation whose isolate took the cell. The shell
809 /// resolves the generation at placement, and a placement that
810 /// straddled an adoption lands on the previous one; the swap pump
811 /// compares this with the current generation. Zero means the cell
812 /// was never stamped, which the pump treats as stale.
813 generation: u64,
814 result: Result<(), Failure>,
815 },
816 /// The node adopted a new application generation. Every resident cell on
817 /// an older generation moves to it at a safe point, or by force once
818 /// `max_age_ms` has passed since this event. A resident cell whose class
819 /// is in `eager_classes` — the engine's reserved classes, which hold no
820 /// application state worth waiting for — is forced at once.
821 GenerationChanged {
822 generation: u64,
823 now_mono_ms: u64,
824 max_age_ms: u64,
825 eager_classes: Vec<String>,
826 },
827 Published {
828 op: OpId,
829 result: Result<(), Failure>,
830 },
831 DurabilityChecked {
832 op: OpId,
833 result: Result<(), Failure>,
834 },
835 RuntimeStopped {
836 op: OpId,
837 },
838 /// A stop returned an error after its retry deadline. The runtime is
839 /// gone, the database stays open, and the cell restarts on it at the
840 /// same epoch, as a generation swap does. A pending stop emits no result.
841 RuntimeStopFailed {
842 op: OpId,
843 },
844 /// The host rescued the database for new activity instead of completing
845 /// the eviction. The runtime restarts through the failed-stop path.
846 RuntimeStopCancelled {
847 op: OpId,
848 },
849 /// Attempt a policy eviction without a caller result. Deterministic
850 /// policy drivers use this input; the Actor uses `EvictRequested` so a
851 /// refusal or an interrupted operation cannot look like success.
852 Evict {
853 cell: CellId,
854 },
855 /// Try an explicit eviction now and report admission before its effects
856 /// run, so the executor can bind the caller to the accepted operation.
857 EvictRequested {
858 request: RequestId,
859 cell: CellId,
860 now_mono_ms: u64,
861 },
862 /// A periodic resource sample from the edge.
863 ///
864 /// The core never reads a clock or a proc file; the shell measures and
865 /// hands the numbers over, and every decision that follows -- whether the
866 /// node is overloaded, whether the latch stays hot, how far to shed --
867 /// happens here where a schedule can replay it.
868 LoadSampled {
869 load: pressure::Load,
870 now_mono_ms: u64,
871 },
872 /// Retire an exact cached remote route after a dispatch failure which is
873 /// known not to have executed the request. Newer route generations are
874 /// unaffected by delayed failure reports.
875 InvalidateRemote {
876 cell: CellId,
877 node: NodeId,
878 epoch: Epoch,
879 },
880 NodeFenced,
881 /// The node is shutting down: release every resident cell and wait for a
882 /// successor to publish it. Unlike an on-demand evict this always
883 /// releases, whatever `ownership_on_evict` is set to. Complete handoffs
884 /// run at most `max_releases` at a time, and a cell that is active when
885 /// the drain begins is picked up once its activity finishes.
886 ReleaseAll,
887 /// Give up to `cells` idle cells to the fleet through the shutdown
888 /// handoff pipeline without draining. The core picks dormant cells
889 /// first, then hibernatable residents, and skips any cell with work.
890 Rebalance {
891 cells: usize,
892 },
893}
894
895#[derive(Clone, Debug, PartialEq, Eq)]
896pub enum Route {
897 Local,
898 Remote {
899 node: NodeId,
900 addr: String,
901 epoch: Epoch,
902 peer_protocol: u16,
903 },
904}
905
906/// Exact resident isolate reserved for a top-level Worker request.
907#[derive(Clone, Debug, PartialEq, Eq)]
908pub struct WorkerRoute {
909 pub cell: CellId,
910 pub epoch: Epoch,
911}
912
913#[derive(Clone, Copy, Debug, PartialEq, Eq)]
914pub enum RequestError {
915 NodeUnavailable,
916 ResolveFailed,
917 AcquireFailed,
918 RestoreFailed,
919 RuntimeFailed,
920 PublishFailed,
921 NodeFenced,
922 PeerIncompatible,
923 CapacityExhausted,
924 /// A local write ran but its durability could not be proven, so the
925 /// response must fail rather than falsely acknowledge the write.
926 DurabilityUnproven,
927}
928
929/// A successful local eviction request. A later request can reactivate the cell.
930#[derive(Debug, Clone, Copy, PartialEq, Eq)]
931pub enum EvictSuccess {
932 /// The awaited eviction completes its runtime stop, including for joined callers.
933 Evicted,
934 /// The Actor finds settled local absence without a pending lifecycle transition.
935 AlreadyAbsent,
936}
937
938/// An eviction refused before an operation starts.
939#[derive(Clone, Copy, Debug, PartialEq, Eq)]
940pub enum EvictRefusal {
941 NodeUnavailable,
942 CellActive,
943 CellTransitioning,
944 AlarmImminent,
945 AlarmUncovered,
946 ConcurrencyLimit,
947}
948
949/// An accepted eviction interrupted by a later lifecycle decision.
950#[derive(Clone, Copy, Debug, PartialEq, Eq)]
951pub enum EvictCancellation {
952 Activity,
953 Alarm,
954 NodeFenced,
955}
956
957/// An eviction whose completion could not be established.
958#[derive(Clone, Copy, Debug, PartialEq, Eq)]
959pub enum EvictFailure {
960 Durability,
961 DurabilityTimeout,
962 RuntimeStop,
963 ActorUnavailable,
964 ReplyLost,
965}
966
967/// Refusal and cancellation are expected outcomes, not node malfunctions.
968#[derive(Clone, Copy, Debug, PartialEq, Eq)]
969pub enum EvictError {
970 Refused(EvictRefusal),
971 Cancelled(EvictCancellation),
972 Failed(EvictFailure),
973}
974
975impl EvictError {
976 /// Stable category shared by Rust diagnostics and HTTP responses.
977 pub const fn kind(&self) -> &'static str {
978 match self {
979 Self::Refused(_) => "refused",
980 Self::Cancelled(_) => "cancelled",
981 Self::Failed(_) => "failed",
982 }
983 }
984
985 /// Stable reason code. Debug output cannot define the wire contract,
986 /// because a Rust variant rename must not change operator clients.
987 pub const fn reason(&self) -> &'static str {
988 match self {
989 Self::Refused(EvictRefusal::NodeUnavailable) => "node_unavailable",
990 Self::Refused(EvictRefusal::CellActive) => "cell_active",
991 Self::Refused(EvictRefusal::CellTransitioning) => "cell_transitioning",
992 Self::Refused(EvictRefusal::AlarmImminent) => "alarm_imminent",
993 Self::Refused(EvictRefusal::AlarmUncovered) => "alarm_uncovered",
994 Self::Refused(EvictRefusal::ConcurrencyLimit) => "eviction_limit",
995 Self::Cancelled(EvictCancellation::Activity) => "new_activity",
996 Self::Cancelled(EvictCancellation::Alarm) => "alarm_activity",
997 Self::Cancelled(EvictCancellation::NodeFenced) => "node_fenced",
998 Self::Failed(EvictFailure::Durability) => "durability_failed",
999 Self::Failed(EvictFailure::DurabilityTimeout) => "durability_timeout",
1000 Self::Failed(EvictFailure::RuntimeStop) => "runtime_stop_failed",
1001 Self::Failed(EvictFailure::ActorUnavailable) => "actor_unavailable",
1002 Self::Failed(EvictFailure::ReplyLost) => "reply_lost",
1003 }
1004 }
1005}
1006
1007impl std::fmt::Display for EvictError {
1008 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1009 write!(f, "{}: {}", self.kind(), self.reason())
1010 }
1011}
1012
1013impl std::error::Error for EvictError {}
1014
1015/// Admission of an explicit caller. The core keeps its operation binding.
1016#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1017pub enum EvictionAdmission {
1018 Absent,
1019 Pending,
1020}
1021
1022/// Work performed outside the core. Every asynchronous effect is versioned;
1023/// completion events with an obsolete `op` are ignored.
1024#[derive(Clone, Debug, PartialEq, Eq)]
1025pub enum Effect {
1026 EvictionAdmission {
1027 request: RequestId,
1028 result: Result<EvictionAdmission, EvictError>,
1029 },
1030 /// Settle a caller bound to the completed operation. A later activation
1031 /// or eviction of the same cell cannot change this result.
1032 EvictionFinished {
1033 request: RequestId,
1034 result: Result<EvictSuccess, EvictError>,
1035 },
1036 ScheduleTimer {
1037 timer: Timer,
1038 at_mono_ms: u64,
1039 },
1040 ReadSelfNodeLease {
1041 op: OpId,
1042 },
1043 CasNodeLease {
1044 op: OpId,
1045 guard: CasGuard,
1046 record: NodeLeaseRecord,
1047 /// The prior record's peer-visible expiry for a renewal. The shell
1048 /// uses it to report how much authority remained when the attempt
1049 /// completed. An initial acquisition has no prior authority.
1050 authority_expires_ms: Option<u64>,
1051 },
1052 /// Read the local cell inventory. This is emitted only after the initial
1053 /// node lease CAS replaced the exact certified predecessor generation.
1054 ReadLocalCells,
1055 ReadOwner {
1056 op: OpId,
1057 cell: CellId,
1058 },
1059 ReadNodeLease {
1060 op: OpId,
1061 cell: CellId,
1062 owner: NodeId,
1063 },
1064 /// The takeover interlock, as a core decision (lease-fold): the dead
1065 /// owner's folded log state was not sealed, so its acked tail may
1066 /// exist only on its followers. The executor recovers every
1067 /// non-sealed session of `owner` into the bucket and reports
1068 /// `NodeLogRecovered`; only then does the claim proceed.
1069 RecoverNodeLog {
1070 op: OpId,
1071 cell: CellId,
1072 owner: NodeId,
1073 },
1074 /// Enumerate recent node leases and return their advisory load records.
1075 /// Listing and bounded parallel reads are adapter mechanics; selection,
1076 /// reservations, and exclusions are deterministic core policy.
1077 ReadCapacityPeers {
1078 op: OpId,
1079 cell: CellId,
1080 },
1081 CasOwner {
1082 op: OpId,
1083 cell: CellId,
1084 guard: CasGuard,
1085 epoch: Epoch,
1086 takeover: bool,
1087 },
1088 /// Bring the bucket's wake entry for this cell into line with its alarm.
1089 ///
1090 /// Emitted wherever the alarm settles, which is the only place that
1091 /// knows. An arm needs an entry; a consumed alarm needs its entry gone,
1092 /// or every later due scan finds a hint for an alarm that already fired
1093 /// and wakes a cell with nothing to do. The snapshot retains its source
1094 /// revision through the proof that permits this effect.
1095 ReconcileWakeEntry {
1096 cell: CellId,
1097 alarm: wake::AlarmSnapshot,
1098 },
1099 /// Publish an evicted cell as unowned, keeping its epoch, so the next
1100 /// node to want it can take it without waiting for this one to notice.
1101 ReleaseOwner {
1102 op: OpId,
1103 cell: CellId,
1104 epoch: Epoch,
1105 },
1106 /// Ask a compatible peer to acquire a cell whose owner record was just
1107 /// released. The result acknowledges authority acquisition. Replica
1108 /// restore and runtime publication continue outside the donor's shutdown
1109 /// critical path.
1110 AdoptReleased {
1111 op: OpId,
1112 cell: CellId,
1113 released_epoch: Epoch,
1114 /// A balancing move rather than a drain: the successor must be a
1115 /// peer below its ownership target, and the search is bounded by
1116 /// the operation deadline instead of the process exit.
1117 rebalance: bool,
1118 },
1119 /// Interrupt the activity which existed when a cell entered its shutdown
1120 /// handoff batch. The shell maps core request IDs to handler/body aborts
1121 /// and closes sockets with a restart status.
1122 CancelCellActivity {
1123 cell: CellId,
1124 requests: Vec<RequestId>,
1125 websockets: Vec<WebSocketId>,
1126 /// A firing alarm is a handler without a routed request id. Its exact
1127 /// operation identifies the shell task to cancel, so a late cancel
1128 /// cannot affect the next alarm firing for this cell.
1129 alarm: Option<OpId>,
1130 /// A forced generation swap lists only the regular and outbound
1131 /// sockets, and the cell stays on this node: its hibernatable sockets
1132 /// and auto-response pair survive. A shutdown handoff lists every
1133 /// socket and forgets the pair, because the cell is leaving.
1134 keep_hibernatable: bool,
1135 },
1136 Restore {
1137 op: OpId,
1138 cell: CellId,
1139 spec: RestoreSpec,
1140 },
1141 StartRuntime {
1142 op: OpId,
1143 cell: CellId,
1144 epoch: Epoch,
1145 },
1146 Publish {
1147 op: OpId,
1148 cell: CellId,
1149 epoch: Epoch,
1150 },
1151 /// Prove that every commit made before this effect is recoverable from
1152 /// replica authority. Voluntary eviction cannot begin until this succeeds.
1153 EnsureDurable {
1154 op: OpId,
1155 cell: CellId,
1156 epoch: Epoch,
1157 /// Whether a request that arrives during this proof puts the cell back
1158 /// into service instead of waiting for a successor. The cell still
1159 /// serves while the proof runs, so an arriving request can cancel the
1160 /// eviction. A revocable proof is therefore the last point at which
1161 /// the node can change its mind, so the shell finishes every remote
1162 /// check it needs here rather than after it takes close exclusion. A
1163 /// drain has nowhere to put the cell back, so it pays for no check it
1164 /// does not need.
1165 ///
1166 /// The two cancel sites do not test the same thing, which is worth
1167 /// knowing before either one changes. `request_authorized` refuses to
1168 /// rescue a cell while the node drains. `worker_request` cancels an
1169 /// `EnsuringDurability` eviction with no drain test at all. That
1170 /// asymmetry is safe only because a drain sets this field false: the
1171 /// shell then does no revocable work, so a rescue costs a cancelled
1172 /// proof and nothing more, and `LtxRepl::evict` remains the final
1173 /// authority on whether the cell may be given up.
1174 revocable: bool,
1175 },
1176 /// The output gate: prove the cell's committed `position` is replicated so
1177 /// a withheld local write response can be released. Unlike
1178 /// [`Effect::EnsureDurable`] this is per-request and changes no cell phase,
1179 /// so the cell keeps serving co-resident requests while one response waits.
1180 AwaitDurable {
1181 op: OpId,
1182 cell: CellId,
1183 epoch: Epoch,
1184 position: u64,
1185 },
1186 /// For bucket-proof acknowledgements, read `own.json` and answer whether it
1187 /// still names this node at this epoch. The core holds the gated write
1188 /// until `Event::OwnershipVerified` returns. Fleet-proof acks never
1189 /// emit this — the ensemble seal is their fence.
1190 VerifyOwnership {
1191 op: OpId,
1192 cell: CellId,
1193 epoch: Epoch,
1194 },
1195 StopRuntime {
1196 op: OpId,
1197 cell: CellId,
1198 epoch: Epoch,
1199 cause: StopCause,
1200 /// After a returned error, the shell stops retrying at its deadline
1201 /// and reports `RuntimeStopFailed`. An in-flight release has no
1202 /// timeout. A drain and a fence keep retrying returned errors until
1203 /// the process ends, because their node is leaving.
1204 bounded: bool,
1205 },
1206 /// Give the cell back instead of finishing this eviction stop.
1207 ///
1208 /// A request is waiting on a cell in `Phase::Cleaning`, and the stop that
1209 /// holds it is a bounded eviction, so the node has somewhere to put the
1210 /// cell back. The shell abandons the stop if it can still do so, and it
1211 /// reports `RuntimeStopCancelled`, which restarts the cell on its open
1212 /// database at the epoch it already had.
1213 ///
1214 /// The shell decides whether it is still able to. An eviction that has
1215 /// made its handoff snapshot visible cannot be abandoned: the snapshot is
1216 /// a full image at one txid and it is the successor's restore artifact, so
1217 /// a cell that served past it would leave a later restore reading a
1218 /// complete database that stops short of an acknowledged write. This
1219 /// effect is therefore a request and not an instruction, and a stop that
1220 /// declines it reports `RuntimeStopped` as before.
1221 AbandonEvictionStop {
1222 op: OpId,
1223 cell: CellId,
1224 },
1225 FireAlarm {
1226 op: OpId,
1227 cell: CellId,
1228 epoch: Epoch,
1229 scheduled_ms: i64,
1230 },
1231 Complete {
1232 request: RequestId,
1233 result: Result<Route, RequestError>,
1234 },
1235 /// Release a withheld output now that the writes it can reveal are
1236 /// decided: `Ok` lets it leave, `Err` refuses it. Emitted only for an
1237 /// output the shell held open via [`Event::OutputAt`].
1238 ///
1239 /// `channel` is the one the shell supplied, returned unchanged. It selects
1240 /// which adapter holds this effect and is the only thing the shell needs
1241 /// in order to route the release. No operation id rides along: the shell
1242 /// never learns the one the core assigned, and `(request, channel)` is
1243 /// unique by construction — `State::validate` enforces it.
1244 Release {
1245 request: RequestId,
1246 channel: Channel,
1247 result: Result<(), RequestError>,
1248 },
1249 /// Complete the synchronous resident-selection decision. `None` means
1250 /// the executor must use the ordinary stateless Worker pool.
1251 CompleteWorker {
1252 request: RequestId,
1253 route: Option<WorkerRoute>,
1254 },
1255 /// Refuse a transport the node cannot afford to hold. The shell closes it;
1256 /// the cell carries on without it.
1257 CloseWebSocket {
1258 cell: CellId,
1259 websocket: WebSocketId,
1260 },
1261 Halt {
1262 code: i32,
1263 reason: HaltReason,
1264 },
1265}
1266
1267/// One database encoded by the local cell path.
1268#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
1269pub struct LocalCell {
1270 pub id: CellId,
1271 pub epoch: Epoch,
1272 /// The epoch's database is open-able as it stands, so a clean reload
1273 /// resumes it in place. False for the copy an eviction preserved: it
1274 /// proves the node held the cell, which is what the ownership
1275 /// confirmation after a restart needs, but it is not a resumable
1276 /// epoch. Without it a restarted node confirmed only the cells that
1277 /// were resident when it died and hid every hibernated one.
1278 pub live: bool,
1279}
1280
1281#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1282pub enum StopCause {
1283 Cleanup,
1284 /// `rebalance` means this eviction hands the cell to the fleet: its
1285 /// ownership record is released and the local replica is not worth
1286 /// keeping. An idle eviction is the opposite on both counts -- it
1287 /// keeps the record so the next activation here renames the file into
1288 /// place instead of paying a full remote restore.
1289 Evict {
1290 rebalance: bool,
1291 },
1292 Fence,
1293 /// A durability proof came back negative, so this runtime's memory and its
1294 /// local database may hold writes the bucket does not. celld has just told
1295 /// the caller those writes failed; continuing to serve them is the
1296 /// divergence, not the failure. Stop, keep no local snapshot, and let the
1297 /// next activation restore from the bucket.
1298 Reset,
1299 /// The cell moves to the current application generation. The runtime
1300 /// leaves its isolate and is started again at the same epoch on an
1301 /// isolate of the new generation: no ownership change, no restore, no
1302 /// replication release. The stop reaches the shell as `Cleaning`, and the
1303 /// core answers the stop with `StartRuntime` instead of a terminal phase.
1304 Swap,
1305}