Diffinery

homeflare/celldpublic

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