Diffinery

homeflare/celldpublic

celld/crates/logic/types.rs
953 lines · 35.9 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}
47
48/// Management-facing lifecycle state derived atomically from [`State`].
49#[derive(Clone, Debug, PartialEq, Eq)]
50pub struct PresenceSnapshot {
51 pub serving: bool,
52 pub cells: Vec<PresenceCell>,
53 pub activity: ActivitySnapshot,
54}
55
56impl PresenceSnapshot {
57 pub fn owned_cells(&self) -> usize {
58 self.cells.len()
59 }
60}
61
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub struct Config {
64 /// Resident cells plus activation reservations may never exceed this.
65 pub max_resident: usize,
66 /// Complete nonresident routes which may be in flight at once.
67 ///
68 /// This is deliberately independent of the stateless Worker pool. A warm
69 /// request consumes no activation slot, while a cold request holds one
70 /// across ownership resolution, capacity waiting, restore, and publish.
71 pub max_activations: usize,
72 /// Evictions that may hold a durability proof in flight at once.
73 ///
74 /// A proof is a round trip to the bucket, so draining a node one cell at a
75 /// time takes the number of cells times that latency -- a node shedding
76 /// five hundred cells against a two hundred millisecond proof refuses
77 /// admission for a minute and a half while it walks down. Bounded
78 /// concurrency is what makes the walk down finish in a time anyone can
79 /// reason about.
80 pub max_evictions: usize,
81 /// Complete cell handoffs in flight at once during shutdown.
82 ///
83 /// `max_evictions` is tuned for a background walk down beside live
84 /// traffic. This permit remains held through durability, release, and
85 /// successor ownership acceptance. The successor's activation ceiling
86 /// bounds the asynchronous restore wave after acceptance.
87 pub max_releases: usize,
88 /// Concurrent outbound WebSockets one cell may hold.
89 ///
90 /// Distinct from the node-wide pin budget, which counts *cells* held
91 /// resident: one socket is enough to pin a cell, so that budget says
92 /// nothing about how many a single cell may open. This bounds what one
93 /// application can consume on its own behalf.
94 pub max_outbound_websockets: usize,
95 /// What an evicted cell's ownership record should say.
96 ///
97 /// Releasing it lets any node take the cell next, which is what makes a
98 /// loaded node shed load rather than merely stop hosting it: keeping the
99 /// record means every later request for that cell still routes here, to a
100 /// node that already decided it has no room. Keeping it is right when the
101 /// local eviction snapshot is the point, because a same-node wake is a
102 /// rename instead of a restore.
103 pub ownership_on_evict: OwnershipOnEvict,
104 /// Production executors require a live self-node lease before serving.
105 /// Deterministic unit slices which do not exercise node authority can
106 /// disable this explicitly.
107 pub require_node_lease: bool,
108 /// Exact cross-node request protocol this process can authenticate and
109 /// understand. A live owner speaking another version is unavailable, not
110 /// stale: incompatibility never authorizes takeover.
111 pub peer_protocol: u16,
112 /// How long an activation effect may remain outstanding before the core
113 /// stops waiting for it.
114 ///
115 /// Without this a swallowed effect is invisible: no event ever arrives, no
116 /// timer is watching, and the request waits forever while every piece of
117 /// state remains perfectly consistent. celld shipped that and parked
118 /// requests past ninety seconds. `None` restores the old behaviour, which
119 /// callers use only when they need to observe an indefinite wait.
120 pub operation_deadline_ms: Option<u64>,
121 /// How close an armed alarm may be before the cell stops being worth
122 /// evicting. Inside this window the wake would cost more than the
123 /// residency it saves, so the cell is held.
124 pub alarm_resident_ms: u64,
125 /// How long a cell may sit unused before the node gives it back, with no
126 /// pressure involved. `None` keeps every cell resident until something
127 /// needs the room.
128 pub idle_evict_ms: Option<u64>,
129 /// Ceilings and low watermarks for load shedding.
130 ///
131 /// `max_resident` is a hard cap on reservations; this is the softer,
132 /// resource-aware question of whether the node is overloaded at all.
133 /// Without it a node has only a cell count to reason about, so it meets
134 /// memory exhaustion by running into it rather than shedding.
135 pub pressure: pressure::PressureConfig,
136}
137
138#[derive(Clone, Debug, PartialEq, Eq)]
139pub struct OwnerRecord {
140 /// `None` is a deliberately released, fenced record. Epochs never reset.
141 pub node: Option<NodeId>,
142 pub epoch: Epoch,
143 pub etag: String,
144}
145
146/// The routing and authority fields read from `nodes/<node>.json`.
147///
148/// The executor samples wall time and returns the verbatim record. The core,
149/// not the storage adapter, decides whether it is live and routable.
150#[derive(Clone, Debug, PartialEq, Eq)]
151pub struct NodeLeaseRecord {
152 pub node: NodeId,
153 pub addr: String,
154 pub expires_ms: u64,
155 pub peer_protocol: u16,
156 /// Per-process generation; production stores this in
157 /// `ownership_index_generation`.
158 pub generation: String,
159 /// The folded node-log state: `None` means this session never opened
160 /// a fleet log — it never acked past the bucket. Anything not sealed
161 /// gates a takeover of this node's cells behind node-log recovery.
162 pub log_state: Option<crate::log_tier::LogState>,
163 /// Object version observed by the read. Empty only in synthetic events.
164 pub etag: String,
165}
166
167/// One advisory fleet-capacity observation returned by the storage shell.
168///
169/// Membership and expiry remain authoritative node-lease facts. Load is only
170/// used to choose where an unowned cell should try to land; the chosen peer
171/// must still atomically admit the handoff before it acquires ownership.
172#[derive(Clone, Debug, PartialEq, Eq)]
173pub struct CapacityPeer {
174 pub node: NodeId,
175 pub addr: String,
176 pub expires_ms: u64,
177 pub peer_protocol: u16,
178 pub sampled_ms: u64,
179 pub resident_cells: usize,
180 pub host_websockets: usize,
181 pub rss_bytes: u64,
182 /// The allocator-adjusted RSS fallback for ordinary memory pressure.
183 /// `None` from a peer that predates the field.
184 pub in_use_bytes: Option<u64>,
185 pub pressured: bool,
186 /// Whether every configured memory measurement is below its low
187 /// watermark. `None` from a peer that predates this field.
188 pub memory_headroom: Option<bool>,
189 /// Cold routes that have not finished on this peer.
190 pub restoring: u64,
191 /// This process accepts a signed adoption request and acknowledges it
192 /// after it acquires the cell's next ownership epoch.
193 pub paced_handoff: bool,
194}
195
196/// A successor that has acquired a released cell.
197///
198/// The executor obtains this only from a signed peer acknowledgement. The
199/// successor can still be restoring the durable replica when it responds.
200#[derive(Clone, Debug, PartialEq, Eq)]
201pub struct AdoptedCell {
202 pub node: NodeId,
203 pub addr: String,
204 pub epoch: Epoch,
205 pub peer_protocol: u16,
206}
207
208#[derive(Clone, Debug, PartialEq, Eq)]
209pub struct NodeLeaseSpec {
210 pub addr: String,
211 pub peer_protocol: u16,
212 pub generation: String,
213 /// The generation named by a clean local reload certificate. An initial
214 /// lease CAS can resume local cells only when it replaces this exact,
215 /// still-live generation.
216 pub resume_generation: Option<String>,
217 pub ttl_ms: u64,
218}
219
220#[derive(Clone, Debug, PartialEq, Eq)]
221pub enum CasGuard {
222 Absent,
223 Match(String),
224}
225
226/// See [`Config::ownership_on_evict`].
227#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
228pub enum OwnershipOnEvict {
229 /// Publish the cell as unowned so any node may take it next.
230 #[default]
231 Release,
232 /// Keep the record, so a same-node wake can reuse the local snapshot.
233 Sticky,
234}
235
236/// Why the node is halting. The shell writes this down: a process that
237/// self-fences and exits without saying why leaves an operator with an exit
238/// code and nothing else.
239#[derive(Clone, Copy, Debug, PartialEq, Eq)]
240pub enum HaltReason {
241 /// The node lease was not renewed inside its TTL, so this node can no
242 /// longer prove it owns anything it is serving.
243 NodeLeaseExpired,
244}
245
246#[derive(Clone, Copy, Debug, PartialEq, Eq)]
247pub enum CasOutcome {
248 Applied,
249 Rejected,
250}
251
252/// Observable result of a successful restore effect. A non-fresh activation
253/// may still discover that no local or replicated database exists; the
254/// adapter reports what happened instead of making the core infer I/O truth.
255#[derive(Clone, Copy, Debug, PartialEq, Eq)]
256pub struct RestoreOutcome {
257 pub restored: bool,
258 /// The alarm the restored database already had armed.
259 ///
260 /// A cell carries its alarm in its own SQLite, so a cell that arrives
261 /// here from another node — or wakes cold — has one the isolate has not
262 /// re-armed yet. Nothing else tells this node about it: the observer
263 /// fires when a *running* isolate calls `setAlarm`, which is exactly the
264 /// case this is not. Without it the mirror reads "no alarm" and every
265 /// residency decision that consults it is wrong in the direction of
266 /// shedding a cell that is about to fire.
267 pub alarm: Option<RestoredAlarm>,
268}
269
270/// See [`RestoreOutcome::alarm`].
271#[derive(Clone, Copy, Debug, PartialEq, Eq)]
272pub struct RestoredAlarm {
273 pub at_ms: i64,
274 /// Whether a durable wake entry already covers it. Read from the same
275 /// flusher the observer consults, not assumed: claiming coverage this
276 /// node cannot prove is how an alarm gets lost across an eviction.
277 pub covered: bool,
278}
279
280#[derive(Clone, Debug, PartialEq, Eq)]
281pub enum LeaseCasOutcome {
282 Applied { etag: String },
283 Rejected,
284}
285
286/// Deterministic timers are versioned effects, not implicit clock reads. A
287/// stale firing from a replaced lease generation is harmless.
288#[derive(Clone, Debug, PartialEq, Eq)]
289pub enum Timer {
290 NodeLeaseRenew {
291 generation: u64,
292 },
293 NodeLeaseFence {
294 generation: u64,
295 },
296 CellAlarm {
297 cell: CellId,
298 generation: u64,
299 },
300 /// Fires if `op` is still outstanding. Identified by operation rather than
301 /// by cell, so a completion that lands first simply leaves a stale timer
302 /// that finds nothing to expire.
303 OperationDeadline {
304 op: OpId,
305 },
306 /// Fires if `cell` is still parked behind the admission gate. Keyed by
307 /// cell because a parked cell has no operation: `OperationDeadline` is
308 /// armed per emitted effect, and parking is the state of having emitted
309 /// none. Without this the queue is the one stall with no bound.
310 QueuedActivation {
311 cell: CellId,
312 generation: u64,
313 },
314}
315
316/// Every way a cell's state can leave this process.
317///
318/// This enum lists every external route. It is deliberately not
319/// `#[non_exhaustive]`, so every exhaustive shell match stops compiling until
320/// somebody decides how a new channel is held and how it is released.
321///
322/// The core stores a channel and hands it back. It never reads it. A `match`
323/// on `Channel` inside `celld-logic` would split one output invariant into a
324/// separate rule for each channel.
325///
326/// An alarm is missing here on purpose, and stays missing. Its consuming
327/// commit does open a barrier -- as `GateOwner::Alarm`, keyed by the cell and
328/// epoch the firing was dispatched against -- but a barrier is not a channel.
329/// The alarm's settlement is not an egress: it is replayed back into the core
330/// rather than released to the shell, it has no request to route by, and the
331/// output gate does not release it to the shell, and it has no request to route
332/// by. A variant here would force the core to match on `Channel` to tell a
333/// release from a replay, which is the one thing this enum exists to prevent.
334#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
335pub enum Channel {
336 /// The answer to the cell event itself: an HTTP response, a cell RPC
337 /// reply, or a peer-served reply.
338 Response,
339 /// `fetch()` from a handler to a third party.
340 Fetch,
341 /// A frame from a `webSocketMessage` handler, captured by the host and
342 /// released from the cell's barrier queue.
343 WsHibernatable,
344 /// A frame on a socket the isolate opened and polls itself. It cannot be
345 /// captured, because the handler may be awaiting the reply to the very
346 /// frame being held, so it waits on a durability ticket instead.
347 WsSelf,
348 /// A service-binding call, `env.NAME.fetch()` or its RPC form.
349 Service,
350 /// A call to another cell: its `fetch` or one of its RPC methods.
351 CellRpc,
352 /// A leased Queue batch leaving its broker for a consumer Worker.
353 Queue,
354}
355
356impl Channel {
357 /// Return the diagnostic name for this channel.
358 pub fn as_str(self) -> &'static str {
359 match self {
360 Channel::Response => "response",
361 Channel::Fetch => "fetch",
362 Channel::WsHibernatable => "ws_hibernatable",
363 Channel::WsSelf => "ws_self",
364 Channel::Service => "service",
365 Channel::CellRpc => "cellrpc",
366 Channel::Queue => "queue",
367 }
368 }
369}
370
371/// Which mechanism proved a gated write durable. The fences differ: the
372/// fleet's follower ensemble arbitrates (a takeover seals a member first),
373/// the bucket only stores — so bucket proofs verify ownership before any
374/// reveal and fleet proofs do not need that extra read.
375#[derive(Clone, Copy, Debug, PartialEq, Eq)]
376pub enum ProofSource {
377 Fleet,
378 Bucket,
379}
380
381/// Whether a failed operation definitely did not commit or may have committed
382/// before its caller lost the response.
383#[derive(Clone, Copy, Debug, PartialEq, Eq)]
384pub enum Failure {
385 Definite,
386 Ambiguous,
387}
388
389#[derive(Clone, Copy, Debug, PartialEq, Eq)]
390pub enum WebSocketKind {
391 Hibernatable,
392 Regular,
393 /// A transport the cell opened itself with `new WebSocket(url)`. It pins
394 /// its cell exactly as a regular one does -- a live transport cannot move
395 /// with ownership -- but unlike an inbound client socket it is created by
396 /// application code at a rate the application chooses, so how much of the
397 /// node it may hold is budgeted.
398 Outbound,
399}
400
401#[derive(Clone, Debug, PartialEq, Eq)]
402pub enum Event {
403 StartNodeLease {
404 now_ms: u64,
405 /// The monotonic instant `now_ms` was sampled. The initial lease's
406 /// TTL is anchored here; without it the anchor is 0 and every
407 /// millisecond of pre-actor startup counts against the first
408 /// acquisition (a slow boot then discards a perfectly good lease).
409 now_mono_ms: u64,
410 spec: NodeLeaseSpec,
411 },
412 SelfNodeLeaseRead {
413 op: OpId,
414 now_ms: u64,
415 now_mono_ms: u64,
416 result: Result<Option<NodeLeaseRecord>, Failure>,
417 },
418 NodeLeaseCasCompleted {
419 op: OpId,
420 now_mono_ms: u64,
421 result: Result<LeaseCasOutcome, Failure>,
422 /// The folded log state the shell serialized into THIS attempt's
423 /// body. The shell stamps the body from its own slot at
424 /// serialization time — after the core chose `desired` — so the
425 /// core's readback comparisons must use this value, never its
426 /// pre-attempt belief. `None` means the body carried no log
427 /// object (bucket posture, or a backend that does not fold).
428 stamped_log_state: Option<crate::log_tier::LogState>,
429 },
430 /// The executor scanned the local paths after an exact node-generation
431 /// handoff. These cells retain their existing ownership epochs, so the
432 /// core can materialize them without reading or changing each owner.
433 LocalCellsRead {
434 result: Result<Vec<LocalCell>, Failure>,
435 },
436 TimerFired {
437 timer: Timer,
438 now_ms: u64,
439 now_mono_ms: u64,
440 },
441 Request {
442 request: RequestId,
443 cell: CellId,
444 },
445 /// Production form of [`Event::Request`] with the sampled clocks. Untimed
446 /// model slices retain the compact variant above and use the state's last
447 /// observed clocks.
448 RequestAt {
449 request: RequestId,
450 cell: CellId,
451 now_mono_ms: u64,
452 },
453 /// A peer selected this node as a possible landing place for an unowned
454 /// cell. Unlike ordinary ingress, this request must refuse immediately if
455 /// its advertised capacity has gone stale; waiting here would strand the
456 /// forwarding node instead of letting it traverse another candidate.
457 CapacityRequestAt {
458 request: RequestId,
459 cell: CellId,
460 now_mono_ms: u64,
461 },
462 /// A terminating peer asks this node to acquire an unowned cell. The
463 /// ownership record must move now, but the runtime stays dormant until
464 /// real traffic needs it. This avoids an eager fleet-wide restore wave.
465 HandoffRequestAt {
466 request: RequestId,
467 cell: CellId,
468 now_ms: u64,
469 now_mono_ms: u64,
470 },
471 /// An event from a WebSocket that this cell already owns. A regular or
472 /// outbound WebSocket pins its resident runtime, so its final events must
473 /// still run locally after a shutdown batch marks the cell as quiescing.
474 /// The exact WebSocket identity prevents new traffic from using this path.
475 WebSocketRequestAt {
476 request: RequestId,
477 cell: CellId,
478 websocket: WebSocketId,
479 now_ms: u64,
480 now_mono_ms: u64,
481 },
482 /// Reserve an idle resident isolate for a top-level Worker request. The
483 /// shell falls back to the stateless pool when no resident is available;
484 /// choosing and pinning a resident is lifecycle policy and therefore
485 /// belongs in the replayable core.
486 WorkerRequest {
487 request: RequestId,
488 },
489 /// Stop cold activation work for a planned same-node replacement while
490 /// leaving published runtimes and ownership intact. Late shell completions
491 /// are stale, so a long restore cannot consume the complete shutdown grace
492 /// and disable the certified local-reload path for every resident cell.
493 BeginPreserve,
494 Cancel {
495 request: RequestId,
496 },
497 ActivityFinished {
498 request: RequestId,
499 },
500 /// An effect is ready to leave the process on `channel`, and it can reveal
501 /// this cell's state. The core withholds it until every write it can
502 /// reveal is proven durable. This is the output gate, and the whole of it:
503 /// every channel arrives here and the core does not branch on which.
504 ///
505 /// `position` is `Some` when the event that produced this output advanced
506 /// the cell's committed WAL to it — the output opens its own barrier and
507 /// waits for a proof that covers that position. `position` is `None` when
508 /// the event only read: the output trails the newest barrier already open
509 /// on the cell, because a reader can start after a write commits and
510 /// before its proof lands. Its own start and end positions therefore
511 /// decide nothing. A cell with nothing outstanding releases it at once,
512 /// so an ordinary read pays no durability latency.
513 ///
514 /// The epoch is not carried: the core reads it from the pinned cell's
515 /// resident phase, which cannot change while the request holds it.
516 Output {
517 request: RequestId,
518 channel: Channel,
519 position: Option<u64>,
520 },
521 /// The shell finished proving a gated write durable. `Ok(position)` reports
522 /// the committed-write position the replica has *actually* proved durable;
523 /// the core acknowledges only when it covers the gated write's position, so
524 /// a replicator that proves less than it was asked to cannot force an early
525 /// ack. `Err` failed the proof outright.
526 ///
527 /// `source` says which mechanism proved it, because the two carry different
528 /// acknowledgement fences. A fleet proof is already arbitrated: a takeover
529 /// seals a follower before restoring, so a stale owner's next ack-all fails
530 /// closed. A bucket proof needs ownership verification before anything
531 /// is revealed.
532 DurableReached {
533 op: OpId,
534 result: Result<u64, Failure>,
535 source: ProofSource,
536 },
537 /// The ownership record still names this node at this epoch
538 /// (`Ok`), or does not, or could not be read.
539 OwnershipVerified {
540 op: OpId,
541 result: Result<(), Failure>,
542 },
543 WebSocketOpened {
544 cell: CellId,
545 websocket: WebSocketId,
546 kind: WebSocketKind,
547 },
548 WebSocketClosed {
549 cell: CellId,
550 websocket: WebSocketId,
551 },
552 AlarmObserved {
553 cell: CellId,
554 at_ms: Option<i64>,
555 covered: bool,
556 now_ms: u64,
557 now_mono_ms: u64,
558 },
559 AlarmFinished {
560 op: OpId,
561 /// The cell and epoch the firing was dispatched against. The gate the
562 /// core opens for the consuming commit is keyed by these, and not by
563 /// the alarm's own op: an activity fold can supersede the firing state
564 /// while the handler's write is still unproven, and that write exists
565 /// — and must hold every reader of the cell — regardless.
566 cell: CellId,
567 epoch: Epoch,
568 now_ms: u64,
569 now_mono_ms: u64,
570 /// The deadline standing after the handler ran, whether a wake entry
571 /// covers it, and the position of the consuming commit if the firing
572 /// wrote. The position is sampled last, so it covers the consume
573 /// itself, and the core proves it durable before the alarm settles.
574 result: Result<(Option<i64>, bool, Option<u64>), Failure>,
575 },
576 WakeHint {
577 cell: CellId,
578 },
579 WakeHintAt {
580 cell: CellId,
581 now_mono_ms: u64,
582 },
583 OwnerRead {
584 op: OpId,
585 /// Wall-clock observation made when the ownership read completed. It
586 /// bounds reuse of a shared owner-node lease without letting the core
587 /// read a clock itself.
588 now_ms: u64,
589 result: Result<Option<OwnerRecord>, Failure>,
590 },
591 NodeLogRecovered {
592 op: OpId,
593 result: Result<(), Failure>,
594 },
595 /// The log tier changed the folded log object the next lease write
596 /// must carry (lease-fold): renew NOW so the change is durable before
597 /// the caller proceeds. A no-op unless the lease is held.
598 NudgeNodeLease {
599 now_ms: u64,
600 now_mono_ms: u64,
601 },
602 NodeLeaseRead {
603 op: OpId,
604 now_ms: u64,
605 result: Result<Option<NodeLeaseRecord>, Failure>,
606 },
607 CapacityPeersRead {
608 op: OpId,
609 now_ms: u64,
610 result: Result<Vec<CapacityPeer>, Failure>,
611 },
612 OwnerCasCompleted {
613 op: OpId,
614 result: Result<CasOutcome, Failure>,
615 },
616 OwnerReleased {
617 op: OpId,
618 result: Result<CasOutcome, Failure>,
619 },
620 /// A released cell became authoritative on a successor. Its runtime can
621 /// still be warming when this event arrives.
622 SuccessorAdopted {
623 op: OpId,
624 result: Result<AdoptedCell, Failure>,
625 },
626 RestoreCompleted {
627 op: OpId,
628 result: Result<RestoreOutcome, Failure>,
629 },
630 RuntimeStarted {
631 op: OpId,
632 /// The isolate now holding this cell's realm. Placement happens in the
633 /// shell, so the core has to be told; the walk down groups on it to
634 /// empty a heap rather than scatter its cuts across every one. `None`
635 /// when no runtime placed the cell.
636 isolate: Option<crate::isolate::IsolateId>,
637 /// The application generation whose isolate took the cell. The shell
638 /// resolves the generation at placement, and a placement that
639 /// straddled an adoption lands on the previous one; the swap pump
640 /// compares this with the current generation. Zero means the cell
641 /// was never stamped, which the pump treats as stale.
642 generation: u64,
643 result: Result<(), Failure>,
644 },
645 /// The node adopted a new application generation. Every resident cell on
646 /// an older generation moves to it at a safe point, or by force once
647 /// `max_age_ms` has passed since this event. A resident cell whose class
648 /// is in `eager_classes` — the engine's reserved classes, which hold no
649 /// application state worth waiting for — is forced at once.
650 GenerationChanged {
651 generation: u64,
652 now_mono_ms: u64,
653 max_age_ms: u64,
654 eager_classes: Vec<String>,
655 },
656 Published {
657 op: OpId,
658 result: Result<(), Failure>,
659 },
660 DurabilityChecked {
661 op: OpId,
662 result: Result<(), Failure>,
663 },
664 RuntimeStopped {
665 op: OpId,
666 },
667 /// Policy input for this first slice. Later eviction selection emits this
668 /// from the same core rather than an external caller choosing a victim.
669 Evict {
670 cell: CellId,
671 },
672 /// A periodic resource sample from the edge.
673 ///
674 /// The core never reads a clock or a proc file; the shell measures and
675 /// hands the numbers over, and every decision that follows -- whether the
676 /// node is overloaded, whether the latch stays hot, how far to shed --
677 /// happens here where a schedule can replay it.
678 LoadSampled {
679 load: pressure::Load,
680 now_mono_ms: u64,
681 },
682 /// Retire an exact cached remote route after a dispatch failure which is
683 /// known not to have executed the request. Newer route generations are
684 /// unaffected by delayed failure reports.
685 InvalidateRemote {
686 cell: CellId,
687 node: NodeId,
688 epoch: Epoch,
689 },
690 NodeFenced,
691 /// The node is shutting down: release every resident cell and wait for a
692 /// successor to publish it. Unlike an on-demand evict this always
693 /// releases, whatever `ownership_on_evict` is set to. Complete handoffs
694 /// run at most `max_releases` at a time, and a cell that is active when
695 /// the drain begins is picked up once its activity finishes.
696 ReleaseAll,
697}
698
699#[derive(Clone, Debug, PartialEq, Eq)]
700pub enum Route {
701 Local,
702 Remote {
703 node: NodeId,
704 addr: String,
705 epoch: Epoch,
706 peer_protocol: u16,
707 },
708}
709
710/// Exact resident isolate reserved for a top-level Worker request.
711#[derive(Clone, Debug, PartialEq, Eq)]
712pub struct WorkerRoute {
713 pub cell: CellId,
714 pub epoch: Epoch,
715 /// A pending durability proof made stale by selecting this still-routable
716 /// resident. The executor uses the ID only to release its effect waiter;
717 /// a late completion is ignored by the core's phase check.
718 pub retired_durability: Option<OpId>,
719}
720
721#[derive(Clone, Copy, Debug, PartialEq, Eq)]
722pub enum RequestError {
723 NodeUnavailable,
724 ResolveFailed,
725 AcquireFailed,
726 RestoreFailed,
727 RuntimeFailed,
728 PublishFailed,
729 NodeFenced,
730 PeerIncompatible,
731 CapacityExhausted,
732 /// A local write ran but its durability could not be proven, so the
733 /// response must fail rather than falsely acknowledge the write.
734 DurabilityUnproven,
735}
736
737/// Work performed outside the core. Every asynchronous effect is versioned;
738/// completion events with an obsolete `op` are ignored.
739#[derive(Clone, Debug, PartialEq, Eq)]
740pub enum Effect {
741 ScheduleTimer {
742 timer: Timer,
743 at_mono_ms: u64,
744 },
745 ReadSelfNodeLease {
746 op: OpId,
747 },
748 CasNodeLease {
749 op: OpId,
750 guard: CasGuard,
751 record: NodeLeaseRecord,
752 /// The prior record's peer-visible expiry for a renewal. The shell
753 /// uses it to report how much authority remained when the attempt
754 /// completed. An initial acquisition has no prior authority.
755 authority_expires_ms: Option<u64>,
756 },
757 /// Read the local cell inventory. This is emitted only after the initial
758 /// node lease CAS replaced the exact certified predecessor generation.
759 ReadLocalCells,
760 ReadOwner {
761 op: OpId,
762 cell: CellId,
763 },
764 ReadNodeLease {
765 op: OpId,
766 cell: CellId,
767 owner: NodeId,
768 },
769 /// The takeover interlock, as a core decision (lease-fold): the dead
770 /// owner's folded log state was not sealed, so its acked tail may
771 /// exist only on its followers. The executor recovers every
772 /// non-sealed session of `owner` into the bucket and reports
773 /// `NodeLogRecovered`; only then does the claim proceed.
774 RecoverNodeLog {
775 op: OpId,
776 cell: CellId,
777 owner: NodeId,
778 },
779 /// Enumerate recent node leases and return their advisory load records.
780 /// Listing and bounded parallel reads are adapter mechanics; selection,
781 /// reservations, and exclusions are deterministic core policy.
782 ReadCapacityPeers {
783 op: OpId,
784 cell: CellId,
785 },
786 CasOwner {
787 op: OpId,
788 cell: CellId,
789 guard: CasGuard,
790 epoch: Epoch,
791 takeover: bool,
792 },
793 /// Bring the bucket's wake entry for this cell into line with its alarm.
794 ///
795 /// Emitted wherever the alarm settles, which is the only place that
796 /// knows. An arm needs an entry; a consumed alarm needs its entry gone,
797 /// or every later due scan finds a hint for an alarm that already fired
798 /// and wakes a cell with nothing to do. `next_alarm_ms` is -1 when no
799 /// alarm remains.
800 ReconcileWakeEntry {
801 cell: CellId,
802 next_alarm_ms: i64,
803 },
804 /// Publish an evicted cell as unowned, keeping its epoch, so the next
805 /// node to want it can take it without waiting for this one to notice.
806 ReleaseOwner {
807 op: OpId,
808 cell: CellId,
809 epoch: Epoch,
810 },
811 /// Ask a compatible peer to acquire a cell whose owner record was just
812 /// released. The result acknowledges authority acquisition. Replica
813 /// restore and runtime publication continue outside the donor's shutdown
814 /// critical path.
815 AdoptReleased {
816 op: OpId,
817 cell: CellId,
818 released_epoch: Epoch,
819 },
820 /// Interrupt the activity which existed when a cell entered its shutdown
821 /// handoff batch. The shell maps core request IDs to handler/body aborts
822 /// and closes sockets with a restart status.
823 CancelCellActivity {
824 cell: CellId,
825 requests: Vec<RequestId>,
826 websockets: Vec<WebSocketId>,
827 /// A forced generation swap lists only the regular and outbound
828 /// sockets, and the cell stays on this node: its hibernatable sockets
829 /// and auto-response pair survive. A shutdown handoff lists every
830 /// socket and forgets the pair, because the cell is leaving.
831 keep_hibernatable: bool,
832 },
833 Restore {
834 op: OpId,
835 cell: CellId,
836 spec: RestoreSpec,
837 },
838 StartRuntime {
839 op: OpId,
840 cell: CellId,
841 epoch: Epoch,
842 },
843 Publish {
844 op: OpId,
845 cell: CellId,
846 epoch: Epoch,
847 },
848 /// Prove that every commit made before this effect is recoverable from
849 /// replica authority. Voluntary eviction cannot begin until this succeeds.
850 EnsureDurable {
851 op: OpId,
852 cell: CellId,
853 epoch: Epoch,
854 },
855 /// The output gate: prove the cell's committed `position` is replicated so
856 /// a withheld local write response can be released. Unlike
857 /// [`Effect::EnsureDurable`] this is per-request and changes no cell phase,
858 /// so the cell keeps serving co-resident requests while one response waits.
859 AwaitDurable {
860 op: OpId,
861 cell: CellId,
862 epoch: Epoch,
863 position: u64,
864 },
865 /// For bucket-proof acknowledgements, read `own.json` and answer whether it
866 /// still names this node at this epoch. The core holds the gated write
867 /// until `Event::OwnershipVerified` returns. Fleet-proof acks never
868 /// emit this — the ensemble seal is their fence.
869 VerifyOwnership {
870 op: OpId,
871 cell: CellId,
872 epoch: Epoch,
873 },
874 StopRuntime {
875 op: OpId,
876 cell: CellId,
877 epoch: Epoch,
878 cause: StopCause,
879 },
880 FireAlarm {
881 op: OpId,
882 cell: CellId,
883 epoch: Epoch,
884 scheduled_ms: i64,
885 },
886 Complete {
887 request: RequestId,
888 result: Result<Route, RequestError>,
889 },
890 /// Release a withheld output now that the writes it can reveal are
891 /// decided: `Ok` lets it leave, `Err` refuses it. Emitted only for an
892 /// output the shell held open via [`Event::Output`].
893 ///
894 /// `channel` is the one the shell supplied, returned unchanged. It selects
895 /// which adapter holds this effect and is the only thing the shell needs
896 /// in order to route the release. No operation id rides along: the shell
897 /// never learns the one the core assigned, and `(request, channel)` is
898 /// unique by construction — `State::validate` enforces it.
899 Release {
900 request: RequestId,
901 channel: Channel,
902 result: Result<(), RequestError>,
903 },
904 /// Complete the synchronous resident-selection decision. `None` means
905 /// the executor must use the ordinary stateless Worker pool.
906 CompleteWorker {
907 request: RequestId,
908 route: Option<WorkerRoute>,
909 },
910 /// Refuse a transport the node cannot afford to hold. The shell closes it;
911 /// the cell carries on without it.
912 CloseWebSocket {
913 cell: CellId,
914 websocket: WebSocketId,
915 },
916 Halt {
917 code: i32,
918 reason: HaltReason,
919 },
920}
921
922/// One database encoded by the local cell path.
923#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
924pub struct LocalCell {
925 pub id: CellId,
926 pub epoch: Epoch,
927}
928
929#[derive(Clone, Copy, Debug, PartialEq, Eq)]
930pub enum StopCause {
931 Cleanup,
932 /// `rebalance` means this eviction hands the cell to the fleet: its
933 /// ownership record is released and the local replica is not worth
934 /// keeping. An idle eviction is the opposite on both counts -- it
935 /// keeps the record so the next activation here renames the file into
936 /// place instead of paying a full remote restore.
937 Evict {
938 rebalance: bool,
939 },
940 Fence,
941 /// A durability proof came back negative, so this runtime's memory and its
942 /// local database may hold writes the bucket does not. celld has just told
943 /// the caller those writes failed; continuing to serve them is the
944 /// divergence, not the failure. Stop, keep no local snapshot, and let the
945 /// next activation restore from the bucket.
946 Reset,
947 /// The cell moves to the current application generation. The runtime
948 /// leaves its isolate and is started again at the same epoch on an
949 /// isolate of the new generation: no ownership change, no restore, no
950 /// replication release. The stop reaches the shell as `Cleaning`, and the
951 /// core answers the stop with `StartRuntime` instead of a terminal phase.
952 Swap,
953}