Diffinery

homeflare/celldpublic

5515 lines · 221.8 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3//! Clean-sheet celld decision core.
4//!
5//! [`on_event`] is the only way behavioral state advances. The production
6//! executor and deterministic simulator both feed it events and perform the
7//! returned effects. No adapter may mutate [`State`] directly.
8
9use std::collections::{BTreeMap, BTreeSet, VecDeque};
10
11pub mod alarm;
12pub mod cache;
13pub mod cell;
14pub mod cron;
15pub mod dead_node_reconciliation;
16pub mod drain;
17pub mod gate;
18pub mod http;
19pub mod isolate;
20pub mod kv;
21pub mod log_evict;
22pub mod log_tier;
23mod output_gate;
24pub mod peer;
25pub mod pressure;
26pub mod queue;
27pub mod restore;
28pub mod routing;
29pub mod schedule;
30pub mod sqlite;
31pub mod sweep;
32pub mod wake;
33
34mod types;
35pub use types::*;
36
37#[derive(Clone, Debug, PartialEq, Eq)]
38enum Activation {
39 Claim(Claim),
40 Restore(RestoreSpec),
41}
42
43#[derive(Clone, Debug, PartialEq, Eq)]
44enum ColdStart {
45 ReadOwner,
46 Restore(RestoreSpec),
47}
48
49/// Facts already decided by ownership resolution that select a safe restore
50/// source. The effect adapter must not rediscover or guess these.
51#[derive(Clone, Debug, PartialEq, Eq)]
52pub struct RestoreSpec {
53 pub epoch: Epoch,
54 /// This activation conditionally created epoch one, so no replica can
55 /// precede it.
56 pub fresh: bool,
57 /// Ownership was seized from a different node (or a released record), so
58 /// a previous local eviction cache is not authoritative.
59 pub took_over: bool,
60 /// The node-level lease handoff proved that this exact local epoch remains
61 /// authoritative. The adapter must not consult the remote replica.
62 pub resume_local: bool,
63 /// The owner the takeover displaced — the node named by the record
64 /// version the acquire consumed — for the node-log takeover interlock.
65 /// `None` when the record was released or absent, which the release
66 /// path already proved durable. Carried here rather than memoized in
67 /// the executor so an acquire confirmed by reconciliation names its
68 /// prior exactly like one confirmed by the CAS response.
69 pub prior: Option<NodeId>,
70}
71
72#[derive(Clone, Debug, PartialEq, Eq)]
73pub struct Claim {
74 pub guard: CasGuard,
75 pub epoch: Epoch,
76 pub takeover: bool,
77 /// The node named by the record version `guard` matches — the prior
78 /// owner this claim displaces if it applies. `None` for a released or
79 /// absent record.
80 pub prior: Option<NodeId>,
81 /// Ambiguous acquires already reconciled for this claim.
82 ///
83 /// An ambiguous compare-and-swap is re-read rather than retried blindly,
84 /// which is correct — it may have applied. But the re-read leads to
85 /// another acquire, and if that is ambiguous too the cycle repeats. With
86 /// no bound a persistently unanswered store turns a request that used to
87 /// hang into one that spins, which is worse: it burns a slot and an
88 /// object-store budget forever instead of merely waiting.
89 pub reconciles: u32,
90}
91
92/// How many times one claim may reconcile an ambiguous acquire before the
93/// request is failed and the caller left to decide. Small: each pass is a full
94/// read plus a write, and a store answering ambiguously three times running is
95/// not about to start answering.
96pub const MAX_ACQUIRE_RECONCILES: u32 = 3;
97
98/// Phases map onto the Durable Objects lifecycle states where Cloudflare has
99/// a name for them:
100///
101/// - `Resident` is active or idle in memory (states 1-3).
102/// - `Dormant` is out of memory but still owned by this node, so the cell has
103/// not been moved off its host. A dormant cell with surviving hibernatable
104/// sockets is *hibernated* (state 4); see [`Core::is_hibernated`].
105/// - `Inactive` is out of memory and owned by nobody: removed from the host,
106/// needing a cold start (state 5, and the initial state of every cell).
107///
108/// Note that celld and Cloudflare use "evict" differently. Cloudflare evicts a
109/// cell *off its host*, which produces `Inactive`. celld evicts a cell *out of
110/// memory*, which produces `Dormant`, and shedding is what then publishes it
111/// unowned.
112#[derive(Clone, Debug, PartialEq, Eq)]
113pub enum Phase {
114 Inactive,
115 /// Cold demand queued behind `max_activations`, before any I/O begins.
116 WaitingActivation,
117 ReadingOwner {
118 op: OpId,
119 },
120 ReadingNodeLease {
121 op: OpId,
122 owner: OwnerRecord,
123 },
124 /// The takeover interlock (lease-fold): the dead owner's folded log
125 /// state was not sealed, so the executor is recovering its sessions
126 /// before this cell may claim.
127 RecoveringOwnerLog {
128 op: OpId,
129 owner: OwnerRecord,
130 },
131 ReadingCapacity {
132 op: OpId,
133 claim: Claim,
134 },
135 WaitingCapacity,
136 Acquiring {
137 op: OpId,
138 claim: Claim,
139 },
140 ReconcilingAcquire {
141 op: OpId,
142 claim: Claim,
143 },
144 Restoring {
145 op: OpId,
146 spec: RestoreSpec,
147 },
148 Starting {
149 op: OpId,
150 epoch: Epoch,
151 },
152 Publishing {
153 op: OpId,
154 epoch: Epoch,
155 },
156 /// The runtime remains published and routable while replica durability is
157 /// being proved. A failed or ambiguous proof returns to `Resident`.
158 EnsuringDurability {
159 op: OpId,
160 epoch: Epoch,
161 },
162 Cleaning {
163 op: OpId,
164 epoch: Epoch,
165 cause: StopCause,
166 },
167 /// Out of memory, still owned here. Hibernated when sockets survived.
168 Dormant {
169 epoch: Epoch,
170 },
171 /// The owner record is no longer this node's, and a signed peer request is
172 /// waiting for a successor to restore and publish the cell.
173 Adopting {
174 op: OpId,
175 released_epoch: Epoch,
176 },
177 Resident {
178 epoch: Epoch,
179 },
180 Remote {
181 node: NodeId,
182 addr: String,
183 epoch: Epoch,
184 peer_protocol: u16,
185 /// Present only for epoch-zero capacity candidates. It identifies the
186 /// exact advisory sample a refusal disproved.
187 capacity_sampled_ms: Option<u64>,
188 },
189 Fenced,
190}
191
192/// One authority observation from one state-machine boundary.
193#[cfg(celld_internal_tests)]
194#[derive(Clone, Debug, PartialEq, Eq)]
195pub struct AuthorityObserverSnapshot {
196 pub node_authoritative: bool,
197 pub fenced: bool,
198 pub now_mono_ms: u64,
199 pub phase: Option<Phase>,
200}
201
202/// The independent inputs for one StepSafety census.
203#[cfg(celld_internal_tests)]
204#[derive(Clone, Debug, PartialEq, Eq)]
205pub struct StepSafetyObserverSnapshot {
206 pub occupied_counter: usize,
207 pub capacity_holder_ids: BTreeSet<CellId>,
208 pub activation_permit_ids: BTreeSet<CellId>,
209 pub activation_holder_ids: BTreeSet<CellId>,
210}
211
212/// The reported name of a phase. Stable across internal renames, because
213/// `/state` and `celld diagnose` publish it.
214fn phase_name(phase: &Phase) -> &'static str {
215 match phase {
216 Phase::Inactive => "inactive",
217 Phase::WaitingActivation => "waiting_activation",
218 Phase::ReadingOwner { .. } => "reading_owner",
219 Phase::ReadingNodeLease { .. } => "reading_node_lease",
220 Phase::RecoveringOwnerLog { .. } => "recovering_owner_log",
221 Phase::ReadingCapacity { .. } => "reading_capacity",
222 Phase::WaitingCapacity => "waiting_capacity",
223 Phase::Acquiring { .. } => "acquiring",
224 Phase::ReconcilingAcquire { .. } => "reconciling_acquire",
225 Phase::Restoring { .. } => "restoring",
226 Phase::Starting { .. } => "starting",
227 Phase::Publishing { .. } => "publishing",
228 Phase::EnsuringDurability { .. } => "ensuring_durability",
229 Phase::Cleaning {
230 cause: StopCause::Swap,
231 ..
232 } => "swapping",
233 Phase::Cleaning { .. } => "cleaning",
234 Phase::Dormant { .. } => "dormant",
235 Phase::Adopting { .. } => "adopting",
236 Phase::Resident { .. } => "resident",
237 Phase::Remote { .. } => "remote",
238 Phase::Fenced => "fenced",
239 }
240}
241
242/// What waits behind an output gate.
243///
244/// An output waits to leave on its channel. A fired alarm waits for its own
245/// settlement, because the core orders the consume-side wake-entry delete from
246/// the far side of the gate: deleting the entry while the consuming commit is
247/// still local would lose both the alarm and the record that could revive it.
248///
249/// The two settle differently and that is the whole reason this is an enum: an
250/// output is released to the shell, an alarm is replayed back into the core. A
251/// channel cannot express the difference -- an alarm has no request to route
252/// by and no adapter holding anything for it -- so it is a second kind of
253/// owner rather than a seventh [`Channel`].
254#[derive(Clone, Debug, PartialEq, Eq)]
255enum GateOwner {
256 /// An output withheld until every write it can reveal is proven.
257 Output(Held),
258 /// The firing alarm's op, and the observation `fire_alarm` made. Both are
259 /// replayed into `alarm_finished` when the gate settles.
260 Alarm {
261 alarm: OpId,
262 at_ms: Option<i64>,
263 covered: bool,
264 },
265}
266
267/// One local write held open by the output gate.
268#[derive(Clone, Debug, PartialEq, Eq)]
269struct Barrier {
270 /// What opened it. An output's `channel` is returned verbatim in the
271 /// release effect; nothing in the core reads it.
272 owner: GateOwner,
273 cell: CellId,
274 epoch: Epoch,
275 position: u64,
276 /// Read-only outputs that finished after this write committed but before
277 /// its durability proof completed. They reveal the same state, so they
278 /// share the write's verdict -- one proof, one verdict, however many
279 /// channels are waiting on it.
280 followers: Vec<Held>,
281}
282
283/// One withheld output: which request raised it, and which way it leaves.
284#[derive(Clone, Copy, Debug, PartialEq, Eq)]
285struct Held {
286 request: RequestId,
287 channel: Channel,
288}
289
290/// One reason that a quiescing cell cannot enter its handoff yet.
291///
292/// This is a read-only management projection. The core remains the authority
293/// for the request and WebSocket indexes that produce it.
294#[derive(Clone, Debug, PartialEq, Eq)]
295pub struct DrainPin {
296 pub cell: CellId,
297 pub request: Option<RequestId>,
298 pub active_request_count: usize,
299 pub output_gate_count: usize,
300 pub regular_websocket_count: usize,
301 pub outbound_websocket_count: usize,
302}
303
304#[derive(Clone, Debug)]
305struct Cell {
306 phase: Phase,
307 /// The shutdown drain has reserved this resident cell for its next
308 /// handoff batch. New requests wait for the successor route while work
309 /// which was already admitted finishes on this runtime.
310 quiescing: bool,
311 requests: BTreeSet<RequestId>,
312 websockets: BTreeMap<WebSocketId, WebSocketKind>,
313 waiting_for: Option<Activation>,
314 waiting_activation: Option<ColdStart>,
315 /// The in-flight release of this cell's ownership record, if any.
316 releasing: Option<OpId>,
317 /// Whether the eviction now under way hands this cell to the fleet.
318 evict_rebalance: bool,
319 alarm: Option<AlarmState>,
320 alarm_wake: bool,
321 /// Startup, rather than a request or alarm, demands this activation.
322 resume_demand: bool,
323 /// When this cell's eviction was last refused, if it has been.
324 ///
325 /// A cell that cannot prove its replica durable goes back to residency,
326 /// and being cold is exactly why nobody registered it -- so it settles at
327 /// the head of the eviction order and is chosen again on the next pass,
328 /// and the one after. Enough of those and the node has no shed candidate
329 /// it will ever succeed with. Recording the refusal lets the order prefer
330 /// cells that have not just failed, while still coming back to them when
331 /// they are all that is left.
332 eviction_refused_mono_ms: Option<u64>,
333 /// The isolate holding this cell's realm. Eviction order reads it: taking
334 /// an isolate's last cell returns the whole heap, taking one of thirty-two
335 /// returns a cell record.
336 isolate: Option<isolate::IsolateId>,
337 /// The application generation whose isolate holds this cell's realm.
338 /// Zero until the shell reports a start, and the swap pump reads zero as
339 /// stale: a cell it cannot place is moved rather than trusted.
340 generation: u64,
341 /// This cell is moving to the current generation: quiescing for the
342 /// swap, stopped, or starting again. Cleared when it publishes, and by
343 /// any phase change that leaves the swap path.
344 swapping: bool,
345 /// A forced swap already cancelled this cell's activity. It asks once.
346 swap_cancelled: bool,
347 /// The queue deadline now watching this cell, if it is parked. A timer
348 /// carrying any other generation has been outlived and expires nothing.
349 queued_generation: Option<u64>,
350 /// When this cell last did something, on the remembered monotonic clock.
351 ///
352 /// Eviction order is the whole reason this exists. Without it the shed
353 /// candidate is whichever cell sorts first by id, so a node under
354 /// sustained pressure evicts its alphabetically-first cell over and over
355 /// -- restoring and shedding the busiest cell on the node while an idle
356 /// one further down the alphabet is never touched.
357 last_used_mono_ms: u64,
358}
359
360#[derive(Clone, Debug, PartialEq, Eq)]
361enum AlarmState {
362 Armed {
363 at_ms: i64,
364 generation: u64,
365 covered: bool,
366 },
367 Firing {
368 op: OpId,
369 at_ms: i64,
370 generation: u64,
371 covered: bool,
372 /// The newest runtime observation that arrived before the firing's
373 /// durability result. It cannot settle the alarm by itself.
374 observed: Option<(Option<i64>, bool)>,
375 },
376}
377
378#[derive(Clone, Copy, Debug, PartialEq, Eq)]
379struct AlarmObservation {
380 at_ms: Option<i64>,
381 covered: bool,
382 firing_settled: bool,
383}
384
385#[derive(Clone, Debug)]
386struct HeldNodeLease {
387 spec: NodeLeaseSpec,
388 record: NodeLeaseRecord,
389 last_ok_mono_ms: u64,
390 last_attempt_mono_ms: u64,
391 timer_generation: u64,
392}
393
394#[derive(Clone, Debug)]
395struct PendingNodeLease {
396 spec: NodeLeaseSpec,
397 desired: NodeLeaseRecord,
398 prior: Option<HeldNodeLease>,
399 /// This read follows a write whose result was ambiguous. It may prove the
400 /// desired record landed, but must not turn a failed create into an
401 /// unbounded read/write loop.
402 readback_only: bool,
403 /// The monotonic instant `desired.expires_ms` was computed from.
404 ///
405 /// Authority is bounded by what the *bucket* says, and the bucket says
406 /// `expires_ms`, which is sampled here rather than when the write lands.
407 /// Anchoring the local fence deadline to the write's completion instead
408 /// would let this node serve for the whole duration of the round trip
409 /// after every peer is entitled to declare it dead -- the store is under
410 /// no obligation to answer quickly, so that window is unbounded.
411 anchor_mono_ms: u64,
412 /// This initial CAS replaces the exact live generation certified by the
413 /// clean local shutdown. Renewals never set this bit.
414 resume_local: bool,
415}
416
417#[derive(Clone, Debug)]
418enum NodeAuthority {
419 Unstarted,
420 Reading {
421 op: OpId,
422 pending: PendingNodeLease,
423 },
424 Writing {
425 op: OpId,
426 pending: PendingNodeLease,
427 },
428 Held(HeldNodeLease),
429 /// A continuous node whose initial acquisition did not succeed, waiting to
430 /// try again.
431 ///
432 /// `StartNodeLease` is emitted exactly once, at process start, so without
433 /// this the first failed acquisition is permanent: the process stays up,
434 /// holds no authority, and answers every request `NodeUnavailable` for as
435 /// long as it runs. One slow or rate-limited bucket response at startup
436 /// should not cost a node its whole lifetime.
437 Retrying {
438 spec: NodeLeaseSpec,
439 generation: u64,
440 },
441 Failed,
442 Fenced,
443}
444
445impl Default for Cell {
446 fn default() -> Self {
447 Self {
448 phase: Phase::Inactive,
449 quiescing: false,
450 requests: BTreeSet::new(),
451 websockets: BTreeMap::new(),
452 waiting_for: None,
453 waiting_activation: None,
454 releasing: None,
455 evict_rebalance: false,
456 alarm: None,
457 alarm_wake: false,
458 resume_demand: false,
459 isolate: None,
460 generation: 0,
461 swapping: false,
462 swap_cancelled: false,
463 queued_generation: None,
464 eviction_refused_mono_ms: None,
465 last_used_mono_ms: 0,
466 }
467 }
468}
469
470/// The last cut the walk down took, and what the node looked like when it did.
471///
472/// The measurement travels with the value because the two are not comparable.
473/// When the latches change, so does the number the walk down reads, and
474/// comparing a fresh resident set size against a stale in-use figure finds them
475/// flat by coincidence.
476#[derive(Clone, Copy, Debug)]
477struct ShedCut {
478 /// The measurement `bytes` was read from.
479 metric: pressure::Metric,
480 /// What that measurement said at the cut.
481 bytes: u64,
482 /// The residency the cut was taken at.
483 cells: usize,
484}
485
486/// All authoritative coordination state for the first vertical slice.
487pub struct State {
488 node: NodeId,
489 config: Config,
490 fenced: bool,
491 /// A shutdown handoff is under way: every resident cell is to be
492 /// released, pumped at most `max_releases` at a time. Sticky -- a
493 /// draining node never goes back to serving.
494 draining: bool,
495 /// An exact clean predecessor was replaced and its local inventory is
496 /// being scanned or materialized. Readiness remains false until every
497 /// discovered cell either publishes or fails closed.
498 resuming: bool,
499 resuming_cells: BTreeSet<CellId>,
500 next_op: OpId,
501 next_timer_generation: u64,
502 cells: BTreeMap<CellId, Cell>,
503 request_cells: BTreeMap<RequestId, CellId>,
504 /// Local routes handed to the executor but not yet reported complete.
505 /// These are eviction pins: the adapter may still be running user code.
506 active_requests: BTreeMap<RequestId, CellId>,
507 /// Reverse index of `active_requests`: how many active requests target
508 /// each cell. `is_active` reads it in O(1) where scanning the values was
509 /// O(active_requests), and `worker_request` calls `is_active` once per
510 /// resident cell — the product wedged cold-cell activation, the rate
511 /// falling with the cell count (engine/pathological-load.md).
512 active_cells: BTreeMap<CellId, usize>,
513 /// Local write responses withheld by the output gate until their cell is
514 /// proven durable to the written position, keyed by the durability op. An
515 /// open gate makes its cell active, so the cell cannot be evicted
516 /// underneath it; a fence drains these to a failed response so a write is
517 /// never acknowledged after the node loses authority.
518 barriers: BTreeMap<OpId, Barrier>,
519 /// Requests whose activity ended while a write of theirs was still on the
520 /// output gate. The pin outlives the activity: it keeps the cell from being
521 /// evicted under the gate, and keeps a later write of the same request able
522 /// to open one. See `activity_finished`.
523 gate_pinned: BTreeSet<RequestId>,
524 /// Last resident selected for top-level Worker execution. Cell IDs are
525 /// ordered, so this is enough to replay a fair round-robin without shell
526 /// atomics or registry iteration order leaking into behavior.
527 worker_cursor: Option<CellId>,
528 activity: ActivitySnapshot,
529 activation_waiters: VecDeque<CellId>,
530 /// Cells holding a complete cold-route admission. Keeping this explicit,
531 /// instead of inferring it from executor tasks, makes the concurrency bound
532 /// part of the replayable state machine.
533 activation_permits: BTreeSet<CellId>,
534 /// Cells with an eviction in flight -- from the durability proof through
535 /// the runtime stop. Explicit for the same reason as the activation
536 /// permits: the bound belongs in the replayable state machine rather than
537 /// being implied by how many executor tasks happen to exist.
538 eviction_permits: BTreeSet<CellId>,
539 /// Cells waiting for a residency slot, in arrival order. FIFO is the
540 /// whole admission policy: waking every waiter on a release and letting
541 /// them race is unfair by construction — under sustained eviction a
542 /// waiter can time out while thousands of slots are freed around it.
543 /// The queue converts "eventually, probably" into a bound: a waiter with
544 /// `k` waiters ahead of it is admitted within `k` releases, so no
545 /// arrival pattern can starve it.
546 capacity_waiters: VecDeque<CellId>,
547 /// Requests received as epoch-zero capacity handoffs. Keeping the mode on
548 /// the request rather than in the HTTP adapter makes the admit/refuse race
549 /// atomic with every other lifecycle transition.
550 capacity_requests: BTreeSet<RequestId>,
551 /// Signed shutdown handoffs that need ownership but not a warm runtime.
552 /// A real request joining the same acquisition still causes the normal
553 /// restore, so demand always outranks the lazy handoff optimization.
554 handoff_requests: BTreeSet<RequestId>,
555 /// Reservations made against each unchanged advisory sample. Concurrent
556 /// lookups are applied one event at a time, so projected load cannot pick
557 /// the same advertised final slot twice by accident.
558 capacity_reservations: BTreeMap<NodeId, usize>,
559 capacity_samples: BTreeMap<NodeId, u64>,
560 /// A refusal disproves exactly one load sample. The node becomes eligible
561 /// again only after its lease advertises a newer sample.
562 capacity_rejections: BTreeMap<NodeId, u64>,
563 /// Live routing authority is shared by every cell owned by the same node.
564 /// Keeping that cache here makes expiry and invalidation deterministic,
565 /// rather than an invisible executor optimization.
566 node_lease_cache: BTreeMap<NodeId, NodeLeaseRecord>,
567 /// Start/publish effects invalidated by fencing may still commit. Their
568 /// late completion must trigger compensating cleanup, not be ignored.
569 retired_runtime_ops: BTreeMap<OpId, (CellId, Epoch)>,
570 /// Runtime starts which exceeded their request deadline but still own a
571 /// live executor task. A start cannot be cancelled safely, so the core
572 /// keeps its phase and operation until the real completion arrives. New
573 /// callers fail fast instead of starting a duplicate runtime for the same
574 /// cell and epoch.
575 timed_out_runtime_starts: BTreeSet<OpId>,
576 /// The cell each in-flight cell-scoped operation belongs to. Completion
577 /// events name only the op; this index is what makes resolving one a
578 /// lookup instead of a walk of every cell.
579 cell_ops: BTreeMap<OpId, CellId>,
580 /// How many cells currently occupy capacity, maintained at every phase
581 /// transition. `has_capacity` asks on every admission and `validate` on
582 /// every debug event; counting by walking the map priced both by the
583 /// total cell count rather than the answer.
584 occupied: usize,
585 node_authority: NodeAuthority,
586 /// A NudgeNodeLease arrived while a lease write was already in flight.
587 /// That write's body was serialized BEFORE the
588 /// nudge's publish, so it cannot carry it. Drain the flag by renewing
589 /// again the moment the in-flight write settles into Held.
590 nudge_pending: bool,
591 /// The most recent wall-clock instant any event carried. Alarms are wall
592 /// clock, so judging whether one is imminent needs this rather than the
593 /// monotonic reading next to it.
594 now_ms: u64,
595 /// The most recent monotonic instant any event carried. Not a clock read:
596 /// the core never asks what time it is, it remembers what it was told, so
597 /// a handler that was not handed a timestamp can still arm a deadline
598 /// relative to the event being processed.
599 now_mono_ms: u64,
600 /// How far down the current sample asked the node to shed.
601 ///
602 /// The walk down runs at eviction speed rather than sample speed: each
603 /// completed eviction starts the next while residency is still above this
604 /// floor. Without one it is a cell per sample, so a node fifteen over its
605 /// watermark refuses work for fifteen sampling periods. Recomputed every
606 /// sample, so a resource trigger comes down by a proportion of what was
607 /// last measured rather than aiming at a cell count that means nothing to
608 /// it.
609 shed_floor: usize,
610 /// The cut the current shed floor was set from. A later latched sample
611 /// compares against this: a completed cut that left the number flat makes
612 /// another cut futile.
613 shed_cut: Option<ShedCut>,
614 /// Which ceilings are latched. Held apart from `shed_reason`, which names
615 /// only the more serious crossing.
616 latches: pressure::Latches,
617 /// The application generation the node serves, as last announced by
618 /// `Event::GenerationChanged`. Zero before any announcement, when no cell
619 /// is stale.
620 current_generation: u64,
621 /// When the current generation was announced, on the monotonic clock.
622 /// The maximum age counts from here.
623 generation_changed_mono_ms: u64,
624 /// How long a resident cell may stay on an older generation before its
625 /// swap is forced. Zero forces every stale cell at the announcement.
626 swap_max_age_ms: u64,
627 /// The classes whose cells are forced without waiting for the maximum
628 /// age, from the last announcement.
629 ///
630 /// Held against the announcement rather than marked on each cell,
631 /// because only a resident cell is ever nominated: a mark left a dormant
632 /// reserved cell -- which is what a reserved cell is whenever it is idle
633 /// -- carrying a forced flag that nothing could act on, and the core
634 /// refuses that pair. Eagerness is a property of the class and the
635 /// adoption, so the pump reads it where it decides, and no cell can hold
636 /// a swap flag it is not swapping under.
637 swap_eager_classes: BTreeSet<String>,
638 /// The shedding latch. celld kept this in the executor, which meant the
639 /// hysteresis -- the part with actual behaviour -- was the one piece the
640 /// simulation could not reach. It is carried here so a sample
641 /// sequence is replayable.
642 shedding: bool,
643 /// Whether the last load sample is below every configured low watermark.
644 /// This is stricter than `!shedding` and reserves room for a fleet handoff.
645 memory_headroom: bool,
646 /// Which resource is holding the latch, for the effect the shell logs.
647 shed_reason: Option<&'static str>,
648}
649
650impl State {
651 pub fn new(node: impl Into<NodeId>, config: Config) -> Self {
652 assert!(config.max_evictions > 0, "max_evictions must be positive");
653 assert!(config.max_releases > 0, "max_releases must be positive");
654 assert!(
655 config.max_activations > 0,
656 "max_activations must be positive"
657 );
658 Self {
659 node: node.into(),
660 config,
661 fenced: false,
662 draining: false,
663 current_generation: 0,
664 generation_changed_mono_ms: 0,
665 swap_max_age_ms: 0,
666 swap_eager_classes: BTreeSet::new(),
667 resuming: false,
668 resuming_cells: BTreeSet::new(),
669 next_op: 1,
670 next_timer_generation: 1,
671 cells: BTreeMap::new(),
672 request_cells: BTreeMap::new(),
673 active_requests: BTreeMap::new(),
674 active_cells: BTreeMap::new(),
675 barriers: BTreeMap::new(),
676 gate_pinned: BTreeSet::new(),
677 worker_cursor: None,
678 activity: ActivitySnapshot::default(),
679 activation_waiters: VecDeque::new(),
680 activation_permits: BTreeSet::new(),
681 eviction_permits: BTreeSet::new(),
682 capacity_waiters: VecDeque::new(),
683 capacity_requests: BTreeSet::new(),
684 handoff_requests: BTreeSet::new(),
685 capacity_reservations: BTreeMap::new(),
686 capacity_samples: BTreeMap::new(),
687 capacity_rejections: BTreeMap::new(),
688 node_lease_cache: BTreeMap::new(),
689 retired_runtime_ops: BTreeMap::new(),
690 timed_out_runtime_starts: BTreeSet::new(),
691 cell_ops: BTreeMap::new(),
692 occupied: 0,
693 node_authority: NodeAuthority::Unstarted,
694 nudge_pending: false,
695 now_ms: 0,
696 now_mono_ms: 0,
697 shed_floor: 0,
698 shed_cut: None,
699 latches: pressure::Latches::default(),
700 shedding: false,
701 memory_headroom: false,
702 shed_reason: None,
703 }
704 }
705
706 pub fn node(&self) -> &str {
707 &self.node
708 }
709
710 pub fn is_fenced(&self) -> bool {
711 self.fenced
712 }
713
714 /// Authority is the lease's published validity evaluated at ask time on
715 /// the monotonic clock — not the `Held` variant. A peer treats the record
716 /// as dead the instant `now_ms` reaches `expires_ms`, so a holder whose
717 /// lease lapsed must answer `false` here even if `Timer::NodeLeaseFence`
718 /// has not fired yet: the timer is the liveness backstop that halts the
719 /// process, never the safety mechanism. A suspended VM's timer fires
720 /// late, but a request evaluated after resume still refuses. The `<` /
721 /// `>=` polarity matches the fence timer at `handle_timer`, so the
722 /// predicate and the timer cannot disagree.
723 pub fn node_authoritative(&self) -> bool {
724 if !self.config.require_node_lease {
725 return !self.fenced;
726 }
727 let fresh = |held: &HeldNodeLease| {
728 self.now_mono_ms.saturating_sub(held.last_ok_mono_ms) < held.spec.ttl_ms
729 };
730 match &self.node_authority {
731 NodeAuthority::Held(held) => fresh(held),
732 NodeAuthority::Reading { pending, .. } | NodeAuthority::Writing { pending, .. } => {
733 pending.prior.as_ref().is_some_and(fresh)
734 }
735 _ => false,
736 }
737 }
738
739 /// Whether the process can accept new traffic.
740 pub fn ready_to_serve(&self) -> bool {
741 if self.fenced || self.resuming {
742 return false;
743 }
744 self.node_authoritative()
745 }
746
747 pub fn phase(&self, cell: &str) -> Option<&Phase> {
748 self.cells.get(cell).map(|cell| &cell.phase)
749 }
750
751 /// Return every cell phase for an opt-in transition observer.
752 ///
753 /// An observer joins these snapshots by cell before it discards each cell
754 /// identifier. A node-wide census cannot preserve that association.
755 #[cfg(celld_internal_tests)]
756 pub fn phase_snapshot_for_test(&self) -> BTreeMap<CellId, Phase> {
757 self.cells
758 .iter()
759 .map(|(id, cell)| (id.clone(), cell.phase.clone()))
760 .collect()
761 }
762
763 /// Return the authority inputs from one observation boundary.
764 #[cfg(celld_internal_tests)]
765 pub fn authority_observer_snapshot(&self, cell: &str) -> AuthorityObserverSnapshot {
766 AuthorityObserverSnapshot {
767 node_authoritative: self.node_authoritative(),
768 fenced: self.fenced,
769 now_mono_ms: self.now_mono_ms,
770 phase: self.phase(cell).cloned(),
771 }
772 }
773
774 /// Return both sides of each structural count from the decision core.
775 #[cfg(celld_internal_tests)]
776 pub fn step_safety_observer_snapshot(&self) -> StepSafetyObserverSnapshot {
777 StepSafetyObserverSnapshot {
778 occupied_counter: self.occupied,
779 capacity_holder_ids: self
780 .cells
781 .iter()
782 .filter(|(_, cell)| phase_occupies_capacity(&cell.phase))
783 .map(|(id, _)| id.clone())
784 .collect(),
785 activation_permit_ids: self.activation_permits.clone(),
786 activation_holder_ids: self
787 .cells
788 .iter()
789 .filter(|(_, cell)| phase_holds_activation(&cell.phase))
790 .map(|(id, _)| id.clone())
791 .collect(),
792 }
793 }
794
795 /// Which resource is currently holding the shedding latch, if any.
796 ///
797 /// A node that is refusing work should be able to say why; without this
798 /// the operator sees only that admissions stopped.
799 pub fn shed_reason(&self) -> Option<&'static str> {
800 self.shed_reason
801 }
802
803 /// Whether this node is currently shedding, for peers ranking it as a
804 /// placement target. A node that says no while walking down invites the
805 /// work it is trying to get rid of.
806 pub fn shedding(&self) -> bool {
807 self.shedding
808 }
809
810 /// Whether the last load sample reserves memory below every pressure
811 /// resume line. False before the first sample.
812 pub fn memory_headroom(&self) -> bool {
813 self.memory_headroom
814 }
815
816 /// Host-side sockets open across every cell. Each one pins its cell
817 /// against eviction, so a node holding many is a poor landing place
818 /// even when its residency looks unremarkable.
819 pub fn host_websockets(&self) -> usize {
820 self.cells.values().map(|cell| cell.websockets.len()).sum()
821 }
822
823 /// Does this cell still hold that socket? False when the core declined
824 /// it, so the shell can answer the opener instead of closing underneath.
825 pub fn holds_websocket(&self, id: &str, websocket: WebSocketId) -> bool {
826 self.cells
827 .get(id)
828 .is_some_and(|cell| cell.websockets.contains_key(&websocket))
829 }
830
831 pub fn occupied(&self) -> usize {
832 self.occupied
833 }
834
835 /// Are fewer than `ceiling` cells occupying capacity?
836 fn occupied_below(&self, ceiling: usize) -> bool {
837 self.occupied < ceiling
838 }
839
840 pub fn residents(&self) -> Vec<CellId> {
841 self.cells
842 .iter()
843 .filter(|(_, cell)| {
844 matches!(
845 cell.phase,
846 Phase::Resident { .. } | Phase::EnsuringDurability { .. }
847 )
848 })
849 .map(|(id, _)| id.clone())
850 .collect()
851 }
852
853 /// Resident cells which have stopped admitting new local requests so the
854 /// shutdown drain can reach a final durability boundary.
855 pub fn quiescing(&self) -> usize {
856 self.cells.values().filter(|cell| cell.quiescing).count()
857 }
858
859 /// Return every pin on every resident reserved for a shutdown handoff.
860 /// A cell without an active request still gets one row, so a regular or
861 /// outbound WebSocket cannot leave an otherwise empty stall invisible.
862 pub fn drain_pins(&self) -> Vec<DrainPin> {
863 let mut pins = Vec::new();
864 for (cell, state) in self.cells.iter().filter(|(_, cell)| cell.quiescing) {
865 let active: Vec<RequestId> = self
866 .active_requests
867 .iter()
868 .filter_map(|(request, request_cell)| (request_cell == cell).then_some(*request))
869 .collect();
870 let regular_websocket_count = state
871 .websockets
872 .values()
873 .filter(|kind| matches!(kind, WebSocketKind::Regular))
874 .count();
875 let outbound_websocket_count = state
876 .websockets
877 .values()
878 .filter(|kind| matches!(kind, WebSocketKind::Outbound))
879 .count();
880 if active.is_empty() {
881 pins.push(DrainPin {
882 cell: cell.clone(),
883 request: None,
884 active_request_count: 0,
885 output_gate_count: 0,
886 regular_websocket_count,
887 outbound_websocket_count,
888 });
889 continue;
890 }
891 let active_request_count = active.len();
892 for request in active {
893 pins.push(DrainPin {
894 cell: cell.clone(),
895 request: Some(request),
896 active_request_count,
897 output_gate_count: self
898 .barriers
899 .values()
900 .filter(|barrier| {
901 matches!(&barrier.owner, GateOwner::Output(held) if held.request == request)
902 || barrier.followers.iter().any(|held| held.request == request)
903 })
904 .count(),
905 regular_websocket_count,
906 outbound_websocket_count,
907 });
908 }
909 }
910 pins
911 }
912
913 /// Return the exact management projection for the current event boundary.
914 /// Activations are not visible until publication; a runtime being held for
915 /// durability remains visible because it is still published and routable.
916 pub fn presence_snapshot(&self) -> PresenceSnapshot {
917 let cells = self
918 .cells
919 .iter()
920 .filter_map(|(id, cell)| match cell.phase {
921 Phase::Resident { epoch } | Phase::EnsuringDurability { epoch, .. } => {
922 Some(PresenceCell {
923 id: id.clone(),
924 epoch,
925 })
926 }
927 _ => None,
928 })
929 .collect();
930 PresenceSnapshot {
931 serving: self.ready_to_serve(),
932 cells,
933 activity: self.activity,
934 }
935 }
936
937 /// The isolate each resident cell sits in. A node holds one V8 heap per
938 /// distinct value here, so the spread of this is the memory a walk down
939 /// can still return.
940 pub fn resident_isolates(&self) -> Vec<isolate::IsolateId> {
941 self.cells
942 .values()
943 .filter(|cell| matches!(cell.phase, Phase::Resident { .. }))
944 .filter_map(|cell| cell.isolate)
945 .collect()
946 }
947
948 pub fn waiting(&self) -> Vec<CellId> {
949 self.capacity_waiters.iter().cloned().collect()
950 }
951
952 pub fn activation_waiting(&self) -> Vec<CellId> {
953 self.activation_waiters.iter().cloned().collect()
954 }
955
956 pub fn activating(&self) -> usize {
957 self.activation_permits.len()
958 }
959
960 /// Evictions in flight, from the durability proof through the runtime
961 /// stop. During a drain this saturates at `max_releases`.
962 pub fn evicting(&self) -> usize {
963 self.eviction_permits.len()
964 }
965
966 /// How many cells sit in each phase, by a stable short name, omitting the
967 /// phases with no cells.
968 ///
969 /// A node that refuses cells is diagnosed by where its cells are, and
970 /// `occupied` cannot say: it counts residency, so a node holding thousands
971 /// of cells part-way through a cold start reports almost none. A fleet held
972 /// that state for fifteen minutes and the record could not say what the
973 /// cells were doing (issue #50).
974 ///
975 /// The names are part of the operator interface. A chart and a human read
976 /// them, so they do not change with an internal rename.
977 pub fn phase_census(&self) -> Vec<(&'static str, usize)> {
978 let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
979 for cell in self.cells.values() {
980 *counts.entry(phase_name(&cell.phase)).or_default() += 1;
981 }
982 counts.into_iter().collect()
983 }
984
985 /// Cold routes that have not finished: cells that hold an activation
986 /// permit plus cells queued behind the activation ceiling. A capacity
987 /// waiter already holds a permit, so this counts every cell once. This is
988 /// capacity telemetry; a graceful handoff is paced by successor ownership
989 /// acknowledgements instead.
990 pub fn activation_backlog(&self) -> usize {
991 self.activation_permits.len() + self.activation_waiters.len()
992 }
993
994 /// Ownership releases still in flight. The shutdown drain waits for
995 /// zero: a released cell stops occupying capacity before its record
996 /// write commits, so an exit gated on occupancy alone can outrun its
997 /// own releases and leave records a successor must wait out the node
998 /// lease for -- the takeover-at-once promise broken on every real
999 /// store, where the write loses a race against a 50ms drain poll that
1000 /// a local fixture always wins.
1001 pub fn releasing(&self) -> usize {
1002 self.cells
1003 .values()
1004 .filter(|cell| cell.releasing.is_some())
1005 .count()
1006 }
1007
1008 /// Released cells still waiting for a successor ownership acknowledgement.
1009 ///
1010 /// This count holds the shutdown handoff permit after the owner write has
1011 /// completed. Without it the release pump can blank the complete resident
1012 /// set before any successor reserves restoration capacity.
1013 pub fn adopting(&self) -> usize {
1014 self.cells
1015 .values()
1016 .filter(|cell| matches!(cell.phase, Phase::Adopting { .. }))
1017 .count()
1018 }
1019
1020 /// Completed successor ownership acknowledgements during this process lifetime.
1021 /// Shutdown uses this monotonic value to distinguish a slow, advancing
1022 /// handoff from one that has stopped making progress.
1023 pub fn handed_off(&self) -> u64 {
1024 self.activity.handed_off
1025 }
1026
1027 /// Return an epoch this node has acquired for a dormant, warming, or
1028 /// published cell. A shutdown handoff acknowledges this authority without
1029 /// forcing the cell runtime into memory.
1030 pub fn accepted_epoch(&self, id: &str) -> Option<Epoch> {
1031 match self.cells.get(id).map(|cell| &cell.phase) {
1032 Some(Phase::Restoring { spec, .. }) => Some(spec.epoch),
1033 Some(
1034 Phase::Starting { epoch, .. }
1035 | Phase::Publishing { epoch, .. }
1036 | Phase::EnsuringDurability { epoch, .. }
1037 | Phase::Cleaning { epoch, .. }
1038 | Phase::Dormant { epoch }
1039 | Phase::Resident { epoch },
1040 ) => Some(*epoch),
1041 _ => None,
1042 }
1043 }
1044
1045 /// Cheap internal consistency gate run by both executors after every event.
1046 /// Check one withheld output: pinned on the barrier's cell, and the only
1047 /// output this request holds on that channel.
1048 fn validate_held(
1049 held: &Held,
1050 op: &OpId,
1051 barrier: &Barrier,
1052 active_requests: &BTreeMap<RequestId, CellId>,
1053 seen: &mut BTreeSet<(RequestId, &'static str)>,
1054 ) -> Result<(), String> {
1055 if active_requests.get(&held.request) != Some(&barrier.cell) {
1056 return Err(format!(
1057 "held output {} on {} behind op {op} is not pinned on {:?}",
1058 held.request,
1059 held.channel.as_str(),
1060 barrier.cell
1061 ));
1062 }
1063 if !seen.insert((held.request, held.channel.as_str())) {
1064 return Err(format!(
1065 "request {} has two outputs held on {}",
1066 held.request,
1067 held.channel.as_str()
1068 ));
1069 }
1070 Ok(())
1071 }
1072
1073 pub fn validate(&self) -> Result<(), String> {
1074 if !self.occupied_below(self.config.max_resident.saturating_add(1)) {
1075 return Err(format!(
1076 "occupied {} exceeds ceiling {}",
1077 self.occupied(),
1078 self.config.max_resident
1079 ));
1080 }
1081 let eviction_ceiling = if self.draining {
1082 self.config.max_releases.max(self.config.max_evictions)
1083 } else {
1084 self.config.max_evictions
1085 };
1086 if self.eviction_permits.len() > eviction_ceiling {
1087 return Err(format!(
1088 "evicting {} exceeds ceiling {}",
1089 self.eviction_permits.len(),
1090 eviction_ceiling
1091 ));
1092 }
1093 let handoffs = self
1094 .quiescing()
1095 .saturating_add(self.eviction_permits.len())
1096 .saturating_add(self.releasing())
1097 .saturating_add(self.adopting());
1098 if self.draining && handoffs > self.config.max_releases {
1099 return Err(format!(
1100 "handoffs {handoffs} exceeds release ceiling {}",
1101 self.config.max_releases
1102 ));
1103 }
1104 if self.activation_permits.len() > self.config.max_activations {
1105 return Err(format!(
1106 "activating {} exceeds ceiling {}",
1107 self.activation_permits.len(),
1108 self.config.max_activations
1109 ));
1110 }
1111
1112 let mut activation_queued = BTreeSet::new();
1113 for id in &self.activation_waiters {
1114 if !activation_queued.insert(id) {
1115 return Err(format!("activation waiter {id:?} is queued twice"));
1116 }
1117 let Some(cell) = self.cells.get(id) else {
1118 return Err(format!("activation waiter {id:?} has no cell state"));
1119 };
1120 if cell.phase != Phase::WaitingActivation || cell.waiting_activation.is_none() {
1121 return Err(format!("activation waiter {id:?} is not waiting"));
1122 }
1123 if self.activation_permits.contains(id) {
1124 return Err(format!("activation waiter {id:?} also holds a permit"));
1125 }
1126 }
1127 for id in &self.activation_permits {
1128 let Some(cell) = self.cells.get(id) else {
1129 return Err(format!("activation permit {id:?} has no cell state"));
1130 };
1131 if !phase_holds_activation(&cell.phase) {
1132 return Err(format!(
1133 "activation permit {id:?} is held in terminal phase {:?}",
1134 cell.phase
1135 ));
1136 }
1137 }
1138
1139 let mut queued = BTreeSet::new();
1140 for id in &self.capacity_waiters {
1141 if !queued.insert(id) {
1142 return Err(format!("capacity waiter {id:?} is queued twice"));
1143 }
1144 let Some(cell) = self.cells.get(id) else {
1145 return Err(format!("capacity waiter {id:?} has no cell state"));
1146 };
1147 if cell.phase != Phase::WaitingCapacity || cell.waiting_for.is_none() {
1148 return Err(format!("capacity waiter {id:?} is not waiting"));
1149 }
1150 }
1151 for (id, cell) in &self.cells {
1152 if cell.quiescing && !matches!(cell.phase, Phase::Resident { .. }) {
1153 return Err(format!(
1154 "cell {id:?} is quiescing in non-resident phase {:?}",
1155 cell.phase
1156 ));
1157 }
1158 if cell.swapping
1159 && !matches!(
1160 cell.phase,
1161 Phase::Resident { .. }
1162 | Phase::Cleaning {
1163 cause: StopCause::Swap,
1164 ..
1165 }
1166 | Phase::Starting { .. }
1167 | Phase::Publishing { .. }
1168 )
1169 {
1170 return Err(format!(
1171 "cell {id:?} is swapping in phase {:?}, outside the swap path",
1172 cell.phase
1173 ));
1174 }
1175 if cell.swap_cancelled && !cell.swapping {
1176 return Err(format!("cell {id:?} carries a swap flag without swapping"));
1177 }
1178 let is_activation_queued = activation_queued.contains(id);
1179 if (cell.phase == Phase::WaitingActivation) != is_activation_queued {
1180 return Err(format!("cell {id:?} activation queue and phase disagree"));
1181 }
1182 if phase_requires_activation_permit(&cell.phase, cell.swapping)
1183 && !self.activation_permits.contains(id)
1184 {
1185 return Err(format!(
1186 "cell {id:?} is in activation phase {:?} without a permit",
1187 cell.phase
1188 ));
1189 }
1190 let is_queued = queued.contains(id);
1191 if (cell.phase == Phase::WaitingCapacity) != is_queued {
1192 return Err(format!("cell {id:?} queue and phase disagree"));
1193 }
1194 for request in &cell.requests {
1195 if self.request_cells.get(request) != Some(id) {
1196 return Err(format!(
1197 "request {request} index disagrees with cell {id:?}"
1198 ));
1199 }
1200 }
1201 // Every in-flight cell op must be resolvable through the index,
1202 // or its completion event will never find this cell.
1203 let indexed = |op: OpId| self.cell_ops.get(&op) == Some(id);
1204 if let Some(op) = phase_op(&cell.phase) {
1205 if !indexed(op) {
1206 return Err(format!("cell {id:?} phase op {op} is not indexed"));
1207 }
1208 }
1209 if let Some(AlarmState::Firing { op, .. }) = cell.alarm {
1210 if !indexed(op) {
1211 return Err(format!("cell {id:?} firing alarm op {op} is not indexed"));
1212 }
1213 }
1214 if let Some(op) = cell.releasing {
1215 if !indexed(op) {
1216 return Err(format!("cell {id:?} release op {op} is not indexed"));
1217 }
1218 }
1219 }
1220 let walked = self
1221 .cells
1222 .values()
1223 .filter(|cell| phase_occupies_capacity(&cell.phase))
1224 .count();
1225 if walked != self.occupied {
1226 return Err(format!(
1227 "occupied counter {} disagrees with the walk {walked}",
1228 self.occupied
1229 ));
1230 }
1231 for (request, id) in &self.request_cells {
1232 if !self
1233 .cells
1234 .get(id)
1235 .is_some_and(|cell| cell.requests.contains(request))
1236 {
1237 return Err(format!("request index {request} has no matching waiter"));
1238 }
1239 }
1240 for op in &self.timed_out_runtime_starts {
1241 let Some(id) = self.cell_ops.get(op) else {
1242 return Err(format!("timed-out runtime start op {op} is not indexed"));
1243 };
1244 if !self.cells.get(id).is_some_and(
1245 |cell| matches!(cell.phase, Phase::Starting { op: current, .. } if current == *op),
1246 ) {
1247 return Err(format!(
1248 "timed-out runtime start op {op} has no matching phase"
1249 ));
1250 }
1251 }
1252 // The reverse index must agree with the map it summarizes, exactly.
1253 let mut recount: BTreeMap<CellId, usize> = BTreeMap::new();
1254 for id in self.active_requests.values() {
1255 *recount.entry(id.clone()).or_insert(0) += 1;
1256 }
1257 if recount != self.active_cells {
1258 return Err(format!(
1259 "active_cells index {:?} disagrees with active_requests {:?}",
1260 self.active_cells, recount
1261 ));
1262 }
1263 for (request, id) in &self.active_requests {
1264 if self.request_cells.contains_key(request) {
1265 return Err(format!("request {request} is both pending and active"));
1266 }
1267 if !self.cells.get(id).is_some_and(|cell| {
1268 matches!(
1269 cell.phase,
1270 Phase::Resident { .. } | Phase::EnsuringDurability { .. }
1271 )
1272 }) {
1273 return Err(format!(
1274 "active request {request} has no resident cell {id:?}"
1275 ));
1276 }
1277 }
1278 // `(request, channel)` identifies a withheld output. The shell keys its
1279 // adapters on that pair, so a second output for the same pair would be
1280 // released once and stranded once.
1281 let mut held_outputs: BTreeSet<(RequestId, &'static str)> = BTreeSet::new();
1282 for (op, barrier) in &self.barriers {
1283 match &barrier.owner {
1284 // A held output keeps its request pinned, so the cell cannot be
1285 // evicted underneath the barrier and a later write of the same
1286 // request can still find it.
1287 GateOwner::Output(held) => {
1288 Self::validate_held(
1289 held,
1290 op,
1291 barrier,
1292 &self.active_requests,
1293 &mut held_outputs,
1294 )?;
1295 }
1296 // An alarm pins nothing: it is not a request, so it has no
1297 // activity to hold. What keeps the cell resident is the firing
1298 // state itself, which `shed_candidate` refuses to evict. The
1299 // phase is deliberately not asserted here — an activity fold
1300 // can retire the firing state while this proof is still in
1301 // flight, and the barrier that outlives it is then settled by
1302 // whichever teardown takes the cell.
1303 GateOwner::Alarm { .. } => {
1304 if !self.cells.contains_key(&barrier.cell) {
1305 return Err(format!(
1306 "gated alarm write op {op} names a cell that is gone: {:?}",
1307 barrier.cell
1308 ));
1309 }
1310 }
1311 }
1312 // A follower is always an output: an alarm opens a barrier and
1313 // never trails one.
1314 for held in &barrier.followers {
1315 Self::validate_held(held, op, barrier, &self.active_requests, &mut held_outputs)?;
1316 }
1317 }
1318 for (id, cell) in &self.cells {
1319 if matches!(cell.alarm, Some(AlarmState::Firing { .. }))
1320 && !matches!(cell.phase, Phase::Resident { .. })
1321 {
1322 return Err(format!("cell {id:?} is firing an alarm while not resident"));
1323 }
1324 if cell
1325 .websockets
1326 .values()
1327 .any(|kind| matches!(kind, WebSocketKind::Regular | WebSocketKind::Outbound))
1328 && !matches!(
1329 cell.phase,
1330 Phase::Resident { .. } | Phase::EnsuringDurability { .. }
1331 )
1332 {
1333 return Err(format!(
1334 "cell {id:?} has a live transport while not resident"
1335 ));
1336 }
1337 }
1338 Ok(())
1339 }
1340
1341 fn op(&mut self) -> OpId {
1342 let op = self.next_op;
1343 self.next_op = self.next_op.checked_add(1).expect("operation id exhausted");
1344 op
1345 }
1346
1347 /// Allocate an op that will live in `cell`'s phase, alarm, or release
1348 /// slot, and index it.
1349 fn cell_op(&mut self, cell: &str) -> OpId {
1350 let op = self.op();
1351 self.cell_ops.insert(op, cell.to_string());
1352 op
1353 }
1354
1355 /// Resolve a completion's op to its cell, consuming the index entry —
1356 /// but only when `predicate` confirms the cell still holds the op. On a
1357 /// mismatch the entry stays: the op's real completion has not arrived
1358 /// yet (an expiry can probe the wrong handler), and it must still find
1359 /// its way here later.
1360 fn take_cell_op(&mut self, op: OpId, predicate: impl Fn(&Cell) -> bool) -> Option<CellId> {
1361 let id = self.cell_ops.get(&op)?.clone();
1362 if !self.cells.get(&id).is_some_and(predicate) {
1363 return None;
1364 }
1365 self.cell_ops.remove(&op);
1366 Some(id)
1367 }
1368
1369 fn has_capacity(&self) -> bool {
1370 // Residency is a hard cap, known exactly and counted -- never sampled.
1371 // A node at its cell cap is at capacity, not overloaded: it refuses
1372 // more and holds what it has, rather than shedding a live cell it must
1373 // then place again elsewhere. The only sampled fact that refuses
1374 // admission is genuine memory pressure, which a cell count
1375 // cannot see.
1376 self.occupied_below(self.config.max_resident) && !self.shedding
1377 }
1378
1379 pub fn is_active(&self, id: &str) -> bool {
1380 self.active_cells.contains_key(id)
1381 || self.cells.get(id).is_some_and(|cell| {
1382 cell.websockets
1383 .values()
1384 .any(|kind| matches!(kind, WebSocketKind::Regular | WebSocketKind::Outbound))
1385 })
1386 }
1387
1388 /// Record `request` as active on `cell`, keeping the `active_cells`
1389 /// reverse index in step with `active_requests`. Every insert into
1390 /// `active_requests` goes through here so the two never disagree.
1391 fn activate_request(&mut self, request: RequestId, cell: CellId) {
1392 *self.active_cells.entry(cell.clone()).or_insert(0) += 1;
1393 self.active_requests.insert(request, cell);
1394 }
1395
1396 /// Drop `request` from the active set, decrementing its cell's index and
1397 /// forgetting the cell once no request targets it. Returns the cell the
1398 /// request held, as `active_requests.remove` did.
1399 fn deactivate_request(&mut self, request: RequestId) -> Option<CellId> {
1400 let cell = self.active_requests.remove(&request)?;
1401 if let Some(count) = self.active_cells.get_mut(&cell) {
1402 *count -= 1;
1403 if *count == 0 {
1404 self.active_cells.remove(&cell);
1405 }
1406 }
1407 Some(cell)
1408 }
1409
1410 /// Hibernated (Durable Objects state 4): out of memory, still on this
1411 /// host, with WebSocket clients parked at the network layer. Nothing in
1412 /// memory survives -- the next event runs the constructor again, exactly
1413 /// as a cold start does -- so the surviving sockets are the whole of the
1414 /// difference from `Inactive`.
1415 pub fn is_hibernated(&self, id: &str) -> bool {
1416 self.cells.get(id).is_some_and(|cell| {
1417 matches!(cell.phase, Phase::Dormant { .. })
1418 && cell
1419 .websockets
1420 .values()
1421 .any(|kind| matches!(kind, WebSocketKind::Hibernatable))
1422 })
1423 }
1424
1425 /// Hibernatable (Durable Objects state 2): resident, doing no work, and
1426 /// holding nothing that must survive in memory. State 3 is the negation --
1427 /// resident and idle, but pinned by a `Regular` or `Outbound` socket that
1428 /// cannot outlive the isolate.
1429 ///
1430 /// This is the cell's own criteria, not a decision to evict. celld also
1431 /// refuses eviction for an imminent or uncovered alarm and for state the
1432 /// bucket cannot restore; those are policy and are checked separately.
1433 pub fn is_hibernatable(&self, id: &str) -> bool {
1434 self.cells
1435 .get(id)
1436 .is_some_and(|cell| matches!(cell.phase, Phase::Resident { .. }))
1437 && !self.is_active(id)
1438 }
1439
1440 pub fn websocket_count(&self, id: &str) -> usize {
1441 self.cells.get(id).map_or(0, |cell| cell.websockets.len())
1442 }
1443
1444 fn complete_request(
1445 &mut self,
1446 id: &str,
1447 request: RequestId,
1448 result: Result<Route, RequestError>,
1449 effects: &mut Vec<Effect>,
1450 ) {
1451 self.capacity_requests.remove(&request);
1452 self.handoff_requests.remove(&request);
1453 match &result {
1454 Ok(Route::Local) => {
1455 self.activate_request(request, id.to_string());
1456 let now = self.now_mono_ms;
1457 if let Some(cell) = self.cells.get_mut(id) {
1458 cell.last_used_mono_ms = now;
1459 }
1460 }
1461 Ok(Route::Remote { .. }) => {
1462 self.activity.proxied = self.activity.proxied.saturating_add(1);
1463 }
1464 Err(_) => {}
1465 }
1466 effects.push(Effect::Complete { request, result });
1467 }
1468
1469 fn record_acquisition(&mut self, spec: &RestoreSpec) {
1470 self.activity.acquired = self.activity.acquired.saturating_add(1);
1471 if spec.took_over {
1472 self.activity.expired_owner_leases =
1473 self.activity.expired_owner_leases.saturating_add(1);
1474 }
1475 if spec.epoch > 1 {
1476 self.activity.advanced_epochs = self.activity.advanced_epochs.saturating_add(1);
1477 }
1478 }
1479
1480 fn worker_request(&mut self, request: RequestId, effects: &mut Vec<Effect>) {
1481 let route = self
1482 .cells
1483 .iter()
1484 .filter_map(|(id, cell)| {
1485 let (epoch, retired_durability) = match cell.phase {
1486 Phase::Resident { epoch } => (epoch, None),
1487 Phase::EnsuringDurability { op, epoch } => (epoch, Some(op)),
1488 _ => return None,
1489 };
1490 if cell.quiescing
1491 || self.is_active(id)
1492 || matches!(cell.alarm, Some(AlarmState::Firing { .. }))
1493 {
1494 return None;
1495 }
1496 Some((id.clone(), epoch, retired_durability))
1497 })
1498 .find(|(id, _, _)| self.worker_cursor.as_ref().is_none_or(|cursor| id > cursor))
1499 .or_else(|| {
1500 self.cells.iter().find_map(|(id, cell)| {
1501 let (epoch, retired_durability) = match cell.phase {
1502 Phase::Resident { epoch } => (epoch, None),
1503 Phase::EnsuringDurability { op, epoch } => (epoch, Some(op)),
1504 _ => return None,
1505 };
1506 (!cell.quiescing
1507 && !self.is_active(id)
1508 && !matches!(cell.alarm, Some(AlarmState::Firing { .. })))
1509 .then(|| (id.clone(), epoch, retired_durability))
1510 })
1511 })
1512 .map(|(cell, epoch, retired_durability)| WorkerRoute {
1513 cell,
1514 epoch,
1515 retired_durability,
1516 });
1517
1518 if let Some(route) = &route {
1519 self.worker_cursor = Some(route.cell.clone());
1520 self.activate_request(request, route.cell.clone());
1521 if let Some(cell) = self.cells.get_mut(&route.cell) {
1522 if matches!(cell.phase, Phase::EnsuringDurability { .. }) {
1523 // Same rescue as `request_authorized`: the permit taken
1524 // at nomination comes back with the cell.
1525 if let Some(stale) = phase_op(&cell.phase) {
1526 self.cell_ops.remove(&stale);
1527 }
1528 set_phase(
1529 &mut self.occupied,
1530 cell,
1531 Phase::Resident { epoch: route.epoch },
1532 );
1533 self.eviction_permits.remove(&route.cell);
1534 }
1535 cell.last_used_mono_ms = self.now_mono_ms;
1536 }
1537 }
1538 effects.push(Effect::CompleteWorker { request, route });
1539 }
1540
1541 fn finish_requests(
1542 &mut self,
1543 id: &str,
1544 cell: &mut Cell,
1545 result: Result<Route, RequestError>,
1546 effects: &mut Vec<Effect>,
1547 ) {
1548 for request in std::mem::take(&mut cell.requests) {
1549 self.request_cells.remove(&request);
1550 self.complete_request(id, request, result.clone(), effects);
1551 }
1552 }
1553
1554 fn begin_cold_route(
1555 &mut self,
1556 id: &str,
1557 cell: &mut Cell,
1558 start: ColdStart,
1559 effects: &mut Vec<Effect>,
1560 ) {
1561 debug_assert!(self.activation_permits.contains(id));
1562 cell.waiting_activation = None;
1563 match start {
1564 ColdStart::ReadOwner => {
1565 let op = self.cell_op(id);
1566 set_phase(&mut self.occupied, cell, Phase::ReadingOwner { op });
1567 effects.push(Effect::ReadOwner {
1568 op,
1569 cell: id.to_string(),
1570 });
1571 }
1572 ColdStart::Restore(spec) => {
1573 self.activate_or_wait(id, cell, Activation::Restore(spec), effects)
1574 }
1575 }
1576 }
1577
1578 fn admit_or_queue_activation(
1579 &mut self,
1580 id: &str,
1581 cell: &mut Cell,
1582 start: ColdStart,
1583 effects: &mut Vec<Effect>,
1584 ) {
1585 if self.activation_permits.contains(id) {
1586 self.begin_cold_route(id, cell, start, effects);
1587 } else if self.activation_permits.len() < self.config.max_activations {
1588 self.activation_permits.insert(id.to_string());
1589 self.begin_cold_route(id, cell, start, effects);
1590 } else {
1591 set_phase(&mut self.occupied, cell, Phase::WaitingActivation);
1592 cell.waiting_activation = Some(start);
1593 self.activation_waiters.push_back(id.to_string());
1594 self.watch_queued(id, cell, effects);
1595 }
1596 }
1597
1598 fn pump_activations(&mut self, effects: &mut Vec<Effect>) {
1599 self.activation_permits.retain(|id| {
1600 self.cells
1601 .get(id)
1602 .is_some_and(|cell| phase_holds_activation(&cell.phase))
1603 });
1604
1605 while self.activation_permits.len() < self.config.max_activations {
1606 let Some(id) = self.activation_waiters.pop_front() else {
1607 break;
1608 };
1609 let Some(mut cell) = self.cells.remove(&id) else {
1610 continue;
1611 };
1612 if cell.phase != Phase::WaitingActivation {
1613 self.cells.insert(id, cell);
1614 continue;
1615 }
1616 let Some(start) = cell.waiting_activation.take() else {
1617 self.cells.insert(id, cell);
1618 continue;
1619 };
1620 if cell.requests.is_empty() && !cell.alarm_wake && !cell.resume_demand {
1621 set_phase(
1622 &mut self.occupied,
1623 &mut cell,
1624 match start {
1625 ColdStart::ReadOwner => Phase::Inactive,
1626 ColdStart::Restore(spec) => Phase::Dormant { epoch: spec.epoch },
1627 },
1628 );
1629 } else {
1630 self.activation_permits.insert(id.clone());
1631 self.begin_cold_route(&id, &mut cell, start, effects);
1632 }
1633 self.cells.insert(id, cell);
1634 }
1635 }
1636
1637 /// Adopt the exact epochs encoded by a clean predecessor's local paths.
1638 /// The node lease CAS that caused this event is the ownership proof, so
1639 /// this path deliberately emits no per-cell ownership effects.
1640 fn local_cells_read(
1641 &mut self,
1642 result: Result<Vec<LocalCell>, Failure>,
1643 effects: &mut Vec<Effect>,
1644 ) {
1645 if !self.resuming {
1646 return;
1647 }
1648 let Ok(mut cells) = result else {
1649 self.resuming = false;
1650 return;
1651 };
1652 cells.sort();
1653 cells.dedup();
1654 if cells.len() > self.config.max_resident || !self.cells.is_empty() {
1655 self.resuming = false;
1656 return;
1657 }
1658 for local in cells {
1659 let mut cell = Cell {
1660 resume_demand: true,
1661 ..Cell::default()
1662 };
1663 self.resuming_cells.insert(local.id.clone());
1664 self.admit_or_queue_activation(
1665 &local.id,
1666 &mut cell,
1667 ColdStart::Restore(RestoreSpec {
1668 epoch: local.epoch,
1669 fresh: false,
1670 took_over: false,
1671 resume_local: true,
1672 prior: None,
1673 }),
1674 effects,
1675 );
1676 self.cells.insert(local.id, cell);
1677 }
1678 if self.resuming_cells.is_empty() {
1679 self.resuming = false;
1680 }
1681 }
1682
1683 fn settle_local_resume(&mut self, id: &str) {
1684 if self.resuming_cells.remove(id) && self.resuming_cells.is_empty() {
1685 self.resuming = false;
1686 }
1687 if let Some(cell) = self.cells.get_mut(id) {
1688 cell.resume_demand = false;
1689 }
1690 }
1691
1692 fn begin_activation(
1693 &mut self,
1694 id: &str,
1695 cell: &mut Cell,
1696 activation: Activation,
1697 effects: &mut Vec<Effect>,
1698 ) {
1699 debug_assert!(self.has_capacity());
1700 cell.waiting_for = None;
1701 let op = self.cell_op(id);
1702 match activation {
1703 Activation::Claim(claim) => {
1704 set_phase(
1705 &mut self.occupied,
1706 cell,
1707 Phase::Acquiring {
1708 op,
1709 claim: claim.clone(),
1710 },
1711 );
1712 effects.push(Effect::CasOwner {
1713 op,
1714 cell: id.to_string(),
1715 guard: claim.guard,
1716 epoch: claim.epoch,
1717 takeover: claim.takeover,
1718 });
1719 }
1720 Activation::Restore(spec) => {
1721 set_phase(
1722 &mut self.occupied,
1723 cell,
1724 Phase::Restoring {
1725 op,
1726 spec: spec.clone(),
1727 },
1728 );
1729 effects.push(Effect::Restore {
1730 op,
1731 cell: id.to_string(),
1732 spec,
1733 });
1734 }
1735 }
1736 }
1737
1738 fn activate_or_wait(
1739 &mut self,
1740 id: &str,
1741 cell: &mut Cell,
1742 activation: Activation,
1743 effects: &mut Vec<Effect>,
1744 ) {
1745 if cell.requests.is_empty() && !cell.alarm_wake && !cell.resume_demand {
1746 set_phase(
1747 &mut self.occupied,
1748 cell,
1749 match activation {
1750 Activation::Claim(_) => Phase::Inactive,
1751 Activation::Restore(spec) => Phase::Dormant { epoch: spec.epoch },
1752 },
1753 );
1754 } else if self.has_capacity() {
1755 self.begin_activation(id, cell, activation, effects);
1756 } else {
1757 set_phase(&mut self.occupied, cell, Phase::WaitingCapacity);
1758 cell.waiting_for = Some(activation);
1759 self.capacity_waiters.push_back(id.to_string());
1760 self.watch_queued(id, cell, effects);
1761 self.shed_one(effects);
1762 }
1763 }
1764
1765 fn pump_capacity(&mut self, effects: &mut Vec<Effect>) {
1766 while self.has_capacity() {
1767 let Some(id) = self.capacity_waiters.pop_front() else {
1768 break;
1769 };
1770 let Some(mut cell) = self.cells.remove(&id) else {
1771 continue;
1772 };
1773 if cell.phase != Phase::WaitingCapacity {
1774 self.cells.insert(id, cell);
1775 continue;
1776 }
1777 let Some(activation) = cell.waiting_for.take() else {
1778 self.cells.insert(id, cell);
1779 continue;
1780 };
1781 if cell.requests.is_empty() && !cell.alarm_wake && !cell.resume_demand {
1782 set_phase(
1783 &mut self.occupied,
1784 &mut cell,
1785 match activation {
1786 Activation::Claim(_) => Phase::Inactive,
1787 Activation::Restore(spec) => Phase::Dormant { epoch: spec.epoch },
1788 },
1789 );
1790 } else {
1791 self.begin_activation(&id, &mut cell, activation, effects);
1792 }
1793 self.cells.insert(id, cell);
1794 }
1795 self.shed_one(effects);
1796 }
1797
1798 fn start_node_lease(&mut self, now_ms: u64, spec: NodeLeaseSpec, effects: &mut Vec<Effect>) {
1799 if !matches!(
1800 self.node_authority,
1801 NodeAuthority::Unstarted | NodeAuthority::Failed
1802 ) {
1803 return;
1804 }
1805 self.begin_node_lease_acquisition(now_ms, spec, effects);
1806 }
1807
1808 fn begin_node_lease_acquisition(
1809 &mut self,
1810 now_ms: u64,
1811 spec: NodeLeaseSpec,
1812 effects: &mut Vec<Effect>,
1813 ) {
1814 let desired = NodeLeaseRecord {
1815 node: self.node.clone(),
1816 addr: spec.addr.clone(),
1817 expires_ms: now_ms.saturating_add(spec.ttl_ms),
1818 peer_protocol: spec.peer_protocol,
1819 generation: spec.generation.clone(),
1820 // A fresh session has not opened a log; the predecessor's
1821 // state was recovered before this install (the engine's
1822 // startup order), so None is the truth, not a reset.
1823 log_state: None,
1824 etag: String::new(),
1825 };
1826 let pending = PendingNodeLease {
1827 spec,
1828 desired,
1829 prior: None,
1830 readback_only: false,
1831 anchor_mono_ms: self.now_mono_ms,
1832 resume_local: false,
1833 };
1834 let op = self.op();
1835 self.node_authority = NodeAuthority::Reading { op, pending };
1836 effects.push(Effect::ReadSelfNodeLease { op });
1837 }
1838
1839 fn fail_initial_node_lease(&mut self, spec: NodeLeaseSpec, effects: &mut Vec<Effect>) {
1840 // Nothing else will ever ask: `StartNodeLease` is a one-shot at
1841 // process start. Arm the retry here or this node is done serving.
1842 // The renewal cadence is the right interval -- it is already the
1843 // rate this fleet has decided its bucket can carry.
1844 let generation = self.next_timer_generation;
1845 self.next_timer_generation = self
1846 .next_timer_generation
1847 .checked_add(1)
1848 .expect("timer generation exhausted");
1849 let retry_after = (spec.ttl_ms / 3).max(1);
1850 effects.push(Effect::ScheduleTimer {
1851 timer: Timer::NodeLeaseRenew { generation },
1852 at_mono_ms: self.now_mono_ms.saturating_add(retry_after),
1853 });
1854 self.node_authority = NodeAuthority::Retrying { spec, generation };
1855 }
1856
1857 /// A lease write landed. Decide whether it actually preserved authority,
1858 /// and if so install it anchored to the instant its `expires_ms` was
1859 /// sampled.
1860 ///
1861 /// A renewal that lands at or after the PRIOR lease's expiry has not
1862 /// extended anything: every peer was already entitled to read that record,
1863 /// find it dead, and seize this node's cells, and one of them may have
1864 /// begun doing exactly that. Rewriting `nodes/<node>.json` does not
1865 /// retract a takeover already in flight -- the ownership compare-and-swap
1866 /// a peer is about to issue is guarded on the ownership record's ETag,
1867 /// which a resident owner never touches -- so resurrecting the lease here
1868 /// is precisely how two nodes end up serving one cell. The gap is a fence,
1869 /// not a hiccup.
1870 fn complete_node_lease_write(
1871 &mut self,
1872 pending: PendingNodeLease,
1873 record: NodeLeaseRecord,
1874 now_mono_ms: u64,
1875 effects: &mut Vec<Effect>,
1876 ) {
1877 // The record just published expires at `anchor + ttl`. A round trip
1878 // that outlived that window landed a lease which is already dead to
1879 // every peer reading the bucket, so this process must not act on it.
1880 let expired = now_mono_ms.saturating_sub(pending.anchor_mono_ms) >= pending.spec.ttl_ms;
1881 match &pending.prior {
1882 // A renewal only preserves authority if it lands while the PRIOR
1883 // lease is still valid. Losing that continuity means peers were
1884 // already entitled to seize this node's cells.
1885 Some(prior) => {
1886 if expired || now_mono_ms.saturating_sub(prior.last_ok_mono_ms) >= prior.spec.ttl_ms
1887 {
1888 self.fence_node(effects);
1889 return;
1890 }
1891 }
1892 // An initial acquisition that lands expired never became
1893 // authoritative: this node owns nothing and is serving nothing, so
1894 // there is no runtime to fence and no reason to halt. Fail the
1895 // waiters and let a later request retry from a fresh sample.
1896 None => {
1897 if expired {
1898 self.fail_initial_node_lease(pending.spec, effects);
1899 return;
1900 }
1901 }
1902 }
1903 let resume_local = pending.resume_local;
1904 self.hold_node_lease(
1905 pending.spec,
1906 record,
1907 pending.anchor_mono_ms,
1908 resume_local,
1909 effects,
1910 );
1911 }
1912
1913 /// Install a held lease. `anchor_mono_ms` is the monotonic instant the
1914 /// record's `expires_ms` was computed from -- NOT the instant the write
1915 /// completed. See [`PendingNodeLease::anchor_mono_ms`].
1916 fn hold_node_lease(
1917 &mut self,
1918 spec: NodeLeaseSpec,
1919 record: NodeLeaseRecord,
1920 anchor_mono_ms: u64,
1921 resume_local: bool,
1922 effects: &mut Vec<Effect>,
1923 ) {
1924 let generation = self.next_timer_generation;
1925 self.next_timer_generation = self
1926 .next_timer_generation
1927 .checked_add(1)
1928 .expect("timer generation exhausted");
1929 // A nudge that arrived mid-write could not ride the write that
1930 // just landed (its body predates the publish): renew again NOW.
1931 let renew_after = if std::mem::take(&mut self.nudge_pending) {
1932 1
1933 } else {
1934 (spec.ttl_ms / 3).max(1)
1935 };
1936 effects.push(Effect::ScheduleTimer {
1937 timer: Timer::NodeLeaseRenew { generation },
1938 at_mono_ms: anchor_mono_ms.saturating_add(renew_after),
1939 });
1940 // Exactly the published deadline. A peer treats the record as live
1941 // while `expires_ms > now_ms`, so this node must have stopped serving
1942 // by the time `now_ms` reaches `expires_ms` -- not one millisecond
1943 // after it.
1944 effects.push(Effect::ScheduleTimer {
1945 timer: Timer::NodeLeaseFence { generation },
1946 at_mono_ms: anchor_mono_ms.saturating_add(spec.ttl_ms),
1947 });
1948 self.node_authority = NodeAuthority::Held(HeldNodeLease {
1949 spec,
1950 record,
1951 last_ok_mono_ms: anchor_mono_ms,
1952 last_attempt_mono_ms: anchor_mono_ms,
1953 timer_generation: generation,
1954 });
1955 if resume_local {
1956 self.resuming = true;
1957 effects.push(Effect::ReadLocalCells);
1958 }
1959 }
1960
1961 fn resume_node_lease_after_failure(
1962 &mut self,
1963 prior: HeldNodeLease,
1964 now_mono_ms: u64,
1965 effects: &mut Vec<Effect>,
1966 ) {
1967 // A publish that arrived mid-write must not wait a full ttl/3
1968 // behind a transient failure: the
1969 // OwnLog waiter's deadline is shorter than that.
1970 let retry_after = if std::mem::take(&mut self.nudge_pending) {
1971 1
1972 } else {
1973 (prior.spec.ttl_ms / 3).max(1)
1974 };
1975 effects.push(Effect::ScheduleTimer {
1976 timer: Timer::NodeLeaseRenew {
1977 generation: prior.timer_generation,
1978 },
1979 at_mono_ms: now_mono_ms.saturating_add(retry_after),
1980 });
1981 self.node_authority = NodeAuthority::Held(prior);
1982 }
1983
1984 fn begin_node_lease_write(
1985 &mut self,
1986 pending: PendingNodeLease,
1987 guard: CasGuard,
1988 effects: &mut Vec<Effect>,
1989 ) {
1990 let op = self.op();
1991 let record = pending.desired.clone();
1992 let authority_expires_ms = pending.prior.as_ref().map(|prior| prior.record.expires_ms);
1993 self.node_authority = NodeAuthority::Writing { op, pending };
1994 effects.push(Effect::CasNodeLease {
1995 op,
1996 guard,
1997 record,
1998 authority_expires_ms,
1999 });
2000 }
2001
2002 fn read_self_node_lease(
2003 &mut self,
2004 op: OpId,
2005 now_ms: u64,
2006 now_mono_ms: u64,
2007 result: Result<Option<NodeLeaseRecord>, Failure>,
2008 effects: &mut Vec<Effect>,
2009 ) {
2010 let authority = std::mem::replace(&mut self.node_authority, NodeAuthority::Failed);
2011 let NodeAuthority::Reading {
2012 op: current,
2013 pending,
2014 } = authority
2015 else {
2016 self.node_authority = authority;
2017 return;
2018 };
2019 if current != op {
2020 self.node_authority = NodeAuthority::Reading {
2021 op: current,
2022 pending,
2023 };
2024 return;
2025 }
2026 match result {
2027 Err(_) => {
2028 if let Some(prior) = pending.prior {
2029 self.resume_node_lease_after_failure(prior, now_mono_ms, effects);
2030 } else {
2031 self.fail_initial_node_lease(pending.spec, effects);
2032 }
2033 }
2034 Ok(Some(record)) if same_node_lease(&record, &pending.desired) => {
2035 self.complete_node_lease_write(pending, record, now_mono_ms, effects);
2036 }
2037 Ok(Some(record))
2038 if pending
2039 .prior
2040 .as_ref()
2041 .is_some_and(|prior| same_node_lease(&record, &prior.record)) =>
2042 {
2043 let mut prior = pending.prior.expect("checked above");
2044 prior.record.etag = record.etag;
2045 self.resume_node_lease_after_failure(prior, now_mono_ms, effects);
2046 }
2047 Ok(Some(record))
2048 if pending.prior.as_ref().is_some_and(|prior| {
2049 record.node == pending.desired.node
2050 && record.addr == pending.desired.addr
2051 && record.peer_protocol == pending.desired.peer_protocol
2052 && record.generation == pending.desired.generation
2053 && record.log_state == pending.desired.log_state
2054 && record.expires_ms > prior.record.expires_ms
2055 && record.expires_ms <= pending.desired.expires_ms
2056 }) =>
2057 {
2058 // Our own zombie: every identity field ours, including the
2059 // folded log state a peer's recovery stamp would have
2060 // changed, and only the expiry moved — no further than an
2061 // attempt of ours could have written. An earlier ambiguous
2062 // renewal landed after its readback missed it (#482). Adopt
2063 // the record: the mono credit is the wall delta the zombie
2064 // provably added, and the fresh fence timer enforces the
2065 // adopted deadline while the stale one no-ops against the
2066 // bumped anchor.
2067 let mut prior = pending.prior.expect("checked above");
2068 let delta = record.expires_ms.saturating_sub(prior.record.expires_ms);
2069 prior.last_ok_mono_ms = prior.last_ok_mono_ms.saturating_add(delta);
2070 prior.record = record;
2071 // An adoption happens only after an ambiguous attempt, its
2072 // readback, a cadence wait, a rejection, and a second
2073 // readback have eaten most of the TTL, so the adopted
2074 // headroom is always thin. The 2026-08-28T07:43Z field
2075 // fence landed one millisecond past an adopted expiry with
2076 // the cadence-scheduled renewal 54 ms from completion.
2077 // Renew NOW, on the nudge lane.
2078 self.nudge_pending = true;
2079 effects.push(Effect::ScheduleTimer {
2080 timer: Timer::NodeLeaseFence {
2081 generation: prior.timer_generation,
2082 },
2083 at_mono_ms: prior.last_ok_mono_ms.saturating_add(prior.spec.ttl_ms),
2084 });
2085 self.resume_node_lease_after_failure(prior, now_mono_ms, effects);
2086 }
2087 Ok(record) if pending.prior.is_some() => {
2088 // A renewal was ambiguous and read-back no longer names our
2089 // exact generation, or the record vanished. Authority is lost.
2090 let _ = record;
2091 self.fence_node(effects);
2092 }
2093 Ok(_) if pending.readback_only => {
2094 // The ambiguous initial write did not publish the exact
2095 // desired generation. Fail this activation; a later request
2096 // may retry from a fresh read, but this one cannot spin.
2097 self.fail_initial_node_lease(pending.spec, effects);
2098 }
2099 Ok(Some(record)) => {
2100 // The record we are
2101 // about to replace carries the predecessor's folded log
2102 // state, and our install writes a fresh one — so a
2103 // not-sealed predecessor log here means recovery has NOT
2104 // run, and installing would erase the only evidence it
2105 // was needed. The engine's boot order makes this
2106 // unreachable; the guard keeps it structurally so.
2107 let predecessor_unrecovered = pending.prior.is_none()
2108 && record.generation != pending.desired.generation
2109 && !matches!(
2110 record.log_state,
2111 None | Some(crate::log_tier::LogState::Sealed)
2112 );
2113 if predecessor_unrecovered {
2114 self.fail_initial_node_lease(pending.spec, effects);
2115 return;
2116 }
2117 // A configured node id is a singleton key: restarting that
2118 // node replaces its prior process generation immediately. The
2119 // ETag still serializes competing replacements, and a process
2120 // which loses that CAS never becomes authoritative.
2121 let mut pending = pending;
2122 pending.resume_local = pending.prior.is_none()
2123 && !pending.readback_only
2124 && record.expires_ms > now_ms
2125 && pending.spec.resume_generation.as_deref()
2126 == Some(record.generation.as_str());
2127 self.begin_node_lease_write(pending, CasGuard::Match(record.etag), effects);
2128 }
2129 Ok(None) => self.begin_node_lease_write(pending, CasGuard::Absent, effects),
2130 }
2131 }
2132
2133 fn node_lease_cas_completed(
2134 &mut self,
2135 op: OpId,
2136 now_mono_ms: u64,
2137 result: Result<LeaseCasOutcome, Failure>,
2138 stamped_log_state: Option<crate::log_tier::LogState>,
2139 effects: &mut Vec<Effect>,
2140 ) {
2141 let authority = std::mem::replace(&mut self.node_authority, NodeAuthority::Failed);
2142 let NodeAuthority::Writing {
2143 op: current,
2144 pending,
2145 } = authority
2146 else {
2147 self.node_authority = authority;
2148 return;
2149 };
2150 if current != op {
2151 self.node_authority = NodeAuthority::Writing {
2152 op: current,
2153 pending,
2154 };
2155 return;
2156 }
2157 match result {
2158 Ok(LeaseCasOutcome::Applied { etag }) => {
2159 let mut record = pending.desired.clone();
2160 record.etag = etag;
2161 // The shell stamps the folded log into the body at
2162 // serialization, after the core chose `desired`: the held
2163 // record must track the body that actually landed, or the next ambiguous
2164 // readback compares the bucket's truth against a stale
2165 // belief and self-fences a healthy node.
2166 record.log_state = stamped_log_state;
2167 self.complete_node_lease_write(pending, record, now_mono_ms, effects);
2168 }
2169 Ok(LeaseCasOutcome::Rejected) => {
2170 // A rejected renewal is NOT proof of usurpation: an earlier
2171 // AMBIGUOUS renewal can land after its own readback missed
2172 // it, and then the ETag moved under our hand (#482 — R2
2173 // throttling manufactured exactly this, and fencing here
2174 // halted a healthy follower with 549ms of real authority
2175 // left). Read back and decide from the record; the readback
2176 // compares against what the shell actually serialized, for
2177 // the same reason the ambiguous arm does.
2178 let read = self.op();
2179 let mut pending = pending;
2180 pending.desired.log_state = stamped_log_state;
2181 self.node_authority = NodeAuthority::Reading { op: read, pending };
2182 effects.push(Effect::ReadSelfNodeLease { op: read });
2183 }
2184 Err(Failure::Ambiguous) => {
2185 let read = self.op();
2186 let mut pending = pending;
2187 pending.readback_only = true;
2188 // The readback compares against what the shell actually
2189 // serialized into this attempt, never the core's
2190 // pre-attempt belief.
2191 pending.desired.log_state = stamped_log_state;
2192 self.node_authority = NodeAuthority::Reading { op: read, pending };
2193 effects.push(Effect::ReadSelfNodeLease { op: read });
2194 }
2195 Err(Failure::Definite) => {
2196 if let Some(prior) = pending.prior {
2197 self.resume_node_lease_after_failure(prior, now_mono_ms, effects);
2198 } else {
2199 self.fail_initial_node_lease(pending.spec, effects);
2200 }
2201 }
2202 }
2203 }
2204
2205 /// Arm a deadline for every activation effect this event produced.
2206 ///
2207 /// Done once, centrally, rather than at each of the eleven sites that emit
2208 /// one: those are eleven chances to forget, and a forgotten deadline is
2209 /// invisible until something hangs. The effect list already names every
2210 /// operation the executor is about to start, so it is the natural place to
2211 /// decide which of them are worth watching.
2212 fn arm_operation_deadlines(&mut self, effects: &mut Vec<Effect>) {
2213 let Some(deadline_ms) = self.config.operation_deadline_ms else {
2214 return;
2215 };
2216 let watched: Vec<OpId> = effects
2217 .iter()
2218 .filter_map(|effect| match effect {
2219 // Every operation that holds something back. The activation
2220 // stages hold a caller; a durability proof holds an eviction;
2221 // a firing alarm holds the cell out of dormancy. All three
2222 // keep the ownership record claimed while they wait.
2223 //
2224 // `StopRuntime` is the deliberate exception. It has no failure
2225 // handling to reuse -- a stop cannot fail, it can only not
2226 // finish -- so abandoning one would mean declaring a runtime
2227 // gone while it may still be running. That needs a decision,
2228 // not a timer.
2229 // A restore is a sequence of individually bounded object-store
2230 // requests. Its total duration scales with the replica. The
2231 // shell cannot cancel the task, so retiring the core op would
2232 // discard late success and let another request duplicate it.
2233 Effect::Restore { .. } => None,
2234 Effect::ReadOwner { op, .. }
2235 | Effect::ReadNodeLease { op, .. }
2236 | Effect::ReadCapacityPeers { op, .. }
2237 | Effect::CasOwner { op, .. }
2238 | Effect::StartRuntime { op, .. }
2239 | Effect::Publish { op, .. }
2240 | Effect::EnsureDurable { op, .. }
2241 // A held write response: a swallowed durability proof must not
2242 // hang a client forever.
2243 | Effect::AwaitDurable { op, .. }
2244 | Effect::FireAlarm { op, .. } => Some(*op),
2245 _ => None,
2246 })
2247 .collect();
2248 let at_mono_ms = self.now_mono_ms.saturating_add(deadline_ms);
2249 for op in watched {
2250 effects.push(Effect::ScheduleTimer {
2251 timer: Timer::OperationDeadline { op },
2252 at_mono_ms,
2253 });
2254 }
2255 }
2256
2257 /// An activation effect outlived its deadline.
2258 ///
2259 /// Expiry deliberately reuses each stage's own failure handling rather
2260 /// than introducing a second way to abandon work: the core already knows
2261 /// how to reconcile an ambiguous acquire and how to fail a read, and a
2262 /// deadline is only a different reason for reaching those paths.
2263 ///
2264 /// The classification is the whole substance. A read cannot have committed
2265 /// anything, so it is definite. Everything past it may have taken effect
2266 /// on the far side while the answer was lost, so it is ambiguous — the
2267 /// same distinction that decides whether a retry is safe. Calling a
2268 /// timed-out compare-and-swap definite would let a second attempt
2269 /// overwrite an epoch that had in fact been applied.
2270 fn expire_operation(&mut self, op: OpId, now_ms: u64, effects: &mut Vec<Effect>) {
2271 // A gated write is tracked in `barriers`, not the op index.
2272 // Ambiguous is the only safe class: the write may or may not be
2273 // durable, so the client must not be told it succeeded.
2274 if self.barriers.contains_key(&op) {
2275 // Source is irrelevant on a failed proof; Bucket is the
2276 // conservative label.
2277 self.durable_reached(op, Err(Failure::Ambiguous), ProofSource::Bucket, effects);
2278 return;
2279 }
2280 // A peek, not a take: each arm below re-enters the op's own
2281 // completion handler, and that handler consumes the index entry.
2282 let Some(id) = self.cell_ops.get(&op).cloned() else {
2283 // Already answered, superseded, or fenced. A stale deadline has
2284 // nothing to expire, which is the ordinary case.
2285 return;
2286 };
2287 let Some(cell) = self.cells.get(&id) else {
2288 return;
2289 };
2290 // A firing alarm is tracked on the cell rather than in its phase, so
2291 // it is looked for first. Expiry re-arms it exactly as a failed
2292 // handler would, which keeps alarms at-least-once instead of turning
2293 // a stuck handler into a lost one.
2294 if matches!(cell.alarm, Some(AlarmState::Firing { op: current, .. }) if current == op) {
2295 // The cell comes from the index here, unlike the event, which
2296 // carries its own: an expiry that cannot find the op has nothing
2297 // to time out, so depending on the index is safe, while the event
2298 // cannot depend on it because a fold may retire the firing state
2299 // while the write it reports is still unproven. The epoch is read
2300 // for completeness and never used — a failure opens no gate, and
2301 // the gate is the only thing `alarm_finished` reads it for.
2302 let epoch = match cell.phase {
2303 Phase::Resident { epoch } => epoch,
2304 _ => 0,
2305 };
2306 let (id, now_mono_ms) = (id.clone(), self.now_mono_ms);
2307 self.alarm_finished(
2308 op,
2309 (id, epoch),
2310 now_ms,
2311 now_mono_ms,
2312 Err(Failure::Ambiguous),
2313 effects,
2314 );
2315 return;
2316 }
2317 if phase_op(&cell.phase) != Some(op) {
2318 return;
2319 }
2320 let phase = Some(cell.phase.clone());
2321 match phase {
2322 Some(Phase::ReadingOwner { .. }) => {
2323 self.owner_read(op, 0, Err(Failure::Definite), effects)
2324 }
2325 Some(Phase::ReadingNodeLease { .. }) => {
2326 self.node_lease_read(op, now_ms, Err(Failure::Definite), effects)
2327 }
2328 Some(Phase::ReadingCapacity { .. }) => {
2329 self.capacity_peers_read(op, now_ms, Err(Failure::Definite), effects)
2330 }
2331 Some(Phase::Acquiring { .. }) | Some(Phase::ReconcilingAcquire { .. }) => {
2332 self.owner_cas_completed(op, Err(Failure::Ambiguous), effects)
2333 }
2334 // A restore has no aggregate deadline. Each object-store request
2335 // is bounded in the shell, and the complete task must retain its
2336 // op so a late success cannot be discarded and duplicated.
2337 Some(Phase::Restoring { .. }) => {}
2338 Some(Phase::Starting { .. }) => self.runtime_start_timed_out(op, effects),
2339 Some(Phase::Publishing { .. }) => self.published(op, Err(Failure::Ambiguous), effects),
2340 // An unprovable snapshot leaves the cell resident. Evicting on a
2341 // proof that never arrived is the one outcome that loses data.
2342 Some(Phase::EnsuringDurability { .. }) => {
2343 self.durability_checked(op, Err(Failure::Ambiguous), effects)
2344 }
2345 _ => {}
2346 }
2347 }
2348
2349 fn timer_fired(
2350 &mut self,
2351 timer: Timer,
2352 now_ms: u64,
2353 now_mono_ms: u64,
2354 effects: &mut Vec<Effect>,
2355 ) {
2356 let timer = match timer {
2357 Timer::CellAlarm { cell, generation } => {
2358 self.cell_alarm_timer(&cell, generation, now_ms, now_mono_ms, effects);
2359 return;
2360 }
2361 // An activation deadline is not conditional on node authority: a
2362 // request stalled behind a swallowed effect must be released
2363 // whatever the lease is doing.
2364 Timer::OperationDeadline { op } => {
2365 self.expire_operation(op, now_ms, effects);
2366 return;
2367 }
2368 // Also unconditional on node authority: a cell parked behind the
2369 // gate is waiting on this node's own capacity, not on its lease.
2370 Timer::QueuedActivation { cell, generation } => {
2371 self.expire_queued(&cell, generation, effects);
2372 self.pump_activations(effects);
2373 self.pump_capacity(effects);
2374 return;
2375 }
2376 timer => timer,
2377 };
2378 // A retry has no held lease to validate against, so it is resolved
2379 // before the authority lookup below discards it.
2380 if let NodeAuthority::Retrying { spec, generation } = &self.node_authority {
2381 if matches!(timer, Timer::NodeLeaseRenew { generation: fired } if fired == *generation)
2382 {
2383 let spec = spec.clone();
2384 self.begin_node_lease_acquisition(now_ms, spec, effects);
2385 }
2386 return;
2387 }
2388 let active = match &self.node_authority {
2389 NodeAuthority::Held(held) => Some(held.clone()),
2390 NodeAuthority::Reading { pending, .. } | NodeAuthority::Writing { pending, .. } => {
2391 pending.prior.clone()
2392 }
2393 _ => None,
2394 };
2395 let Some(held) = active else {
2396 return;
2397 };
2398 match timer {
2399 // `>=`, not `>`: a peer stops treating the record as live the
2400 // instant `now_ms` reaches `expires_ms`, so authority must end
2401 // there too. Serving through that one millisecond overlaps a
2402 // takeover that is already entitled to proceed.
2403 Timer::NodeLeaseFence { generation }
2404 if generation == held.timer_generation
2405 && now_mono_ms.saturating_sub(held.last_ok_mono_ms) >= held.spec.ttl_ms =>
2406 {
2407 self.fence_node(effects);
2408 }
2409 // A renew timer that arrives after the lease it belongs to has
2410 // already expired is not a renewal opportunity; authority is
2411 // already gone. Fence rather than issue a write that could
2412 // resurrect it behind a peer's in-flight takeover.
2413 Timer::NodeLeaseRenew { generation }
2414 if generation == held.timer_generation
2415 && now_mono_ms.saturating_sub(held.last_ok_mono_ms) >= held.spec.ttl_ms =>
2416 {
2417 self.fence_node(effects);
2418 }
2419 Timer::NodeLeaseRenew { generation }
2420 if generation == held.timer_generation
2421 && matches!(self.node_authority, NodeAuthority::Held(_)) =>
2422 {
2423 let NodeAuthority::Held(mut prior) =
2424 std::mem::replace(&mut self.node_authority, NodeAuthority::Failed)
2425 else {
2426 unreachable!("held checked above")
2427 };
2428 prior.last_attempt_mono_ms = now_mono_ms;
2429 let spec = prior.spec.clone();
2430 let desired = NodeLeaseRecord {
2431 node: self.node.clone(),
2432 addr: spec.addr.clone(),
2433 expires_ms: now_ms.saturating_add(spec.ttl_ms),
2434 peer_protocol: spec.peer_protocol,
2435 generation: spec.generation.clone(),
2436 // The write discipline the fold's safety rests on
2437 // (BrokenLeaseRenewalDropsLog is the spec tooth): a
2438 // renewal carries the folded log state through
2439 // unchanged.
2440 log_state: prior.record.log_state,
2441 etag: String::new(),
2442 };
2443 let guard = CasGuard::Match(prior.record.etag.clone());
2444 self.begin_node_lease_write(
2445 PendingNodeLease {
2446 spec,
2447 desired,
2448 prior: Some(prior),
2449 readback_only: false,
2450 anchor_mono_ms: now_mono_ms,
2451 resume_local: false,
2452 },
2453 guard,
2454 effects,
2455 );
2456 }
2457 Timer::CellAlarm { .. } => unreachable!("cell timers returned above"),
2458 _ => {}
2459 }
2460 }
2461
2462 fn schedule_alarm_timer(
2463 &self,
2464 cell: &str,
2465 generation: u64,
2466 at_ms: i64,
2467 now_ms: u64,
2468 now_mono_ms: u64,
2469 effects: &mut Vec<Effect>,
2470 ) {
2471 let at_ms = u64::try_from(at_ms).unwrap_or(0);
2472 effects.push(Effect::ScheduleTimer {
2473 timer: Timer::CellAlarm {
2474 cell: cell.to_string(),
2475 generation,
2476 },
2477 at_mono_ms: now_mono_ms.saturating_add(at_ms.saturating_sub(now_ms)),
2478 });
2479 }
2480
2481 fn alarm_observed(
2482 &mut self,
2483 id: &str,
2484 observed: AlarmObservation,
2485 now_ms: u64,
2486 now_mono_ms: u64,
2487 effects: &mut Vec<Effect>,
2488 ) {
2489 let AlarmObservation {
2490 at_ms,
2491 covered,
2492 firing_settled,
2493 } = observed;
2494 let Some(mut cell) = self.cells.remove(id) else {
2495 return;
2496 };
2497 if matches!(cell.phase, Phase::Fenced) {
2498 self.cells.insert(id.to_string(), cell);
2499 return;
2500 }
2501 // A failed output proof has already chosen the durable recovery
2502 // state and is stopping the unproven runtime. Its alarm cache can
2503 // still report the locally consumed row while the stop is in flight.
2504 // That observation belongs to the runtime being discarded, so it
2505 // cannot replace the re-armed alarm or delete its wake entry.
2506 if matches!(
2507 cell.phase,
2508 Phase::Cleaning {
2509 cause: StopCause::Reset,
2510 ..
2511 }
2512 ) {
2513 self.cells.insert(id.to_string(), cell);
2514 return;
2515 }
2516 if let Phase::EnsuringDurability { op, epoch } = cell.phase {
2517 self.cell_ops.remove(&op);
2518 set_phase(&mut self.occupied, &mut cell, Phase::Resident { epoch });
2519 }
2520 // Runtime observations can arrive before `AlarmFinished`. The alarm
2521 // handler removes its row before its consuming write is durable, so a
2522 // direct `None` must not replace `Firing` and delete the wake entry.
2523 // Stage a real move for the completion path. The completion carries
2524 // the durability verdict that decides whether the observation is safe
2525 // to apply. An unchanged report only refreshes wake coverage unless
2526 // it supersedes an earlier staged move.
2527 if !firing_settled {
2528 if let Some(AlarmState::Firing {
2529 at_ms: firing_at_ms,
2530 covered: firing_covered,
2531 observed,
2532 ..
2533 }) = &mut cell.alarm
2534 {
2535 if at_ms == Some(*firing_at_ms) && observed.is_none() {
2536 *firing_covered = covered;
2537 } else {
2538 *observed = Some((at_ms, covered));
2539 }
2540 self.cells.insert(id.to_string(), cell);
2541 return;
2542 }
2543 }
2544 let observed_before = match cell.alarm {
2545 Some(AlarmState::Armed { at_ms, .. }) | Some(AlarmState::Firing { at_ms, .. }) => at_ms,
2546 None => -1,
2547 };
2548 // The assignment below replaces a firing alarm unconditionally. Its
2549 // op entry is usually consumed already (`alarm_finished` routes
2550 // through here), but a direct observation can land mid-fire, and the
2551 // replaced op will then never match a lookup again.
2552 if let Some(AlarmState::Firing { op, .. }) = cell.alarm {
2553 self.cell_ops.remove(&op);
2554 }
2555 cell.alarm = at_ms.filter(|at_ms| *at_ms >= 0).map(|at_ms| {
2556 let generation = self.next_timer_generation;
2557 self.next_timer_generation = self
2558 .next_timer_generation
2559 .checked_add(1)
2560 .expect("timer generation exhausted");
2561 self.schedule_alarm_timer(id, generation, at_ms, now_ms, now_mono_ms, effects);
2562 AlarmState::Armed {
2563 at_ms,
2564 generation,
2565 covered,
2566 }
2567 });
2568 if cell.alarm.is_none() {
2569 cell.alarm_wake = false;
2570 }
2571 // Both ways an alarm settles arrive here -- a request that changed it
2572 // and a firing that consumed it (`alarm_finished` routes through this
2573 // function). Saying so once, here, is what keeps the bucket entry
2574 // from depending on the shell noticing each path separately. Only on
2575 // a change: an activity that left the alarm alone has nothing to
2576 // mirror, and re-stating it would put a bucket round trip on the end
2577 // of every request.
2578 let settled = at_ms.filter(|at_ms| *at_ms >= 0).unwrap_or(-1);
2579 if settled != observed_before {
2580 effects.push(Effect::ReconcileWakeEntry {
2581 cell: id.to_string(),
2582 next_alarm_ms: settled,
2583 });
2584 }
2585 self.cells.insert(id.to_string(), cell);
2586 }
2587
2588 fn cell_alarm_timer(
2589 &mut self,
2590 id: &str,
2591 generation: u64,
2592 now_ms: u64,
2593 now_mono_ms: u64,
2594 effects: &mut Vec<Effect>,
2595 ) {
2596 if !self.node_authoritative() {
2597 return;
2598 }
2599 let Some(mut cell) = self.cells.remove(id) else {
2600 return;
2601 };
2602 let Some(AlarmState::Armed {
2603 at_ms,
2604 generation: current,
2605 covered,
2606 }) = cell.alarm
2607 else {
2608 self.cells.insert(id.to_string(), cell);
2609 return;
2610 };
2611 if current != generation {
2612 self.cells.insert(id.to_string(), cell);
2613 return;
2614 }
2615 if i64::try_from(now_ms).unwrap_or(i64::MAX) < at_ms {
2616 self.schedule_alarm_timer(id, generation, at_ms, now_ms, now_mono_ms, effects);
2617 self.cells.insert(id.to_string(), cell);
2618 return;
2619 }
2620 let epoch = match cell.phase {
2621 Phase::Resident { epoch } => epoch,
2622 Phase::EnsuringDurability { op, epoch } => {
2623 self.cell_ops.remove(&op);
2624 set_phase(&mut self.occupied, &mut cell, Phase::Resident { epoch });
2625 epoch
2626 }
2627 Phase::Fenced => {
2628 cell.alarm = None;
2629 self.cells.insert(id.to_string(), cell);
2630 return;
2631 }
2632 Phase::Dormant { .. } => {
2633 cell.alarm_wake = true;
2634 // Every activation takes a fresh epoch. The LTX metadata does
2635 // not survive an eviction, so a same-epoch wake would restart
2636 // at TXID 1 inside a populated prefix and mix two writer
2637 // lineages (CelldWriterGeneration.tla, #158). The CAS also
2638 // settles the older resume-vs-release race deterministically.
2639 self.admit_or_queue_activation(id, &mut cell, ColdStart::ReadOwner, effects);
2640 effects.push(Effect::ScheduleTimer {
2641 timer: Timer::CellAlarm {
2642 cell: id.to_string(),
2643 generation,
2644 },
2645 at_mono_ms: now_mono_ms.saturating_add(100),
2646 });
2647 self.cells.insert(id.to_string(), cell);
2648 return;
2649 }
2650 Phase::Inactive => {
2651 cell.alarm_wake = true;
2652 self.admit_or_queue_activation(id, &mut cell, ColdStart::ReadOwner, effects);
2653 effects.push(Effect::ScheduleTimer {
2654 timer: Timer::CellAlarm {
2655 cell: id.to_string(),
2656 generation,
2657 },
2658 at_mono_ms: now_mono_ms.saturating_add(100),
2659 });
2660 self.cells.insert(id.to_string(), cell);
2661 return;
2662 }
2663 _ => {
2664 effects.push(Effect::ScheduleTimer {
2665 timer: Timer::CellAlarm {
2666 cell: id.to_string(),
2667 generation,
2668 },
2669 at_mono_ms: now_mono_ms.saturating_add(100),
2670 });
2671 self.cells.insert(id.to_string(), cell);
2672 return;
2673 }
2674 };
2675 let op = self.cell_op(id);
2676 cell.alarm = Some(AlarmState::Firing {
2677 op,
2678 at_ms,
2679 generation,
2680 covered,
2681 observed: None,
2682 });
2683 cell.alarm_wake = false;
2684 self.cells.insert(id.to_string(), cell);
2685 effects.push(Effect::FireAlarm {
2686 op,
2687 cell: id.to_string(),
2688 epoch,
2689 scheduled_ms: at_ms,
2690 });
2691 }
2692
2693 /// Settle a firing alarm, once the commit that consumed it is durable.
2694 ///
2695 /// The consuming commit is a write like any other, so it takes the same
2696 /// output gate a request's write takes. Holding the alarm behind that gate
2697 /// is what lets the core order the wake-entry delete safely: the delete
2698 /// leaves only from the far side of a proven `DurableReached`, and every
2699 /// response that can reveal the same commit trails the same gate through
2700 /// `read_output`. The gate is keyed by the cell and epoch the firing was
2701 /// dispatched against, because an activity fold can supersede the firing
2702 /// state while the write is still unproven.
2703 ///
2704 /// The gate calls back here with `position: None` once it settles, so the
2705 /// second pass runs the ordinary settlement below and cannot re-gate.
2706 ///
2707 /// `(fired, epoch)` is where the firing was dispatched, carried as a pair
2708 /// because neither half means anything without the other.
2709 fn alarm_finished(
2710 &mut self,
2711 op: OpId,
2712 (fired, epoch): (CellId, Epoch),
2713 now_ms: u64,
2714 now_mono_ms: u64,
2715 result: Result<(Option<i64>, bool, Option<u64>), Failure>,
2716 effects: &mut Vec<Effect>,
2717 ) {
2718 if let Ok((at_ms, covered, Some(position))) = result {
2719 if matches!(
2720 self.cells.get(&fired).map(|cell| &cell.phase),
2721 Some(Phase::Resident { epoch: current }) if *current == epoch
2722 ) {
2723 let gate = self.op();
2724 self.barriers.insert(
2725 gate,
2726 Barrier {
2727 owner: GateOwner::Alarm {
2728 alarm: op,
2729 at_ms,
2730 covered,
2731 },
2732 cell: fired.clone(),
2733 epoch,
2734 position,
2735 followers: Vec::new(),
2736 },
2737 );
2738 effects.push(Effect::AwaitDurable {
2739 op: gate,
2740 cell: fired,
2741 epoch,
2742 position,
2743 });
2744 return;
2745 }
2746 // The cell no longer runs the epoch this write belongs to, so the
2747 // reset or fence that took it has already refused to acknowledge
2748 // the write. Settle the alarm below; a superseded op falls out of
2749 // `take_cell_op`.
2750 }
2751 let result = result.map(|(at_ms, covered, _)| (at_ms, covered));
2752 let Some(id) = self.take_cell_op(op, |cell| {
2753 matches!(cell.alarm, Some(AlarmState::Firing { op: current, .. }) if current == op)
2754 }) else {
2755 return;
2756 };
2757 let Some(mut cell) = self.cells.remove(&id) else {
2758 return;
2759 };
2760 let Some(AlarmState::Firing {
2761 at_ms,
2762 generation,
2763 covered,
2764 observed,
2765 ..
2766 }) = cell.alarm
2767 else {
2768 self.cells.insert(id, cell);
2769 return;
2770 };
2771 match result {
2772 Ok((at_ms, covered)) => {
2773 // Leave the fired alarm in place for `alarm_observed` to
2774 // replace: it assigns unconditionally, and it compares against
2775 // what was there to decide whether the bucket entry has to
2776 // follow. Clearing it here first makes a consumed alarm look
2777 // like it was never armed, and the entry is never deleted.
2778 self.cells.insert(id.clone(), cell);
2779 let (at_ms, covered) = observed.unwrap_or((at_ms, covered));
2780 self.alarm_observed(
2781 &id,
2782 AlarmObservation {
2783 at_ms,
2784 covered,
2785 firing_settled: true,
2786 },
2787 now_ms,
2788 now_mono_ms,
2789 effects,
2790 );
2791 }
2792 Err(_) => {
2793 cell.alarm = Some(AlarmState::Armed {
2794 at_ms,
2795 generation,
2796 covered,
2797 });
2798 self.cells.insert(id.clone(), cell);
2799 effects.push(Effect::ScheduleTimer {
2800 timer: Timer::CellAlarm {
2801 cell: id,
2802 generation,
2803 },
2804 at_mono_ms: now_mono_ms.saturating_add(500),
2805 });
2806 }
2807 }
2808 }
2809
2810 fn fence_node(&mut self, effects: &mut Vec<Effect>) {
2811 self.node_authority = NodeAuthority::Fenced;
2812 self.fence(effects);
2813 effects.push(Effect::Halt {
2814 code: 3,
2815 reason: HaltReason::NodeLeaseExpired,
2816 });
2817 }
2818
2819 fn request(
2820 &mut self,
2821 request: RequestId,
2822 id: CellId,
2823 capacity_handoff: bool,
2824 ownership_handoff: bool,
2825 effects: &mut Vec<Effect>,
2826 ) {
2827 if self.request_cells.contains_key(&request) {
2828 return;
2829 }
2830 if self.fenced {
2831 effects.push(Effect::Complete {
2832 request,
2833 result: Err(RequestError::NodeFenced),
2834 });
2835 return;
2836 }
2837 if capacity_handoff {
2838 self.capacity_requests.insert(request);
2839 }
2840 if ownership_handoff {
2841 self.handoff_requests.insert(request);
2842 }
2843 if self.node_authoritative() {
2844 self.request_authorized(request, id, effects);
2845 return;
2846 }
2847 effects.push(Effect::Complete {
2848 request,
2849 result: Err(RequestError::NodeUnavailable),
2850 });
2851 }
2852
2853 /// Route one event from an already-registered WebSocket. A regular or
2854 /// outbound socket keeps its resident runtime alive, so a shutdown drain
2855 /// must let that socket finish its message and close handlers locally.
2856 /// Ordinary requests still wait for the successor once the cell quiesces.
2857 fn websocket_request(
2858 &mut self,
2859 request: RequestId,
2860 id: CellId,
2861 websocket: WebSocketId,
2862 effects: &mut Vec<Effect>,
2863 ) {
2864 let held_resident = self.node_authoritative()
2865 && self.cells.get(&id).is_some_and(|cell| {
2866 matches!(cell.phase, Phase::Resident { .. })
2867 && cell.websockets.contains_key(&websocket)
2868 });
2869 if held_resident {
2870 self.complete_request(&id, request, Ok(Route::Local), effects);
2871 } else {
2872 // A hibernatable socket can outlive residency. It follows the
2873 // ordinary route so it can reactivate here or reach a successor.
2874 self.request(request, id, false, false, effects);
2875 }
2876 }
2877
2878 fn request_authorized(&mut self, request: RequestId, id: CellId, effects: &mut Vec<Effect>) {
2879 let mut cell = self.cells.remove(&id).unwrap_or_default();
2880 match &cell.phase {
2881 Phase::Resident { .. } if !cell.quiescing => {
2882 self.complete_request(&id, request, Ok(Route::Local), effects)
2883 }
2884 Phase::EnsuringDurability { op, epoch } if !self.draining => {
2885 // The runtime is still published, so a new request wins the
2886 // race with voluntary eviction. Retiring the operation makes
2887 // its eventual durability completion harmless. The permit
2888 // taken at nomination comes back with the rescue: leaked, it
2889 // counts against `max_evictions` forever and eventually
2890 // stands every future eviction down.
2891 let epoch = *epoch;
2892 self.cell_ops.remove(op);
2893 set_phase(&mut self.occupied, &mut cell, Phase::Resident { epoch });
2894 self.eviction_permits.remove(&id);
2895 self.complete_request(&id, request, Ok(Route::Local), effects);
2896 }
2897 Phase::Remote {
2898 node,
2899 addr,
2900 epoch,
2901 peer_protocol,
2902 ..
2903 } => effects.push(Effect::Complete {
2904 request,
2905 result: Ok(Route::Remote {
2906 node: node.clone(),
2907 addr: addr.clone(),
2908 epoch: *epoch,
2909 peer_protocol: *peer_protocol,
2910 }),
2911 }),
2912 Phase::Fenced => effects.push(Effect::Complete {
2913 request,
2914 result: Err(RequestError::NodeFenced),
2915 }),
2916 Phase::Starting { op, .. } if self.timed_out_runtime_starts.contains(op) => effects
2917 .push(Effect::Complete {
2918 request,
2919 result: Err(RequestError::RuntimeFailed),
2920 }),
2921 Phase::Inactive if self.draining => effects.push(Effect::Complete {
2922 request,
2923 result: Err(RequestError::NodeUnavailable),
2924 }),
2925 Phase::Dormant { .. } if self.handoff_requests.contains(&request) => {
2926 // The ownership-only handoff is complete already. Keep the
2927 // synthetic request pending just long enough for the executor
2928 // to observe `accepted_epoch`; its cancellation removes it.
2929 cell.requests.insert(request);
2930 self.request_cells.insert(request, id.clone());
2931 }
2932 phase => {
2933 cell.requests.insert(request);
2934 self.request_cells.insert(request, id.clone());
2935 match phase {
2936 Phase::Inactive => {
2937 self.admit_or_queue_activation(
2938 &id,
2939 &mut cell,
2940 ColdStart::ReadOwner,
2941 effects,
2942 );
2943 }
2944 Phase::Dormant { .. } if !self.draining => {
2945 // A wake always claims a fresh epoch. The preserved
2946 // snapshot remains reusable as the previous epoch's
2947 // baseline after the claim succeeds.
2948 self.admit_or_queue_activation(
2949 &id,
2950 &mut cell,
2951 ColdStart::ReadOwner,
2952 effects,
2953 );
2954 }
2955 _ => {}
2956 }
2957 }
2958 }
2959 self.cells.insert(id, cell);
2960 }
2961
2962 fn wake_hint(&mut self, id: CellId, effects: &mut Vec<Effect>) {
2963 if self.fenced {
2964 return;
2965 }
2966 if self.node_authoritative() {
2967 self.wake_hint_authorized(id, effects);
2968 }
2969 }
2970
2971 fn wake_hint_authorized(&mut self, id: CellId, effects: &mut Vec<Effect>) {
2972 if self.draining {
2973 return;
2974 }
2975 let mut cell = self.cells.remove(&id).unwrap_or_default();
2976 cell.alarm_wake = true;
2977 match cell.phase {
2978 Phase::Inactive | Phase::Remote { .. } => {
2979 self.admit_or_queue_activation(&id, &mut cell, ColdStart::ReadOwner, effects);
2980 }
2981 Phase::Dormant { .. } => {
2982 self.admit_or_queue_activation(&id, &mut cell, ColdStart::ReadOwner, effects)
2983 }
2984 _ => {}
2985 }
2986 self.cells.insert(id, cell);
2987 }
2988
2989 fn cancel(&mut self, request: RequestId, effects: &mut Vec<Effect>) {
2990 // A cancelled route can already be Local-complete: the reply raced
2991 // the caller's death and was never consumed, so no activity guard
2992 // exists and no `ActivityFinished` will ever arrive. Release the
2993 // activity here, or the leaked entry pins its cell forever and a
2994 // later quiesce can never reach eviction. Every consumed route
2995 // disarms its cancel guard before this event can be sent, and a
2996 // guard that did report finished has already left `active_requests`,
2997 // so this release cannot double-fire.
2998 if self.active_requests.contains_key(&request) {
2999 self.activity_finished(request, effects);
3000 }
3001 self.capacity_requests.remove(&request);
3002 self.handoff_requests.remove(&request);
3003 let Some(id) = self.request_cells.remove(&request) else {
3004 return;
3005 };
3006 let Some(cell) = self.cells.get_mut(&id) else {
3007 return;
3008 };
3009 cell.requests.remove(&request);
3010 if cell.requests.is_empty() && !cell.alarm_wake && cell.phase == Phase::WaitingActivation {
3011 let start = cell.waiting_activation.take();
3012 set_phase(
3013 &mut self.occupied,
3014 cell,
3015 match start {
3016 Some(ColdStart::Restore(spec)) => Phase::Dormant { epoch: spec.epoch },
3017 _ => Phase::Inactive,
3018 },
3019 );
3020 self.activation_waiters.retain(|queued| queued != &id);
3021 } else if cell.requests.is_empty()
3022 && !cell.alarm_wake
3023 && cell.phase == Phase::WaitingCapacity
3024 {
3025 let activation = cell.waiting_for.take();
3026 set_phase(
3027 &mut self.occupied,
3028 cell,
3029 match activation {
3030 Some(Activation::Restore(spec)) => Phase::Dormant { epoch: spec.epoch },
3031 _ => Phase::Inactive,
3032 },
3033 );
3034 self.capacity_waiters.retain(|queued| queued != &id);
3035 }
3036 }
3037
3038 /// Retire cold work that cannot contribute to a clean local reload.
3039 ///
3040 /// Published runtimes remain untouched. The shell drains their active
3041 /// turns before it snapshots the resident inventory. A restore has no
3042 /// runtime to preserve, and it can legitimately outlive every caller, so
3043 /// waiting for it would make one cold cell disable local reuse for the
3044 /// complete node. Retire those phases and fail their callers. A later
3045 /// completion is ignored because its operation is no longer current.
3046 fn begin_preserve(&mut self, effects: &mut Vec<Effect>) {
3047 self.activation_waiters.clear();
3048 self.capacity_waiters.clear();
3049
3050 let ids: Vec<CellId> = self.cells.keys().cloned().collect();
3051 for id in ids {
3052 let mut cell = self.cells.remove(&id).expect("id came from map");
3053 let fallback = match &cell.phase {
3054 Phase::WaitingActivation => match cell.waiting_activation.as_ref() {
3055 Some(ColdStart::Restore(spec)) => Some(Phase::Dormant { epoch: spec.epoch }),
3056 _ => Some(Phase::Inactive),
3057 },
3058 Phase::ReadingOwner { .. }
3059 | Phase::ReadingNodeLease { .. }
3060 | Phase::ReadingCapacity { .. }
3061 | Phase::Acquiring { .. }
3062 | Phase::ReconcilingAcquire { .. } => Some(Phase::Inactive),
3063 Phase::WaitingCapacity => match cell.waiting_for.as_ref() {
3064 Some(Activation::Restore(spec)) => Some(Phase::Dormant { epoch: spec.epoch }),
3065 _ => Some(Phase::Inactive),
3066 },
3067 Phase::Restoring { spec, .. } => Some(Phase::Dormant { epoch: spec.epoch }),
3068 _ => None,
3069 };
3070 if let Some(fallback) = fallback {
3071 if let Some(stale) = phase_op(&cell.phase) {
3072 self.cell_ops.remove(&stale);
3073 }
3074 self.finish_requests(&id, &mut cell, Err(RequestError::NodeFenced), effects);
3075 set_phase(&mut self.occupied, &mut cell, fallback);
3076 cell.waiting_for = None;
3077 cell.waiting_activation = None;
3078 cell.alarm_wake = false;
3079 cell.resume_demand = false;
3080 self.resuming_cells.remove(&id);
3081 }
3082 self.cells.insert(id, cell);
3083 }
3084 if self.resuming_cells.is_empty() {
3085 self.resuming = false;
3086 }
3087 self.activation_permits.retain(|id| {
3088 self.cells
3089 .get(id)
3090 .is_some_and(|cell| phase_holds_activation(&cell.phase))
3091 });
3092 self.capacity_requests
3093 .retain(|request| self.request_cells.contains_key(request));
3094 self.handoff_requests
3095 .retain(|request| self.request_cells.contains_key(request));
3096 }
3097
3098 fn begin_capacity_lookup(
3099 &mut self,
3100 id: &str,
3101 cell: &mut Cell,
3102 claim: Claim,
3103 effects: &mut Vec<Effect>,
3104 ) {
3105 let op = self.cell_op(id);
3106 set_phase(
3107 &mut self.occupied,
3108 cell,
3109 Phase::ReadingCapacity {
3110 op,
3111 claim: claim.clone(),
3112 },
3113 );
3114 effects.push(Effect::ReadCapacityPeers {
3115 op,
3116 cell: id.to_string(),
3117 });
3118 }
3119
3120 /// Place a genuinely unowned cell. Ordinary ingress may look for fleet
3121 /// capacity before waiting locally; a capacity handoff must either reserve
3122 /// a real local slot now or explicitly refuse so its caller can traverse.
3123 fn place_unowned(
3124 &mut self,
3125 id: &str,
3126 cell: &mut Cell,
3127 claim: Claim,
3128 effects: &mut Vec<Effect>,
3129 ) {
3130 if self.has_capacity() {
3131 self.activate_or_wait(id, cell, Activation::Claim(claim), effects);
3132 return;
3133 }
3134
3135 let handoffs: Vec<RequestId> = cell
3136 .requests
3137 .iter()
3138 .copied()
3139 .filter(|request| self.capacity_requests.contains(request))
3140 .collect();
3141 for request in handoffs {
3142 cell.requests.remove(&request);
3143 self.request_cells.remove(&request);
3144 self.complete_request(id, request, Err(RequestError::CapacityExhausted), effects);
3145 }
3146
3147 if cell.requests.is_empty() || !self.config.require_node_lease {
3148 // Alarm wakes cannot be proxied as an HTTP capacity handoff. They
3149 // retain the old local wait semantics until alarm dispatch itself
3150 // has a fleet transport effect. Lease-disabled mode likewise has
3151 // no authoritative fleet membership to enumerate.
3152 self.activate_or_wait(id, cell, Activation::Claim(claim), effects);
3153 } else {
3154 self.begin_capacity_lookup(id, cell, claim, effects);
3155 }
3156 }
3157
3158 fn owner_read(
3159 &mut self,
3160 op: OpId,
3161 now_ms: u64,
3162 result: Result<Option<OwnerRecord>, Failure>,
3163 effects: &mut Vec<Effect>,
3164 ) {
3165 let Some(id) = self.take_cell_op(op, |cell| {
3166 matches!(
3167 cell.phase,
3168 Phase::ReadingOwner { op: current }
3169 | Phase::ReconcilingAcquire { op: current, .. }
3170 if current == op
3171 )
3172 }) else {
3173 return;
3174 };
3175 let mut cell = self.cells.remove(&id).expect("cell found above");
3176 let reconciling_claim = match &cell.phase {
3177 Phase::ReconcilingAcquire { claim, .. } => Some(claim.clone()),
3178 _ => None,
3179 };
3180 // A reconcile re-reads and then acquires again: one attempt
3181 // continuing, not a new one. The count has to survive the round trip
3182 // or the bound below can never be reached.
3183 let reconciles = reconciling_claim
3184 .as_ref()
3185 .map_or(0, |claim| claim.reconciles);
3186 match result {
3187 Ok(Some(record))
3188 if reconciling_claim.as_ref().is_some_and(|claim| {
3189 record.node.as_deref() == Some(self.node.as_str())
3190 && record.epoch == claim.epoch
3191 }) =>
3192 {
3193 let spec = RestoreSpec {
3194 epoch: record.epoch,
3195 fresh: matches!(
3196 reconciling_claim.as_ref().map(|claim| &claim.guard),
3197 Some(CasGuard::Absent)
3198 ),
3199 took_over: reconciling_claim
3200 .as_ref()
3201 .is_some_and(|claim| claim.takeover),
3202 resume_local: false,
3203 // The ambiguous acquire applied after all, so the prior
3204 // owner it displaced is the one the claim carried — the
3205 // takeover interlock must see it exactly as if the CAS
3206 // response had confirmed directly.
3207 prior: reconciling_claim
3208 .as_ref()
3209 .and_then(|claim| claim.prior.clone()),
3210 };
3211 self.record_acquisition(&spec);
3212 let ownership_only = !cell.requests.is_empty()
3213 && cell
3214 .requests
3215 .iter()
3216 .all(|request| self.handoff_requests.contains(request));
3217 if ownership_only {
3218 set_phase(
3219 &mut self.occupied,
3220 &mut cell,
3221 Phase::Dormant { epoch: spec.epoch },
3222 );
3223 } else {
3224 self.activate_or_wait(&id, &mut cell, Activation::Restore(spec), effects);
3225 }
3226 }
3227 Ok(Some(record)) if record.node.as_deref() == Some(self.node.as_str()) => {
3228 let epoch = record.epoch.saturating_add(1);
3229 let prior = record.node.clone();
3230 self.activate_or_wait(
3231 &id,
3232 &mut cell,
3233 Activation::Claim(Claim {
3234 guard: CasGuard::Match(record.etag),
3235 epoch,
3236 takeover: false,
3237 prior,
3238 reconciles,
3239 }),
3240 effects,
3241 );
3242 }
3243 Ok(Some(record)) if record.node.is_none() => {
3244 let epoch = record.epoch.saturating_add(1);
3245 self.place_unowned(
3246 &id,
3247 &mut cell,
3248 Claim {
3249 guard: CasGuard::Match(record.etag),
3250 epoch,
3251 takeover: true,
3252 prior: None,
3253 reconciles,
3254 },
3255 effects,
3256 );
3257 }
3258 Ok(Some(record)) => {
3259 let owner = record.node.clone().expect("foreign owner checked above");
3260 let cached = self
3261 .node_lease_cache
3262 .get(&owner)
3263 .filter(|lease| lease.expires_ms > now_ms && !lease.addr.is_empty())
3264 .cloned();
3265 if let Some(lease) = cached {
3266 self.apply_node_lease_result(
3267 &id,
3268 &mut cell,
3269 record,
3270 now_ms,
3271 Ok(Some(lease)),
3272 effects,
3273 );
3274 } else {
3275 self.node_lease_cache.remove(&owner);
3276 let next = self.cell_op(&id);
3277 set_phase(
3278 &mut self.occupied,
3279 &mut cell,
3280 Phase::ReadingNodeLease {
3281 op: next,
3282 owner: record,
3283 },
3284 );
3285 effects.push(Effect::ReadNodeLease {
3286 op: next,
3287 cell: id.clone(),
3288 owner,
3289 });
3290 }
3291 }
3292 Ok(None) => {
3293 self.place_unowned(
3294 &id,
3295 &mut cell,
3296 Claim {
3297 guard: CasGuard::Absent,
3298 epoch: 1,
3299 takeover: false,
3300 prior: None,
3301 reconciles,
3302 },
3303 effects,
3304 );
3305 }
3306 Err(_) => {
3307 set_phase(&mut self.occupied, &mut cell, Phase::Inactive);
3308 self.finish_requests(&id, &mut cell, Err(RequestError::ResolveFailed), effects);
3309 }
3310 }
3311 self.cells.insert(id, cell);
3312 if reconciling_claim.is_some() {
3313 self.pump_capacity(effects);
3314 }
3315 }
3316
3317 fn node_lease_read(
3318 &mut self,
3319 op: OpId,
3320 now_ms: u64,
3321 result: Result<Option<NodeLeaseRecord>, Failure>,
3322 effects: &mut Vec<Effect>,
3323 ) {
3324 let Some(id) = self.take_cell_op(op, |cell| {
3325 matches!(cell.phase, Phase::ReadingNodeLease { op: current, .. } if current == op)
3326 }) else {
3327 return;
3328 };
3329 let mut cell = self.cells.remove(&id).expect("cell found above");
3330 let Phase::ReadingNodeLease { owner: record, .. } = &cell.phase else {
3331 unreachable!()
3332 };
3333 let record = record.clone();
3334 if let Ok(Some(lease)) = &result {
3335 if record.node.as_deref() == Some(lease.node.as_str())
3336 && lease.expires_ms > now_ms
3337 && !lease.addr.is_empty()
3338 {
3339 self.node_lease_cache
3340 .insert(lease.node.clone(), lease.clone());
3341 }
3342 }
3343 self.apply_node_lease_result(&id, &mut cell, record, now_ms, result, effects);
3344 self.cells.insert(id, cell);
3345 }
3346
3347 fn capacity_peers_read(
3348 &mut self,
3349 op: OpId,
3350 now_ms: u64,
3351 result: Result<Vec<CapacityPeer>, Failure>,
3352 effects: &mut Vec<Effect>,
3353 ) {
3354 let Some(id) = self.take_cell_op(op, |cell| {
3355 matches!(cell.phase, Phase::ReadingCapacity { op: current, .. } if current == op)
3356 }) else {
3357 return;
3358 };
3359 let mut cell = self.cells.remove(&id).expect("cell found above");
3360 let Phase::ReadingCapacity { claim, .. } = &cell.phase else {
3361 unreachable!()
3362 };
3363 let claim = claim.clone();
3364 let peers = match result {
3365 Ok(peers) => peers,
3366 Err(_) => {
3367 self.activate_or_wait(&id, &mut cell, Activation::Claim(claim), effects);
3368 self.cells.insert(id, cell);
3369 return;
3370 }
3371 };
3372
3373 // A newer load sample supersedes both reservations made against and
3374 // refusals of the prior sample. Equal samples deliberately retain
3375 // both, which is what makes concurrent read completions compose.
3376 for peer in &peers {
3377 let prior = self.capacity_samples.get(&peer.node).copied().unwrap_or(0);
3378 if peer.sampled_ms > prior {
3379 self.capacity_samples
3380 .insert(peer.node.clone(), peer.sampled_ms);
3381 self.capacity_reservations.remove(&peer.node);
3382 self.capacity_rejections.remove(&peer.node);
3383 }
3384 }
3385
3386 let selected = peers
3387 .into_iter()
3388 .filter(|peer| {
3389 peer.node != self.node
3390 && peer.expires_ms > now_ms
3391 && !peer.addr.is_empty()
3392 && peer.peer_protocol == self.config.peer_protocol
3393 && peer.sampled_ms != 0
3394 && !peer.pressured
3395 && self
3396 .capacity_rejections
3397 .get(&peer.node)
3398 .is_none_or(|sample| peer.sampled_ms > *sample)
3399 })
3400 .map(|peer| {
3401 let projected = peer.resident_cells.saturating_add(
3402 self.capacity_reservations
3403 .get(&peer.node)
3404 .copied()
3405 .unwrap_or(0),
3406 );
3407 (peer, projected)
3408 })
3409 .min_by_key(|(peer, projected)| {
3410 // The third key is the memory the peer holds, which is what
3411 // the peer decides its own pressure on. A peer from before that
3412 // field existed reports nothing, and its resident set size is
3413 // the only number available -- which reads as more loaded than
3414 // it is, and is the conservative direction for a tiebreak.
3415 (
3416 *projected,
3417 peer.host_websockets,
3418 peer.in_use_bytes.unwrap_or(peer.rss_bytes),
3419 peer.node.clone(),
3420 )
3421 });
3422
3423 if let Some((peer, _)) = selected {
3424 *self
3425 .capacity_reservations
3426 .entry(peer.node.clone())
3427 .or_default() += 1;
3428 set_phase(
3429 &mut self.occupied,
3430 &mut cell,
3431 Phase::Remote {
3432 node: peer.node.clone(),
3433 addr: peer.addr.clone(),
3434 epoch: 0,
3435 peer_protocol: peer.peer_protocol,
3436 capacity_sampled_ms: Some(peer.sampled_ms),
3437 },
3438 );
3439 self.finish_requests(
3440 &id,
3441 &mut cell,
3442 Ok(Route::Remote {
3443 node: peer.node,
3444 addr: peer.addr,
3445 epoch: 0,
3446 peer_protocol: peer.peer_protocol,
3447 }),
3448 effects,
3449 );
3450 } else {
3451 self.activate_or_wait(&id, &mut cell, Activation::Claim(claim), effects);
3452 }
3453 self.cells.insert(id, cell);
3454 }
3455
3456 fn apply_node_lease_result(
3457 &mut self,
3458 id: &str,
3459 cell: &mut Cell,
3460 record: OwnerRecord,
3461 now_ms: u64,
3462 result: Result<Option<NodeLeaseRecord>, Failure>,
3463 effects: &mut Vec<Effect>,
3464 ) {
3465 match result {
3466 Ok(Some(lease))
3467 if lease.expires_ms > now_ms
3468 && !lease.addr.is_empty()
3469 && record.node.as_deref() == Some(lease.node.as_str())
3470 && lease.peer_protocol != self.config.peer_protocol =>
3471 {
3472 set_phase(&mut self.occupied, cell, Phase::Inactive);
3473 self.finish_requests(id, cell, Err(RequestError::PeerIncompatible), effects);
3474 }
3475 Ok(Some(lease))
3476 if lease.expires_ms > now_ms
3477 && !lease.addr.is_empty()
3478 && record.node.as_deref() == Some(lease.node.as_str())
3479 && lease.peer_protocol == self.config.peer_protocol =>
3480 {
3481 let node = lease.node;
3482 let addr = lease.addr;
3483 let epoch = record.epoch;
3484 set_phase(
3485 &mut self.occupied,
3486 cell,
3487 Phase::Remote {
3488 node: node.clone(),
3489 addr: addr.clone(),
3490 epoch,
3491 peer_protocol: lease.peer_protocol,
3492 capacity_sampled_ms: None,
3493 },
3494 );
3495 self.finish_requests(
3496 id,
3497 cell,
3498 Ok(Route::Remote {
3499 node,
3500 addr,
3501 epoch,
3502 peer_protocol: lease.peer_protocol,
3503 }),
3504 effects,
3505 );
3506 }
3507 Ok(lease) => {
3508 // The takeover interlock, decided HERE on the lease the
3509 // core just read (lease-fold): a dead owner whose folded
3510 // log state is not sealed may hold acked writes only on
3511 // its followers, and claiming before recovery fixes a
3512 // bucket state that excludes them. Absence of a lease —
3513 // or a lease that never opened a log — keeps its meaning
3514 // as a proof: nothing was acked past the bucket.
3515 let unrecovered = lease.as_ref().is_some_and(|lease| {
3516 !matches!(
3517 lease.log_state,
3518 None | Some(crate::log_tier::LogState::Sealed)
3519 )
3520 });
3521 if unrecovered {
3522 let owner = record.node.clone().unwrap_or_default();
3523 let next = self.cell_op(id);
3524 set_phase(
3525 &mut self.occupied,
3526 cell,
3527 Phase::RecoveringOwnerLog {
3528 op: next,
3529 owner: record,
3530 },
3531 );
3532 effects.push(Effect::RecoverNodeLog {
3533 op: next,
3534 cell: id.to_string(),
3535 owner,
3536 });
3537 return;
3538 }
3539 let epoch = record.epoch.saturating_add(1);
3540 let prior = record.node.clone();
3541 self.activate_or_wait(
3542 id,
3543 cell,
3544 Activation::Claim(Claim {
3545 guard: CasGuard::Match(record.etag),
3546 epoch,
3547 takeover: true,
3548 prior,
3549 reconciles: 0,
3550 }),
3551 effects,
3552 );
3553 }
3554 Err(_) => {
3555 set_phase(&mut self.occupied, cell, Phase::Inactive);
3556 self.finish_requests(id, cell, Err(RequestError::ResolveFailed), effects);
3557 }
3558 }
3559 }
3560
3561 /// The interlock's completion: recovery sealed (or proved absent)
3562 /// every session of the dead owner, so the claim the gate deferred
3563 /// proceeds against the SAME owner record the decision was made on —
3564 /// the CAS guard still carries its etag, so a record that moved in
3565 /// the meantime rejects the claim and resolution restarts.
3566 fn node_log_recovered(
3567 &mut self,
3568 op: OpId,
3569 result: Result<(), Failure>,
3570 effects: &mut Vec<Effect>,
3571 ) {
3572 let Some(id) = self.take_cell_op(
3573 op,
3574 |cell| matches!(cell.phase, Phase::RecoveringOwnerLog { op: p, .. } if p == op),
3575 ) else {
3576 return;
3577 };
3578 let mut cell = self.cells.remove(&id).expect("cell found above");
3579 let Phase::RecoveringOwnerLog { owner, .. } = cell.phase.clone() else {
3580 unreachable!()
3581 };
3582 match result {
3583 Ok(()) => {
3584 let epoch = owner.epoch.saturating_add(1);
3585 let prior = owner.node.clone();
3586 self.activate_or_wait(
3587 &id,
3588 &mut cell,
3589 Activation::Claim(Claim {
3590 guard: CasGuard::Match(owner.etag),
3591 epoch,
3592 takeover: true,
3593 prior,
3594 reconciles: 0,
3595 }),
3596 effects,
3597 );
3598 }
3599 Err(_) => {
3600 set_phase(&mut self.occupied, &mut cell, Phase::Inactive);
3601 self.finish_requests(&id, &mut cell, Err(RequestError::ResolveFailed), effects);
3602 }
3603 }
3604 self.cells.insert(id, cell);
3605 }
3606
3607 fn owner_cas_completed(
3608 &mut self,
3609 op: OpId,
3610 result: Result<CasOutcome, Failure>,
3611 effects: &mut Vec<Effect>,
3612 ) {
3613 let Some(id) = self.take_cell_op(
3614 op,
3615 |cell| matches!(cell.phase, Phase::Acquiring { op: current, .. } if current == op),
3616 ) else {
3617 return;
3618 };
3619 let mut cell = self.cells.remove(&id).expect("cell found above");
3620 let Phase::Acquiring { claim, .. } = &cell.phase else {
3621 unreachable!()
3622 };
3623 let claim = claim.clone();
3624 match result {
3625 Ok(CasOutcome::Applied) => {
3626 let spec = RestoreSpec {
3627 epoch: claim.epoch,
3628 fresh: matches!(claim.guard, CasGuard::Absent),
3629 took_over: claim.takeover,
3630 resume_local: false,
3631 prior: claim.prior.clone(),
3632 };
3633 self.record_acquisition(&spec);
3634 let ownership_only = !cell.requests.is_empty()
3635 && cell
3636 .requests
3637 .iter()
3638 .all(|request| self.handoff_requests.contains(request));
3639 if ownership_only {
3640 set_phase(
3641 &mut self.occupied,
3642 &mut cell,
3643 Phase::Dormant { epoch: spec.epoch },
3644 );
3645 } else {
3646 let next = self.cell_op(&id);
3647 set_phase(
3648 &mut self.occupied,
3649 &mut cell,
3650 Phase::Restoring {
3651 op: next,
3652 spec: spec.clone(),
3653 },
3654 );
3655 effects.push(Effect::Restore {
3656 op: next,
3657 cell: id.clone(),
3658 spec,
3659 });
3660 }
3661 }
3662 Ok(CasOutcome::Rejected) => {
3663 let next = self.cell_op(&id);
3664 set_phase(
3665 &mut self.occupied,
3666 &mut cell,
3667 Phase::ReadingOwner { op: next },
3668 );
3669 effects.push(Effect::ReadOwner {
3670 op: next,
3671 cell: id.clone(),
3672 });
3673 }
3674 Err(Failure::Ambiguous) if claim.reconciles < MAX_ACQUIRE_RECONCILES => {
3675 let next = self.cell_op(&id);
3676 let claim = Claim {
3677 reconciles: claim.reconciles + 1,
3678 ..claim
3679 };
3680 set_phase(
3681 &mut self.occupied,
3682 &mut cell,
3683 Phase::ReconcilingAcquire { op: next, claim },
3684 );
3685 effects.push(Effect::ReadOwner {
3686 op: next,
3687 cell: id.clone(),
3688 });
3689 }
3690 Err(Failure::Ambiguous) => {
3691 // Out of reconciles. The claim may or may not have applied, so
3692 // this cell is left dormant for a later request to resolve
3693 // from the record rather than guessed at here.
3694 set_phase(&mut self.occupied, &mut cell, Phase::Inactive);
3695 self.finish_requests(&id, &mut cell, Err(RequestError::AcquireFailed), effects);
3696 }
3697 Err(Failure::Definite) => {
3698 set_phase(&mut self.occupied, &mut cell, Phase::Inactive);
3699 self.finish_requests(&id, &mut cell, Err(RequestError::AcquireFailed), effects);
3700 }
3701 }
3702 self.cells.insert(id, cell);
3703 self.pump_capacity(effects);
3704 }
3705
3706 fn restore_completed(
3707 &mut self,
3708 op: OpId,
3709 result: Result<RestoreOutcome, Failure>,
3710 effects: &mut Vec<Effect>,
3711 ) {
3712 let Some(id) = self.take_cell_op(
3713 op,
3714 |cell| matches!(cell.phase, Phase::Restoring { op: current, .. } if current == op),
3715 ) else {
3716 return;
3717 };
3718 let mut cell = self.cells.remove(&id).expect("cell found above");
3719 let Phase::Restoring { spec, .. } = &cell.phase else {
3720 unreachable!()
3721 };
3722 let epoch = spec.epoch;
3723 let mut resume_failed = false;
3724 match result {
3725 Ok(outcome) => {
3726 if outcome.restored {
3727 self.activity.restored = self.activity.restored.saturating_add(1);
3728 }
3729 // Seed the mirror from the durable truth the restore loaded,
3730 // before the isolate opens the same database and long before
3731 // it would re-arm anything.
3732 if let Some(alarm) = outcome.alarm.filter(|alarm| alarm.at_ms >= 0) {
3733 let generation = self.next_timer_generation;
3734 self.next_timer_generation = self
3735 .next_timer_generation
3736 .checked_add(1)
3737 .expect("timer generation exhausted");
3738 let (now_ms, now_mono_ms) = (self.now_ms, self.now_mono_ms);
3739 self.schedule_alarm_timer(
3740 &id,
3741 generation,
3742 alarm.at_ms,
3743 now_ms,
3744 now_mono_ms,
3745 effects,
3746 );
3747 cell.alarm = Some(AlarmState::Armed {
3748 at_ms: alarm.at_ms,
3749 generation,
3750 covered: alarm.covered,
3751 });
3752 }
3753 let next = self.cell_op(&id);
3754 set_phase(
3755 &mut self.occupied,
3756 &mut cell,
3757 Phase::Starting { op: next, epoch },
3758 );
3759 effects.push(Effect::StartRuntime {
3760 op: next,
3761 cell: id.clone(),
3762 epoch,
3763 });
3764 }
3765 Err(_) => {
3766 set_phase(&mut self.occupied, &mut cell, Phase::Dormant { epoch });
3767 self.finish_requests(&id, &mut cell, Err(RequestError::RestoreFailed), effects);
3768 resume_failed = cell.resume_demand;
3769 }
3770 }
3771 self.cells.insert(id.clone(), cell);
3772 if resume_failed {
3773 self.settle_local_resume(&id);
3774 }
3775 self.pump_capacity(effects);
3776 }
3777
3778 fn runtime_started(
3779 &mut self,
3780 op: OpId,
3781 isolate: Option<isolate::IsolateId>,
3782 generation: u64,
3783 result: Result<(), Failure>,
3784 effects: &mut Vec<Effect>,
3785 ) {
3786 let Some(id) = self.take_cell_op(
3787 op,
3788 |cell| matches!(cell.phase, Phase::Starting { op: current, .. } if current == op),
3789 ) else {
3790 self.compensate_retired_runtime(op, result, effects);
3791 return;
3792 };
3793 self.timed_out_runtime_starts.remove(&op);
3794 let mut cell = self.cells.remove(&id).expect("cell found above");
3795 let Phase::Starting { epoch, .. } = cell.phase else {
3796 unreachable!()
3797 };
3798 let mut resume_failed = false;
3799 match result {
3800 Ok(()) => {
3801 cell.isolate = isolate;
3802 cell.generation = generation;
3803 let next = self.cell_op(&id);
3804 set_phase(
3805 &mut self.occupied,
3806 &mut cell,
3807 Phase::Publishing { op: next, epoch },
3808 );
3809 effects.push(Effect::Publish {
3810 op: next,
3811 cell: id.clone(),
3812 epoch,
3813 });
3814 }
3815 Err(_) => {
3816 set_phase(&mut self.occupied, &mut cell, Phase::Dormant { epoch });
3817 self.finish_requests(&id, &mut cell, Err(RequestError::RuntimeFailed), effects);
3818 resume_failed = cell.resume_demand;
3819 }
3820 }
3821 self.cells.insert(id.clone(), cell);
3822 if resume_failed {
3823 self.settle_local_resume(&id);
3824 }
3825 self.pump_capacity(effects);
3826 }
3827
3828 /// Fail the callers waiting on a runtime start without retiring the start.
3829 ///
3830 /// The shell cannot cancel a V8 startup turn. Treating this deadline as a
3831 /// definite failure lets the next request start a second runtime while the
3832 /// first task can still insert its handle. The late first completion then
3833 /// becomes an untracked runtime which every later request reports as an
3834 /// existing duplicate. Keep the operation indexed instead. Its real
3835 /// completion publishes the runtime or returns the cell to `Dormant`.
3836 fn runtime_start_timed_out(&mut self, op: OpId, effects: &mut Vec<Effect>) {
3837 let Some(id) = self.cell_ops.get(&op).cloned() else {
3838 return;
3839 };
3840 let Some(mut cell) = self.cells.remove(&id) else {
3841 return;
3842 };
3843 if !matches!(cell.phase, Phase::Starting { op: current, .. } if current == op) {
3844 self.cells.insert(id, cell);
3845 return;
3846 }
3847 self.timed_out_runtime_starts.insert(op);
3848 self.finish_requests(&id, &mut cell, Err(RequestError::RuntimeFailed), effects);
3849 self.cells.insert(id, cell);
3850 }
3851
3852 fn published(&mut self, op: OpId, result: Result<(), Failure>, effects: &mut Vec<Effect>) {
3853 let Some(id) = self.take_cell_op(
3854 op,
3855 |cell| matches!(cell.phase, Phase::Publishing { op: current, .. } if current == op),
3856 ) else {
3857 self.compensate_retired_runtime(op, result, effects);
3858 return;
3859 };
3860 let mut cell = self.cells.remove(&id).expect("cell found above");
3861 let Phase::Publishing { epoch, .. } = cell.phase else {
3862 unreachable!()
3863 };
3864 let completing_resume = cell.resume_demand;
3865 match result {
3866 Ok(()) => {
3867 set_phase(&mut self.occupied, &mut cell, Phase::Resident { epoch });
3868 // A swap ends here: the cell is resident again, on the
3869 // generation `runtime_started` recorded.
3870 cell.swapping = false;
3871 cell.swap_cancelled = false;
3872 self.finish_requests(&id, &mut cell, Ok(Route::Local), effects);
3873 }
3874 Err(_) => {
3875 let next = self.cell_op(&id);
3876 set_phase(
3877 &mut self.occupied,
3878 &mut cell,
3879 Phase::Cleaning {
3880 op: next,
3881 epoch,
3882 cause: StopCause::Cleanup,
3883 },
3884 );
3885 effects.push(Effect::StopRuntime {
3886 op: next,
3887 cell: id.clone(),
3888 epoch,
3889 cause: StopCause::Cleanup,
3890 });
3891 }
3892 }
3893 self.cells.insert(id.clone(), cell);
3894 if completing_resume {
3895 self.settle_local_resume(&id);
3896 }
3897 }
3898
3899 /// A release either published the cell as unowned or did not. Ownership
3900 /// is the bucket's answer, not this node's, so a rejected or failed write
3901 /// simply leaves the record naming this node -- correct, if less useful,
3902 /// and the next eviction gets another chance.
3903 fn owner_released(
3904 &mut self,
3905 op: OpId,
3906 result: Result<CasOutcome, Failure>,
3907 effects: &mut Vec<Effect>,
3908 ) {
3909 let Some(id) = self.take_cell_op(op, |cell| cell.releasing == Some(op)) else {
3910 return;
3911 };
3912 let released_epoch = match self.cells.get(&id).map(|cell| &cell.phase) {
3913 Some(Phase::Dormant { epoch }) => Some(*epoch),
3914 _ => None,
3915 };
3916 // Only a cell still sitting where the eviction left it may be
3917 // forgotten. Anything else means it was wanted again while the write
3918 // was in flight, and that claim outranks a release decided earlier.
3919 // On a draining node a rejection settles the cell too: the record no
3920 // longer names this node at this epoch, so nothing here blocks a
3921 // successor, and the pump must not re-read a record it can never
3922 // blank. An indefinite failure stays `Dormant`, which is what makes
3923 // the pump retry it while the drain window is open.
3924 let settled = matches!(result, Ok(CasOutcome::Applied))
3925 || (self.draining && matches!(result, Ok(CasOutcome::Rejected)));
3926 let adoption =
3927 (settled && self.draining && released_epoch.is_some()).then(|| self.cell_op(&id));
3928 let cell = self.cells.get_mut(&id).expect("cell found above");
3929 cell.releasing = None;
3930 if let (Some(released_epoch), Some(adopt)) = (released_epoch, adoption) {
3931 set_phase(
3932 &mut self.occupied,
3933 cell,
3934 Phase::Adopting {
3935 op: adopt,
3936 released_epoch,
3937 },
3938 );
3939 effects.push(Effect::AdoptReleased {
3940 op: adopt,
3941 cell: id,
3942 released_epoch,
3943 });
3944 } else if settled && matches!(cell.phase, Phase::Dormant { .. }) {
3945 set_phase(&mut self.occupied, cell, Phase::Inactive);
3946 }
3947 }
3948
3949 /// Finish one shutdown handoff after a successor acquired the cell. The
3950 /// successor keeps the cell dormant until real traffic needs a runtime,
3951 /// so a fleet restart does not eagerly materialize every resident cell.
3952 fn successor_adopted(
3953 &mut self,
3954 op: OpId,
3955 result: Result<AdoptedCell, Failure>,
3956 effects: &mut Vec<Effect>,
3957 ) {
3958 let Some(id) = self.take_cell_op(
3959 op,
3960 |cell| matches!(cell.phase, Phase::Adopting { op: current, .. } if current == op),
3961 ) else {
3962 return;
3963 };
3964 let mut cell = self.cells.remove(&id).expect("cell found above");
3965 let Phase::Adopting { released_epoch, .. } = cell.phase else {
3966 unreachable!()
3967 };
3968 match result {
3969 Ok(adopted)
3970 if adopted.node != self.node
3971 && !adopted.addr.is_empty()
3972 && adopted.epoch > released_epoch
3973 && adopted.peer_protocol == self.config.peer_protocol =>
3974 {
3975 self.activity.handed_off = self.activity.handed_off.saturating_add(1);
3976 let route = Route::Remote {
3977 node: adopted.node.clone(),
3978 addr: adopted.addr.clone(),
3979 epoch: adopted.epoch,
3980 peer_protocol: adopted.peer_protocol,
3981 };
3982 set_phase(
3983 &mut self.occupied,
3984 &mut cell,
3985 Phase::Remote {
3986 node: adopted.node,
3987 addr: adopted.addr,
3988 epoch: adopted.epoch,
3989 peer_protocol: adopted.peer_protocol,
3990 capacity_sampled_ms: None,
3991 },
3992 );
3993 self.finish_requests(&id, &mut cell, Ok(route), effects);
3994 }
3995 _ => {
3996 self.activity.handoff_failed = self.activity.handoff_failed.saturating_add(1);
3997 set_phase(&mut self.occupied, &mut cell, Phase::Inactive);
3998 self.finish_requests(&id, &mut cell, Err(RequestError::NodeUnavailable), effects);
3999 }
4000 }
4001 self.cells.insert(id, cell);
4002 }
4003
4004 fn runtime_stopped(&mut self, op: OpId, effects: &mut Vec<Effect>) {
4005 let Some(id) = self.take_cell_op(
4006 op,
4007 |cell| matches!(cell.phase, Phase::Cleaning { op: current, .. } if current == op),
4008 ) else {
4009 return;
4010 };
4011 let mut cell = self.cells.remove(&id).expect("cell found above");
4012 // The realm went with the runtime. Leaving the isolate recorded here
4013 // would keep counting this cell against that heap, so the walk down
4014 // would never see an isolate empty and would never aim at one.
4015 cell.isolate = None;
4016 let Phase::Cleaning { epoch, cause, .. } = cell.phase else {
4017 unreachable!()
4018 };
4019 match cause {
4020 StopCause::Cleanup => {
4021 set_phase(&mut self.occupied, &mut cell, Phase::Dormant { epoch });
4022 self.finish_requests(&id, &mut cell, Err(RequestError::PublishFailed), effects);
4023 }
4024 // `Inactive`, not `Dormant`: the next request re-reads the
4025 // ownership record. A proof that could not be completed is exactly
4026 // the moment to stop assuming this node still holds the cell, and
4027 // the re-read costs one GET on a path that was already failing.
4028 StopCause::Reset => {
4029 set_phase(&mut self.occupied, &mut cell, Phase::Inactive);
4030 if let Some(AlarmState::Firing { op, .. }) = cell.alarm {
4031 self.cell_ops.remove(&op);
4032 }
4033 cell.alarm = None;
4034 cell.alarm_wake = false;
4035 cell.websockets.clear();
4036 self.finish_requests(
4037 &id,
4038 &mut cell,
4039 Err(RequestError::DurabilityUnproven),
4040 effects,
4041 );
4042 }
4043 StopCause::Evict { rebalance }
4044 if cell.requests.is_empty() || (self.draining && rebalance) =>
4045 {
4046 set_phase(&mut self.occupied, &mut cell, Phase::Dormant { epoch });
4047 self.eviction_permits.remove(&id);
4048 // The record still names this node, which is the whole cost of
4049 // stopping here: every later request for the cell routes to a
4050 // node that has already decided it has no room. Publishing it
4051 // as unowned is what turns an eviction into shed load.
4052 if rebalance {
4053 let op = self.cell_op(&id);
4054 cell.releasing = Some(op);
4055 effects.push(Effect::ReleaseOwner {
4056 op,
4057 cell: id.clone(),
4058 epoch,
4059 });
4060 }
4061 }
4062 StopCause::Evict { .. } => {
4063 // A request arrived mid-eviction, so the cell turns straight
4064 // back around. The eviction is over either way.
4065 self.eviction_permits.remove(&id);
4066 // The stop discarded the LTX metadata. Re-read ownership and
4067 // claim epoch+1 before reusing the preserved SQLite image.
4068 self.admit_or_queue_activation(&id, &mut cell, ColdStart::ReadOwner, effects);
4069 }
4070 // The node began leaving while the cell was between isolates.
4071 // Started again it would only be one more resident for the
4072 // drain to evict; dormant, the drain releases its record like
4073 // any other.
4074 StopCause::Swap if self.draining => {
4075 set_phase(&mut self.occupied, &mut cell, Phase::Dormant { epoch });
4076 self.finish_requests(&id, &mut cell, Err(RequestError::PublishFailed), effects);
4077 }
4078 // The swap's second half: the same epoch, the same owner record,
4079 // the same replica, a new isolate. `Starting` without `Restore`
4080 // is deliberate — the database is open on disk and the LTX
4081 // handle never closed — and without `CasOwner`, because nothing
4082 // about ownership changed. Requests queued while the cell
4083 // quiesced release when it publishes.
4084 StopCause::Swap => {
4085 let op = self.cell_op(&id);
4086 set_phase(&mut self.occupied, &mut cell, Phase::Starting { op, epoch });
4087 effects.push(Effect::StartRuntime {
4088 op,
4089 cell: id.clone(),
4090 epoch,
4091 });
4092 }
4093 StopCause::Fence => unreachable!("fenced cells do not wait for runtime shutdown"),
4094 }
4095 self.cells.insert(id, cell);
4096 self.pump_capacity(effects);
4097 self.shed_toward_floor(effects);
4098 }
4099
4100 /// Announce the generation the node now serves.
4101 ///
4102 /// Nothing moves here, and nothing is marked; the pump moves cells after
4103 /// this and every later event, so the bound, the safe point, and
4104 /// eagerness are decided by the same code whether a cell became stale
4105 /// now or lands stale later. A resident cell of an eager class is forced
4106 /// at once: the engine's reserved cells hold no application state worth
4107 /// waiting for, and the cron cell must run the new schedule before the
4108 /// adoption arms it.
4109 fn generation_changed(&mut self, generation: u64, max_age_ms: u64, eager_classes: &[String]) {
4110 if generation <= self.current_generation {
4111 return;
4112 }
4113 self.current_generation = generation;
4114 self.generation_changed_mono_ms = self.now_mono_ms;
4115 self.swap_max_age_ms = max_age_ms;
4116 self.swap_eager_classes = eager_classes.iter().cloned().collect();
4117 }
4118
4119 /// Whether this cell's class was named eager by the last announcement, so
4120 /// its swap does not wait for the maximum age.
4121 ///
4122 /// A scope is `<class>:<instance>` and the instance may itself contain a
4123 /// `:`, so the class is everything before the first one -- the same split
4124 /// the shell makes when it resolves a cell to its Worker config.
4125 fn swap_is_eager(&self, id: &str) -> bool {
4126 let class = id.split_once(':').map_or(id, |(class, _)| class);
4127 self.swap_eager_classes.contains(class)
4128 }
4129
4130 /// Whether a swap can stop this cell's runtime now without cutting work
4131 /// short: no request running, no output withheld by the gate, no alarm
4132 /// handler in flight, and no regular or outbound socket, which cannot
4133 /// outlive the isolate. The input gate is not consulted; a
4134 /// `blockConcurrencyWhile` holder is a running request or alarm, so it is
4135 /// covered by those.
4136 fn swap_safe_point(&self, id: &str) -> bool {
4137 let Some(cell) = self.cells.get(id) else {
4138 return false;
4139 };
4140 !self.active_cells.contains_key(id)
4141 && !cell
4142 .websockets
4143 .values()
4144 .any(|kind| matches!(kind, WebSocketKind::Regular | WebSocketKind::Outbound))
4145 && !matches!(cell.alarm, Some(AlarmState::Firing { .. }))
4146 && !self.barriers.values().any(|barrier| barrier.cell == id)
4147 }
4148
4149 /// The swap pump, run after every event once a generation change has
4150 /// been announced: move every resident cell on an older generation to
4151 /// the current one, at most `max_releases` at a time.
4152 ///
4153 /// A nominated cell quiesces first, exactly as a shutdown handoff does:
4154 /// new requests queue for the restarted runtime instead of routing to the
4155 /// old one, so continuous traffic cannot keep the cell from ever reaching
4156 /// a safe point. Work already admitted finishes. At the safe point the
4157 /// cell stops with `StopCause::Swap`, and `runtime_stopped` starts it
4158 /// again on the current generation at the same epoch.
4159 ///
4160 /// A cell that never reaches a safe point — a regular WebSocket, an
4161 /// endless request — is forced once the maximum age has passed, or at
4162 /// once when its class is eager: its activity is cancelled, which is what
4163 /// a Cloudflare deployment does to every object unconditionally. The
4164 /// hibernatable sockets survive either way.
4165 fn pump_swap(&mut self, effects: &mut Vec<Effect>) {
4166 if self.current_generation == 0
4167 || self.draining
4168 || self.fenced
4169 || !self.node_authoritative()
4170 {
4171 return;
4172 }
4173 let current = self.current_generation;
4174 let forced_by_age = self
4175 .now_mono_ms
4176 .saturating_sub(self.generation_changed_mono_ms)
4177 >= self.swap_max_age_ms;
4178 let in_flight = self.cells.values().filter(|cell| cell.swapping).count();
4179 let room = self.config.max_releases.saturating_sub(in_flight);
4180 let stale: Vec<CellId> = self
4181 .cells
4182 .iter()
4183 .filter(|(_, cell)| {
4184 matches!(cell.phase, Phase::Resident { .. })
4185 && !cell.swapping
4186 && !cell.quiescing
4187 && cell.releasing.is_none()
4188 && cell.generation != current
4189 })
4190 .map(|(id, _)| id.clone())
4191 .collect();
4192 for id in stale.into_iter().take(room) {
4193 let cell = self.cells.get_mut(&id).expect("stale cell listed above");
4194 cell.swapping = true;
4195 cell.quiescing = true;
4196 }
4197 let nominated: Vec<CellId> = self
4198 .cells
4199 .iter()
4200 .filter(|(_, cell)| {
4201 cell.swapping && cell.quiescing && matches!(cell.phase, Phase::Resident { .. })
4202 })
4203 .map(|(id, _)| id.clone())
4204 .collect();
4205 for id in nominated {
4206 if !self.swap_safe_point(&id) {
4207 let eager = self.swap_is_eager(&id);
4208 let cell = self.cells.get(&id).expect("nominated cell listed above");
4209 if !(forced_by_age || eager) || cell.swap_cancelled {
4210 continue;
4211 }
4212 let requests = self
4213 .active_requests
4214 .iter()
4215 .filter_map(|(request, cell)| (cell == &id).then_some(*request))
4216 .collect();
4217 let cell = self
4218 .cells
4219 .get_mut(&id)
4220 .expect("nominated cell listed above");
4221 cell.swap_cancelled = true;
4222 let websockets = cell
4223 .websockets
4224 .iter()
4225 .filter(|(_, kind)| !matches!(kind, WebSocketKind::Hibernatable))
4226 .map(|(websocket, _)| *websocket)
4227 .collect();
4228 effects.push(Effect::CancelCellActivity {
4229 cell: id,
4230 requests,
4231 websockets,
4232 keep_hibernatable: true,
4233 });
4234 continue;
4235 }
4236 let op = self.cell_op(&id);
4237 let cell = self
4238 .cells
4239 .get_mut(&id)
4240 .expect("nominated cell listed above");
4241 let Phase::Resident { epoch } = cell.phase else {
4242 unreachable!("nominated cells are resident")
4243 };
4244 set_phase(
4245 &mut self.occupied,
4246 cell,
4247 Phase::Cleaning {
4248 op,
4249 epoch,
4250 cause: StopCause::Swap,
4251 },
4252 );
4253 effects.push(Effect::StopRuntime {
4254 op,
4255 cell: id,
4256 epoch,
4257 cause: StopCause::Swap,
4258 });
4259 }
4260 }
4261
4262 /// The generation a cell's runtime was started on, if it has one.
4263 pub fn cell_generation(&self, id: &str) -> Option<u64> {
4264 self.cells.get(id).map(|cell| cell.generation)
4265 }
4266
4267 /// The generation the node serves, as last announced.
4268 pub fn current_generation(&self) -> u64 {
4269 self.current_generation
4270 }
4271
4272 /// Cells moving to the current generation right now.
4273 pub fn swapping(&self) -> usize {
4274 self.cells.values().filter(|cell| cell.swapping).count()
4275 }
4276
4277 fn durability_checked(
4278 &mut self,
4279 op: OpId,
4280 result: Result<(), Failure>,
4281 effects: &mut Vec<Effect>,
4282 ) {
4283 let now = self.now_mono_ms;
4284 let Some(id) = self.take_cell_op(op, |cell| {
4285 matches!(cell.phase, Phase::EnsuringDurability { op: current, .. } if current == op)
4286 }) else {
4287 return;
4288 };
4289 let cell = self.cells.get_mut(&id).expect("cell found above");
4290 let Phase::EnsuringDurability { epoch, .. } = cell.phase else {
4291 unreachable!()
4292 };
4293 match result {
4294 Ok(()) => {
4295 // Minted inline: `cell` still borrows the map, and field
4296 // accesses split where a method call cannot.
4297 let stop = self.next_op;
4298 self.next_op = self.next_op.checked_add(1).expect("operation id exhausted");
4299 self.cell_ops.insert(stop, id.clone());
4300 let rebalance = cell.evict_rebalance;
4301 set_phase(
4302 &mut self.occupied,
4303 cell,
4304 Phase::Cleaning {
4305 op: stop,
4306 epoch,
4307 cause: StopCause::Evict { rebalance },
4308 },
4309 );
4310 effects.push(Effect::StopRuntime {
4311 op: stop,
4312 cell: id,
4313 epoch,
4314 cause: StopCause::Evict { rebalance },
4315 });
4316 }
4317 Err(_) => {
4318 set_phase(&mut self.occupied, cell, Phase::Resident { epoch });
4319 cell.eviction_refused_mono_ms = Some(now);
4320 self.eviction_permits.remove(&id);
4321 }
4322 }
4323 }
4324
4325 /// Evict on demand. Local, like an idle eviction: the caller asked
4326 /// this node to drop the cell, not to give it away.
4327 fn evict(&mut self, id: &str, effects: &mut Vec<Effect>) {
4328 self.begin_eviction(id, false, effects);
4329 }
4330
4331 /// Shutdown handoff: give every resident cell away by releasing its
4332 /// owner record, so peers take over at once instead of waiting out the
4333 /// node lease. `rebalance` is forced true, so this releases even when
4334 /// `ownership_on_evict` keeps ownership on an ordinary evict.
4335 ///
4336 /// Only marks the node draining; `pump_release` does the work, at most
4337 /// `max_releases` at a time. An unbounded walk here would start a
4338 /// durability proof per resident cell at once -- a node holding
4339 /// thousands turns its own shutdown into the restore storm the eviction
4340 /// bound exists to prevent, and trips the `validate` ceiling besides.
4341 fn release_all(&mut self, effects: &mut Vec<Effect>) {
4342 self.draining = true;
4343 self.pump_release(effects);
4344 }
4345
4346 /// The drain pump, run after every event once draining: keep
4347 /// `max_releases` handoffs in flight while any owned cell remains.
4348 /// The pump first marks a bounded batch as quiescing. A quiescing cell
4349 /// queues new requests for its successor, so continuous traffic cannot
4350 /// keep finding a fresh activity between eviction attempts. Work already
4351 /// admitted on the cell finishes before its durability proof starts.
4352 /// Releases in flight count against the same ceiling as the proofs: the
4353 /// bound exists to keep shutdown from flooding the store, and a release
4354 /// is one more write in that flood.
4355 fn pump_release(&mut self, effects: &mut Vec<Effect>) {
4356 if !self.draining {
4357 return;
4358 }
4359 let mut in_flight =
4360 self.eviction_permits.len() + self.releasing() + self.adopting() + self.quiescing();
4361
4362 // A reserved cell can become idle on any event. Promote it into the
4363 // ordinary eviction state without spending another handoff permit.
4364 let quiescing: Vec<CellId> = self
4365 .cells
4366 .iter()
4367 .filter(|(_, cell)| cell.quiescing)
4368 .map(|(id, _)| id.clone())
4369 .collect();
4370 for id in quiescing {
4371 self.begin_eviction(&id, true, effects);
4372 }
4373
4374 // Reserve the complete batch even when its cells are active. Future
4375 // requests wait in `cell.requests`; the already-running requests keep
4376 // the runtime pinned until their activity guards finish.
4377 let residents: Vec<CellId> = self
4378 .cells
4379 .iter()
4380 .filter(|(_, cell)| !cell.quiescing && matches!(cell.phase, Phase::Resident { .. }))
4381 .map(|(id, _)| id.clone())
4382 .collect();
4383 for id in residents {
4384 if in_flight >= self.config.max_releases {
4385 return;
4386 }
4387 let requests = self
4388 .active_requests
4389 .iter()
4390 .filter_map(|(request, cell)| (cell == &id).then_some(*request))
4391 .collect();
4392 let cell = self.cells.get_mut(&id).expect("resident cell listed above");
4393 cell.quiescing = true;
4394 let websockets = cell.websockets.keys().copied().collect();
4395 effects.push(Effect::CancelCellActivity {
4396 cell: id.clone(),
4397 requests,
4398 websockets,
4399 keep_hibernatable: false,
4400 });
4401 in_flight += 1;
4402 if !self.begin_eviction(&id, true, effects) {
4403 continue;
4404 }
4405 }
4406 // A cell evicted before the drain kept its record on this node --
4407 // a sticky eviction, hibernation, or a release whose write failed
4408 // -- so a later request could resume locally. On a leaving node
4409 // that record only makes a successor wait out the node lease. The
4410 // runtime is already stopped, so the drain releases the record
4411 // directly.
4412 let dormant: Vec<(CellId, Epoch)> = self
4413 .cells
4414 .iter()
4415 .filter_map(|(id, cell)| match cell.phase {
4416 Phase::Dormant { epoch } if cell.releasing.is_none() => Some((id.clone(), epoch)),
4417 _ => None,
4418 })
4419 .collect();
4420 for (id, epoch) in dormant {
4421 if in_flight >= self.config.max_releases {
4422 return;
4423 }
4424 let op = self.cell_op(&id);
4425 let cell = self.cells.get_mut(&id).expect("dormant cell listed above");
4426 cell.releasing = Some(op);
4427 effects.push(Effect::ReleaseOwner {
4428 op,
4429 cell: id,
4430 epoch,
4431 });
4432 in_flight += 1;
4433 }
4434 }
4435
4436 /// Does an eviction made for room hand the cell away?
4437 fn rebalances(&self) -> bool {
4438 self.config.ownership_on_evict == OwnershipOnEvict::Release
4439 }
4440
4441 fn begin_eviction(&mut self, id: &str, rebalance: bool, effects: &mut Vec<Effect>) -> bool {
4442 // An alarm about to fire is not worth an eviction: the wake costs
4443 // more than the residency it would save, so the cell is held even
4444 // though its entry is perfectly durable. Coverage says the alarm can
4445 // survive the eviction; this says it is not worth surviving it.
4446 let alarm_is_imminent = self.cells.get(id).is_some_and(|cell| match cell.alarm {
4447 Some(AlarmState::Armed { at_ms, .. }) | Some(AlarmState::Firing { at_ms, .. }) => {
4448 at_ms >= 0
4449 && (at_ms as u64).saturating_sub(self.now_ms) <= self.config.alarm_resident_ms
4450 }
4451 None => false,
4452 });
4453 // Only while there is room to spare. Holding a cell to save a wake is
4454 // worth it on an idle node and indefensible on a full one: the window
4455 // defaults to an hour, so on an alarm-driven workload this would hold
4456 // most of the node and pin it at its ceiling -- trading a real
4457 // admission failure for a saved activation. Under pressure the node
4458 // takes the wake.
4459 if alarm_is_imminent && !self.shedding && !self.draining {
4460 return false;
4461 }
4462 let alarm_is_safe = self.cells.get(id).is_some_and(|cell| {
4463 cell.alarm
4464 .as_ref()
4465 .is_none_or(|alarm| matches!(alarm, AlarmState::Armed { covered: true, .. }))
4466 });
4467 if !self.is_hibernatable(id) || !alarm_is_safe {
4468 return false;
4469 }
4470 let Some(Phase::Resident { epoch }) = self.cells.get(id).map(|cell| &cell.phase) else {
4471 return false;
4472 };
4473 let epoch = *epoch;
4474 let op = self.cell_op(id);
4475 let Some(cell) = self.cells.get_mut(id) else {
4476 return false;
4477 };
4478 cell.evict_rebalance = rebalance;
4479 set_phase(
4480 &mut self.occupied,
4481 cell,
4482 Phase::EnsuringDurability { op, epoch },
4483 );
4484 self.eviction_permits.insert(id.to_string());
4485 effects.push(Effect::EnsureDurable {
4486 op,
4487 cell: id.to_string(),
4488 epoch,
4489 });
4490 true
4491 }
4492
4493 fn shed_one(&mut self, effects: &mut Vec<Effect>) {
4494 // Only when the blocker is headroom. A latched node is already walking
4495 // down on its own schedule, and admission stays closed until it
4496 // reaches the low watermark -- so shedding to make room for a waiter
4497 // that cannot be admitted has no stopping condition, and every
4498 // completed eviction re-enters here through `pump_capacity` and starts
4499 // another. That empties the node.
4500 //
4501 // Count the evictions already in flight against the waiters: this is
4502 // reachable from every activity finish and websocket close, and a
4503 // waiter whose eviction is already under way must not turn each of
4504 // those triggers into another victim. Spend the cut on commit, never
4505 // on nomination.
4506 if self.shedding
4507 || self.capacity_waiters.len() <= self.eviction_permits.len()
4508 || self.eviction_permits.len() >= self.config.max_evictions
4509 {
4510 return;
4511 }
4512 if let Some(victim) = self.shed_candidate() {
4513 self.begin_eviction(&victim, self.rebalances(), effects);
4514 }
4515 }
4516
4517 /// The cell to shed right now: resident, idle, not holding an alarm the
4518 /// node still owes, and the least recently used of those. Demand shedding
4519 /// and pressure shedding both come through here, so they cannot disagree
4520 /// about what is safe to take or which one to take first.
4521 /// Bound the time a cell can sit behind the admission gate.
4522 ///
4523 /// Every other stall in a cold route is bounded by `operation_deadline_ms`
4524 /// through `watch_operations`, which arms per emitted effect. A parked
4525 /// cell has emitted none, so it is the one stall nothing expires, and a
4526 /// gate that closes on memory the queue itself holds can never reopen.
4527 fn watch_queued(&mut self, id: &str, cell: &mut Cell, effects: &mut Vec<Effect>) {
4528 let Some(deadline_ms) = self.config.operation_deadline_ms else {
4529 return;
4530 };
4531 let generation = self.next_timer_generation;
4532 self.next_timer_generation = self
4533 .next_timer_generation
4534 .checked_add(1)
4535 .expect("timer generation exhausted");
4536 cell.queued_generation = Some(generation);
4537 effects.push(Effect::ScheduleTimer {
4538 timer: Timer::QueuedActivation {
4539 cell: id.to_string(),
4540 generation,
4541 },
4542 at_mono_ms: self.now_mono_ms.saturating_add(deadline_ms),
4543 });
4544 }
4545
4546 /// A cell that has waited out its deadline behind the gate.
4547 ///
4548 /// Answering `CapacityExhausted` is the existing refusal for "not here,
4549 /// not now": it already carries the stale-route header, so the caller
4550 /// re-resolves instead of retrying a node that cannot take it.
4551 fn expire_queued(&mut self, cell: &str, generation: u64, effects: &mut Vec<Effect>) {
4552 let Some(queued) = self.cells.get(cell) else {
4553 return;
4554 };
4555 if queued.queued_generation != Some(generation) {
4556 return;
4557 }
4558 if !matches!(
4559 queued.phase,
4560 Phase::WaitingActivation | Phase::WaitingCapacity
4561 ) {
4562 return;
4563 }
4564 for request in queued.requests.iter().copied().collect::<Vec<_>>() {
4565 effects.push(Effect::Complete {
4566 request,
4567 result: Err(RequestError::CapacityExhausted),
4568 });
4569 self.request_cells.remove(&request);
4570 self.capacity_requests.remove(&request);
4571 if let Some(queued) = self.cells.get_mut(cell) {
4572 queued.requests.remove(&request);
4573 }
4574 }
4575 self.activation_waiters.retain(|queued| queued != cell);
4576 self.capacity_waiters.retain(|queued| queued != cell);
4577 let Some(queued) = self.cells.get_mut(cell) else {
4578 return;
4579 };
4580 queued.queued_generation = None;
4581 // An alarm wake is not a client waiting, so it keeps the cell queued
4582 // rather than being refused with the requests.
4583 if queued.alarm_wake {
4584 return;
4585 }
4586 let start = queued.waiting_activation.take();
4587 let activation = queued.waiting_for.take();
4588 let dormant = match (start, activation) {
4589 (Some(ColdStart::Restore(spec)), _) => Some(spec.epoch),
4590 (_, Some(Activation::Restore(spec))) => Some(spec.epoch),
4591 _ => None,
4592 };
4593 set_phase(
4594 &mut self.occupied,
4595 queued,
4596 match dormant {
4597 Some(epoch) => Phase::Dormant { epoch },
4598 None => Phase::Inactive,
4599 },
4600 );
4601 }
4602
4603 fn shed_candidate(&self) -> Option<CellId> {
4604 let evictable = |id: &CellId, cell: &Cell| {
4605 self.is_hibernatable(id)
4606 && cell
4607 .alarm
4608 .as_ref()
4609 .is_none_or(|alarm| matches!(alarm, AlarmState::Armed { covered: true, .. }))
4610 };
4611 // How many cells each isolate still holds. The victim comes from the
4612 // one closest to empty, because only the cut that takes an isolate's
4613 // last cell gives the heap back -- and the heap is where the memory
4614 // is. Evicting by recency alone spreads the cuts over every isolate,
4615 // so the node gives up its working set and frees nothing.
4616 let mut occupancy: BTreeMap<isolate::IsolateId, usize> = BTreeMap::new();
4617 for cell in self.cells.values() {
4618 if let Some(isolate) = cell.isolate {
4619 *occupancy.entry(isolate).or_default() += 1;
4620 }
4621 }
4622 self.cells
4623 .iter()
4624 .filter(|(id, cell)| evictable(id, cell))
4625 // Within an isolate the order is unchanged: never-refused first,
4626 // then by how long ago the refusal was, then least recently used,
4627 // with the id as a tiebreak so the choice is a function of the
4628 // state and not of map iteration order.
4629 //
4630 // A cell the shell never placed sorts last rather than first. It
4631 // has no heap to give back, so preferring it would reintroduce the
4632 // scatter this ordering exists to remove.
4633 .min_by_key(|(id, cell)| {
4634 let emptiest = cell
4635 .isolate
4636 .and_then(|isolate| occupancy.get(&isolate).copied())
4637 .unwrap_or(usize::MAX);
4638 (
4639 emptiest,
4640 cell.eviction_refused_mono_ms,
4641 cell.last_used_mono_ms,
4642 (*id).clone(),
4643 )
4644 })
4645 .map(|(id, _)| id.clone())
4646 }
4647
4648 /// Release one cell that has gone cold, with nothing asking for the room.
4649 ///
4650 /// Shedding answers "this node is in trouble"; this answers the ordinary
4651 /// question of a cell nobody has touched in a long time. Without it a node
4652 /// only ever gives a cell back under pressure or when another cell wants
4653 /// the slot, so a quiet node holds every cell it ever served until it
4654 /// reaches a watermark -- paying to keep runtimes alive for traffic that
4655 /// stopped hours ago.
4656 fn evict_idle(&mut self, now_mono_ms: u64, effects: &mut Vec<Effect>) {
4657 let Some(idle_ms) = self.config.idle_evict_ms else {
4658 return;
4659 };
4660 let Some(candidate) = self.shed_candidate() else {
4661 return;
4662 };
4663 let cold = self
4664 .cells
4665 .get(&candidate)
4666 .is_some_and(|cell| now_mono_ms.saturating_sub(cell.last_used_mono_ms) >= idle_ms);
4667 if cold {
4668 // Idle eviction is a local residency decision, not a handoff.
4669 self.begin_eviction(&candidate, false, effects);
4670 }
4671 }
4672
4673 /// Fold a resource sample into the shedding latch, then act on it.
4674 ///
4675 /// The latch is the whole point. Shedding on the instantaneous crossing
4676 /// alone flaps: the eviction relieves the pressure, admission resumes, the
4677 /// ceiling is crossed again. `PressureConfig` holds the node in shedding
4678 /// until every configured low watermark clears, so the node walks down to
4679 /// its target instead of oscillating around its ceiling.
4680 fn load_sampled(&mut self, load: pressure::Load, now_mono_ms: u64, effects: &mut Vec<Effect>) {
4681 self.memory_headroom = self.config.pressure.has_headroom(load);
4682 // Both latches are folded, and the reason names the more serious of the
4683 // two. The latches are state of their own: derived from the reason
4684 // instead, one crossing holds the node against the other's watermark.
4685 let (latches, reason) = self.config.pressure.classify(load, self.latches);
4686 self.latches = latches;
4687 self.shed_reason = reason;
4688 self.shedding = reason.is_some();
4689 if !self.shedding {
4690 // Relieved. Whatever was queued for capacity may proceed.
4691 self.shed_cut = None;
4692 self.pump_capacity(effects);
4693 self.evict_idle(now_mono_ms, effects);
4694 return;
4695 }
4696 // Evicting only helps if it can finish the job. Without a stopping
4697 // condition, a ceiling below the process's memory floor cuts a
4698 // proportion of whatever remains on every sample and walks the node to
4699 // zero. So the latch holds -- admission stays closed, the node is over
4700 // its ceiling -- while the walk down stops spending the working set.
4701 // `walk_metric` documents which measurement it reads and why. Changing
4702 // that measurement discards the baseline: the two numbers are not
4703 // comparable, and they sit close enough to find each other flat by
4704 // coincidence.
4705 let metric = pressure::PressureConfig::walk_metric(latches);
4706 let sample_bytes = load.metric_bytes(metric);
4707 if self.shed_cut.is_some_and(|cut| cut.metric != metric) {
4708 self.shed_cut = None;
4709 }
4710 if let Some(cut) = self.shed_cut {
4711 let cut_landed = self.occupied() <= self.shed_floor && self.eviction_permits.is_empty();
4712 // A rising sample re-arms the walk down: the projection was built
4713 // from a measurement that no longer describes the node, so take a
4714 // fresh baseline. The band absorbs the jitter of a live sample and
4715 // decides nothing about what a cut must achieve.
4716 let rose = sample_bytes > cut.bytes.saturating_add(cut.bytes / 100);
4717 if cut_landed && !rose && !self.shedding_can_reach_resume_line(cut, sample_bytes) {
4718 return;
4719 }
4720 }
4721 // How far this resource sample asks the node to come down: a proportion
4722 // of what was just measured, because the effect of an eviction on the
4723 // sample is not visible until the next one.
4724 self.shed_floor = pressure::PressureConfig::release_target(load.resident_cells);
4725 self.shed_cut = Some(ShedCut {
4726 metric,
4727 bytes: sample_bytes,
4728 cells: load.resident_cells,
4729 });
4730 self.shed_toward_floor(effects);
4731 }
4732
4733 /// Is there a heap this walk down can still take back whole?
4734 ///
4735 /// True when some isolate holds only evictable cells and it is not the
4736 /// last one. The last one is excluded deliberately: emptying it means
4737 /// walking the node to zero, which is the case the stopping condition
4738 /// exists to prevent, and the node keeps one heap's worth of working set
4739 /// instead.
4740 ///
4741 /// A cell the shell never placed counts against nothing here, so a node
4742 /// with no placement reported falls through to the projection unchanged.
4743 fn can_empty_an_isolate(&self) -> bool {
4744 let mut evictable: BTreeMap<isolate::IsolateId, bool> = BTreeMap::new();
4745 for (id, cell) in &self.cells {
4746 let Some(isolate) = cell.isolate else {
4747 continue;
4748 };
4749 let can_go = self.is_hibernatable(id)
4750 && cell
4751 .alarm
4752 .as_ref()
4753 .is_none_or(|alarm| matches!(alarm, AlarmState::Armed { covered: true, .. }));
4754 *evictable.entry(isolate).or_insert(true) &= can_go;
4755 }
4756 evictable.len() > 1 && evictable.values().any(|all_evictable| *all_evictable)
4757 }
4758
4759 /// Can shedding still get the sample down to the resume line?
4760 ///
4761 /// Do not replace this with a band on the last two samples, at any width.
4762 /// A cut is a proportion of the cells while the sample also holds memory no
4763 /// cell owns, so once that fixed part dominates, a cut that helps moves the
4764 /// sample by less than the band and the walk down stops above a line it
4765 /// could reach. That is #50, and 5% and 1% both had it.
4766 ///
4767 /// The yield is wanted honest, not corrected: a node that keeps part of a
4768 /// stopped cell really does return less per eviction, and holding the
4769 /// working set is the right answer there. A lagging sample under-reports
4770 /// the yield for a sample or two, and the walk down survives that because
4771 /// a stop takes no fresh baseline: the sample keeps falling against the
4772 /// bytes of the last cut until the memory that came back late has landed
4773 /// against it.
4774 fn shedding_can_reach_resume_line(&self, cut: ShedCut, sample_bytes: u64) -> bool {
4775 let Some(resume_line) = self.config.pressure.resume_line(cut.metric) else {
4776 // Unreachable: `walk_metric` only names a measurement whose ceiling
4777 // is configured. With no line, the safe answer is that shedding
4778 // buys nothing, so the caller keeps the working set.
4779 return false;
4780 };
4781 // The projection below prices the next cut from the last one, which
4782 // only holds while every cut is worth the same. It is not: a cut that
4783 // takes an isolate's last cell returns that heap, and the heap is
4784 // most of what a cell costs. So while a heap can still be emptied,
4785 // the last cut does not describe the next one and the projection has
4786 // nothing to say.
4787 if self.can_empty_an_isolate() {
4788 return true;
4789 }
4790 let removed = cut.cells.saturating_sub(self.occupied());
4791 if removed == 0 {
4792 // Only a node holding nothing arrives here. Reaching this call
4793 // means `occupied` is at or below `release_target(cut.cells)`,
4794 // which sits strictly below `cut.cells` for any residency but
4795 // zero, so zero is the one residency where a cut can vacate
4796 // nothing and still be measured. It vacated nothing because there
4797 // was nothing to vacate, so there is no yield to project and the
4798 // division below would be by zero.
4799 //
4800 // Such a node is over its ceiling on memory no cell owns, and it
4801 // holds no cell to spend on the crossing. The two answers here
4802 // therefore differ only in which sample the baseline remembers,
4803 // and neither changes what the node does. This one lets the walk
4804 // down carry on, the way the isolate arm above does.
4805 return true;
4806 }
4807 let returned = cut.bytes.saturating_sub(sample_bytes);
4808 // One division, at the end: a per-cell yield rounded to a whole number
4809 // first is zero for any cell worth less than a byte more than the
4810 // rounding, which reports every walk down on a large node as futile.
4811 let projected = u128::from(returned).saturating_mul(self.occupied() as u128)
4812 / u128::from(removed as u64);
4813 let floor = u128::from(sample_bytes).saturating_sub(projected);
4814 // Inclusive: `classify` holds the latch only *above* the low watermark,
4815 // so a projection landing exactly on the line reaches a node that
4816 // releases. A strict `<` here wedges that node.
4817 floor <= u128::from(resume_line)
4818 }
4819
4820 /// Continue a latched walk down as each eviction lands.
4821 ///
4822 /// `shed_one` stands down while the latch is hot, because its stopping
4823 /// condition -- the waiter got in -- cannot be met until the node is
4824 /// relieved. This is the other half: a stopping condition that can be met,
4825 /// so the node reaches its floor at the speed evictions complete rather
4826 /// than one per sampling period. Serialized like every other eviction
4827 /// path, so a walk down never puts the whole working set in flight.
4828 fn shed_toward_floor(&mut self, effects: &mut Vec<Effect>) {
4829 if !self.shedding || self.occupied() <= self.shed_floor {
4830 return;
4831 }
4832 // Fill the permits rather than starting one and waiting for it. Each
4833 // proof is a round trip, so a serialized drain costs the number of
4834 // cells times that latency; running the bound's worth at once is the
4835 // difference between a walk down measured in seconds and one measured
4836 // in minutes.
4837 // Count what is already leaving against the target. `occupied` still
4838 // includes a cell whose proof is in flight, so comparing it directly
4839 // nominates cells the evictions already under way will account for,
4840 // and the node settles below its floor by up to the whole bound --
4841 // the mistake celld's eviction budget documents: spend the cut on
4842 // commit, never on nomination.
4843 while self.eviction_permits.len() < self.config.max_evictions
4844 && self.occupied().saturating_sub(self.eviction_permits.len()) > self.shed_floor
4845 {
4846 let Some(victim) = self.shed_candidate() else {
4847 return;
4848 };
4849 if !self.begin_eviction(&victim, self.rebalances(), effects) {
4850 return;
4851 }
4852 }
4853 }
4854
4855 fn activity_finished(&mut self, request: RequestId, effects: &mut Vec<Effect>) {
4856 // A write still on the output gate keeps its request pinned, so the
4857 // cell cannot be evicted before the write is proven durable. The unpin
4858 // moves to whichever path drains the last gate for this request.
4859 if self.barriers.values().any(|barrier| {
4860 matches!(&barrier.owner, GateOwner::Output(held) if held.request == request)
4861 || barrier.followers.iter().any(|held| held.request == request)
4862 }) {
4863 self.gate_pinned.insert(request);
4864 return;
4865 }
4866 if let Some(id) = self.deactivate_request(request) {
4867 let now = self.now_mono_ms;
4868 if let Some(cell) = self.cells.get_mut(&id) {
4869 cell.last_used_mono_ms = now;
4870 }
4871 }
4872 self.shed_one(effects);
4873 }
4874
4875 /// Discard a runtime whose durability could not be proved.
4876 ///
4877 /// The caller has been told its write failed. If the cell stays resident,
4878 /// the very next read is served from the same unreplicated memory and
4879 /// returns that write anyway -- the node disagreeing with what it just
4880 /// told a client. Stopping with [`StopCause::Reset`] keeps no local
4881 /// snapshot, so the next activation restores from the bucket.
4882 ///
4883 /// Note this is a stop, not a truncation. The restored database is not
4884 /// invalidated by a failed proof; only this node's unreplicated additions
4885 /// to it are in doubt, and re-reading durable state is how they are
4886 /// discarded.
4887 fn reset_cell(&mut self, id: &str, epoch: Epoch, effects: &mut Vec<Effect>) {
4888 if !matches!(
4889 self.cells.get(id).map(|cell| &cell.phase),
4890 Some(Phase::Resident { epoch: current }) if *current == epoch
4891 ) {
4892 return;
4893 }
4894 // Every other write still on the gate for this cell loses its runtime
4895 // here, so none of them may be acknowledged either.
4896 let doomed: Vec<OpId> = self
4897 .barriers
4898 .iter()
4899 .filter(|(_, barrier)| barrier.cell == id && barrier.epoch == epoch)
4900 .map(|(op, _)| *op)
4901 .collect();
4902 for op in doomed {
4903 let Some(gate) = self.barriers.remove(&op) else {
4904 continue;
4905 };
4906 match gate.owner {
4907 GateOwner::Output(held) => {
4908 self.gate_pinned.remove(&held.request);
4909 effects.push(Effect::Release {
4910 request: held.request,
4911 channel: held.channel,
4912 result: Err(RequestError::DurabilityUnproven),
4913 });
4914 }
4915 // This proof can no longer succeed against a runtime being
4916 // discarded, so the alarm settles as a failed handler's does:
4917 // re-armed, with the wake entry left in place for the next
4918 // activation to find.
4919 GateOwner::Alarm { alarm, .. } => {
4920 let (now_ms, now_mono_ms) = (self.now_ms, self.now_mono_ms);
4921 self.alarm_finished(
4922 alarm,
4923 (gate.cell.clone(), gate.epoch),
4924 now_ms,
4925 now_mono_ms,
4926 Err(Failure::Ambiguous),
4927 effects,
4928 );
4929 }
4930 }
4931 for held in gate.followers {
4932 effects.push(Effect::Release {
4933 request: held.request,
4934 channel: held.channel,
4935 result: Err(RequestError::DurabilityUnproven),
4936 });
4937 }
4938 }
4939 // Requests already running against this runtime lose it here, exactly
4940 // as a fence does. Leaving them in `active_requests` would leave the
4941 // core believing a stopped cell is still serving, which its own
4942 // invariant catches.
4943 let running: Vec<RequestId> = self
4944 .active_requests
4945 .iter()
4946 .filter(|(_, cell)| cell.as_str() == id)
4947 .map(|(request, _)| *request)
4948 .collect();
4949 for request in running {
4950 self.deactivate_request(request);
4951 self.gate_pinned.remove(&request);
4952 }
4953 let op = self.cell_op(id);
4954 if let Some(cell) = self.cells.get_mut(id) {
4955 // The phase being replaced may hold an op that will now never
4956 // complete against it; its index entry must not outlive it.
4957 if let Some(stale) = phase_op(&cell.phase) {
4958 self.cell_ops.remove(&stale);
4959 }
4960 set_phase(
4961 &mut self.occupied,
4962 cell,
4963 Phase::Cleaning {
4964 op,
4965 epoch,
4966 cause: StopCause::Reset,
4967 },
4968 );
4969 }
4970 effects.push(Effect::StopRuntime {
4971 op,
4972 cell: id.to_string(),
4973 epoch,
4974 cause: StopCause::Reset,
4975 });
4976 }
4977
4978 /// How many cells are currently held resident by a non-hibernatable
4979 /// transport.
4980 fn outbound_pinned(&self) -> usize {
4981 self.cells
4982 .values()
4983 .filter(|cell| {
4984 cell.websockets
4985 .values()
4986 .any(|kind| *kind == WebSocketKind::Outbound)
4987 })
4988 .count()
4989 }
4990
4991 fn websocket_opened(
4992 &mut self,
4993 id: &str,
4994 websocket: WebSocketId,
4995 kind: WebSocketKind,
4996 effects: &mut Vec<Effect>,
4997 ) {
4998 if self.fenced {
4999 return;
5000 }
5001 // A non-hibernatable transport holds its cell resident for as long as
5002 // it is open, so every one of them is a cell the node can never shed.
5003 // Pin the whole ceiling and there is nothing left to nominate:
5004 // residency cannot fall, admission waits on capacity that will never
5005 // be freed, and the node is wedged by its own applications. Cells that
5006 // already hold one are not counted again -- the budget is on how much
5007 // of the node is held, not on how many sockets exist.
5008 let already_pinned = self.cells.get(id).is_some_and(|cell| {
5009 cell.websockets
5010 .values()
5011 .any(|kind| *kind == WebSocketKind::Outbound)
5012 });
5013 let cell_outbound = self.cells.get(id).map_or(0, |cell| {
5014 cell.websockets
5015 .values()
5016 .filter(|kind| **kind == WebSocketKind::Outbound)
5017 .count()
5018 });
5019 if kind == WebSocketKind::Outbound
5020 && (cell_outbound >= self.config.max_outbound_websockets
5021 || (!already_pinned
5022 && !pressure::may_pin_outbound(
5023 self.outbound_pinned(),
5024 Some(self.config.max_resident),
5025 )))
5026 {
5027 effects.push(Effect::CloseWebSocket {
5028 cell: id.to_string(),
5029 websocket,
5030 });
5031 return;
5032 }
5033 let Some(cell) = self.cells.get_mut(id) else {
5034 return;
5035 };
5036 cell.websockets.insert(websocket, kind);
5037 }
5038
5039 fn websocket_closed(&mut self, id: &str, websocket: WebSocketId, effects: &mut Vec<Effect>) {
5040 if let Some(cell) = self.cells.get_mut(id) {
5041 cell.websockets.remove(&websocket);
5042 }
5043 self.shed_one(effects);
5044 }
5045
5046 fn invalidate_remote(&mut self, id: &str, node: &str, epoch: Epoch) {
5047 self.node_lease_cache.remove(node);
5048 let rejected_sample = self.cells.get(id).and_then(|cell| match &cell.phase {
5049 Phase::Remote {
5050 node: current,
5051 epoch: current_epoch,
5052 capacity_sampled_ms,
5053 ..
5054 } if current == node && *current_epoch == epoch => *capacity_sampled_ms,
5055 _ => None,
5056 });
5057 if let Some(sample) = rejected_sample {
5058 self.capacity_rejections.insert(node.to_string(), sample);
5059 self.capacity_reservations.remove(node);
5060 }
5061 let Some(cell) = self.cells.get_mut(id) else {
5062 return;
5063 };
5064 if matches!(
5065 &cell.phase,
5066 Phase::Remote {
5067 node: current,
5068 epoch: current_epoch,
5069 ..
5070 } if current == node && *current_epoch == epoch
5071 ) {
5072 set_phase(&mut self.occupied, cell, Phase::Inactive);
5073 }
5074 }
5075
5076 fn fence(&mut self, effects: &mut Vec<Effect>) {
5077 if self.fenced {
5078 return;
5079 }
5080 self.fenced = true;
5081 self.activation_waiters.clear();
5082 self.activation_permits.clear();
5083 self.capacity_waiters.clear();
5084 self.active_requests.clear();
5085 self.active_cells.clear();
5086 // Any write still waiting on the output gate loses its cell here, so it
5087 // must fail rather than be acknowledged — the fence and the fail are
5088 // atomic. A late DurableReached for a drained op is ignored.
5089 self.gate_pinned.clear();
5090 for (_, gate) in std::mem::take(&mut self.barriers) {
5091 // An alarm has no output to fail, and unlike `reset_cell` it is not
5092 // replayed either. The per-cell teardown below retires its firing
5093 // op and clears the alarm, and the wake entry is left where it is,
5094 // so the node that takes the cell next discovers it and fires
5095 // again.
5096 if let GateOwner::Output(held) = gate.owner {
5097 effects.push(Effect::Release {
5098 request: held.request,
5099 channel: held.channel,
5100 result: Err(RequestError::NodeFenced),
5101 });
5102 }
5103 for held in gate.followers {
5104 effects.push(Effect::Release {
5105 request: held.request,
5106 channel: held.channel,
5107 result: Err(RequestError::NodeFenced),
5108 });
5109 }
5110 }
5111 let ids: Vec<CellId> = self.cells.keys().cloned().collect();
5112 for id in ids {
5113 let mut cell = self.cells.remove(&id).expect("id came from map");
5114 match &cell.phase {
5115 Phase::Starting { op, epoch } | Phase::Publishing { op, epoch } => {
5116 self.timed_out_runtime_starts.remove(op);
5117 self.retired_runtime_ops.insert(*op, (id.clone(), *epoch));
5118 }
5119 _ => {}
5120 }
5121 if let Some(epoch) = runtime_epoch(&cell.phase) {
5122 let op = self.op();
5123 effects.push(Effect::StopRuntime {
5124 op,
5125 cell: id.clone(),
5126 epoch,
5127 cause: StopCause::Fence,
5128 });
5129 }
5130 self.finish_requests(&id, &mut cell, Err(RequestError::NodeFenced), effects);
5131 // The phase and alarm die here without completing; their ops can
5132 // never match a lookup again. The release op survives on purpose:
5133 // `owner_released` still consumes it after a fence, as it did
5134 // when resolution was a scan.
5135 if let Some(stale) = phase_op(&cell.phase) {
5136 self.cell_ops.remove(&stale);
5137 }
5138 if let Some(AlarmState::Firing { op, .. }) = cell.alarm {
5139 self.cell_ops.remove(&op);
5140 }
5141 set_phase(&mut self.occupied, &mut cell, Phase::Fenced);
5142 cell.waiting_for = None;
5143 cell.waiting_activation = None;
5144 cell.alarm = None;
5145 cell.alarm_wake = false;
5146 cell.websockets.clear();
5147 self.cells.insert(id, cell);
5148 }
5149 }
5150
5151 fn compensate_retired_runtime(
5152 &mut self,
5153 op: OpId,
5154 result: Result<(), Failure>,
5155 effects: &mut Vec<Effect>,
5156 ) {
5157 let Some((cell, epoch)) = self.retired_runtime_ops.remove(&op) else {
5158 return;
5159 };
5160 // Definite failure created nothing. Success or ambiguity may have
5161 // created/published a runtime after authority was revoked, so cleanup
5162 // is mandatory and idempotent.
5163 if result != Err(Failure::Definite) {
5164 let cleanup = self.op();
5165 effects.push(Effect::StopRuntime {
5166 op: cleanup,
5167 cell,
5168 epoch,
5169 // This completion lost node authority before it became
5170 // visible. It can close the database, but it cannot run the
5171 // durability pass that an ordinary live cleanup uses to make
5172 // the image a successor-epoch base.
5173 cause: StopCause::Fence,
5174 });
5175 }
5176 }
5177}
5178
5179/// The sole state transition entry point.
5180/// The monotonic instant an event carries, if it carries one. Events without
5181/// a timestamp leave the remembered instant alone rather than resetting it.
5182/// The wall-clock reading an event carried, if it carried one.
5183fn event_now_ms(event: &Event) -> Option<u64> {
5184 match event {
5185 Event::StartNodeLease { now_ms, .. }
5186 | Event::SelfNodeLeaseRead { now_ms, .. }
5187 | Event::OwnerRead { now_ms, .. }
5188 | Event::NodeLeaseRead { now_ms, .. }
5189 | Event::TimerFired { now_ms, .. }
5190 | Event::AlarmObserved { now_ms, .. }
5191 | Event::AlarmFinished { now_ms, .. } => Some(*now_ms),
5192 _ => None,
5193 }
5194}
5195
5196fn event_mono_ms(event: &Event) -> Option<u64> {
5197 match event {
5198 Event::StartNodeLease { now_mono_ms, .. }
5199 | Event::SelfNodeLeaseRead { now_mono_ms, .. }
5200 | Event::NodeLeaseCasCompleted { now_mono_ms, .. }
5201 | Event::RequestAt { now_mono_ms, .. }
5202 | Event::CapacityRequestAt { now_mono_ms, .. }
5203 | Event::HandoffRequestAt { now_mono_ms, .. }
5204 | Event::WebSocketRequestAt { now_mono_ms, .. }
5205 | Event::WakeHintAt { now_mono_ms, .. }
5206 | Event::TimerFired { now_mono_ms, .. }
5207 | Event::AlarmObserved { now_mono_ms, .. }
5208 | Event::AlarmFinished { now_mono_ms, .. }
5209 | Event::LoadSampled { now_mono_ms, .. }
5210 | Event::GenerationChanged { now_mono_ms, .. } => Some(*now_mono_ms),
5211 _ => None,
5212 }
5213}
5214
5215pub fn on_event(state: &mut State, event: Event) -> Vec<Effect> {
5216 let mut effects = Vec::new();
5217 if let Some(now_mono_ms) = event_mono_ms(&event) {
5218 state.now_mono_ms = state.now_mono_ms.max(now_mono_ms);
5219 }
5220 if let Some(now_ms) = event_now_ms(&event) {
5221 state.now_ms = state.now_ms.max(now_ms);
5222 }
5223 match event {
5224 Event::StartNodeLease { now_ms, spec, .. } => {
5225 state.start_node_lease(now_ms, spec, &mut effects)
5226 }
5227 Event::NodeLogRecovered { op, result } => {
5228 state.node_log_recovered(op, result, &mut effects)
5229 }
5230 Event::NudgeNodeLease {
5231 now_ms,
5232 now_mono_ms,
5233 } => match &state.node_authority {
5234 NodeAuthority::Held(held) => {
5235 let generation = held.timer_generation;
5236 state.timer_fired(
5237 Timer::NodeLeaseRenew { generation },
5238 now_ms,
5239 now_mono_ms,
5240 &mut effects,
5241 );
5242 }
5243 // A write is in flight (or a read preceding one): its body was
5244 // serialized before this nudge's publish, so it cannot confirm
5245 // it. Remember, and hold_node_lease renews again on arrival.
5246 NodeAuthority::Writing { .. } | NodeAuthority::Reading { .. } => {
5247 state.nudge_pending = true;
5248 }
5249 _ => {}
5250 },
5251 Event::SelfNodeLeaseRead {
5252 op,
5253 now_ms,
5254 now_mono_ms,
5255 result,
5256 } => state.read_self_node_lease(op, now_ms, now_mono_ms, result, &mut effects),
5257 Event::NodeLeaseCasCompleted {
5258 op,
5259 now_mono_ms,
5260 result,
5261 stamped_log_state,
5262 } => {
5263 state.node_lease_cas_completed(op, now_mono_ms, result, stamped_log_state, &mut effects)
5264 }
5265 Event::LocalCellsRead { result } => state.local_cells_read(result, &mut effects),
5266 Event::TimerFired {
5267 timer,
5268 now_ms,
5269 now_mono_ms,
5270 } => state.timer_fired(timer, now_ms, now_mono_ms, &mut effects),
5271 Event::Request { request, cell } => {
5272 state.request(request, cell, false, false, &mut effects)
5273 }
5274 Event::RequestAt { request, cell, .. } => {
5275 state.request(request, cell, false, false, &mut effects)
5276 }
5277 Event::CapacityRequestAt { request, cell, .. } => {
5278 state.request(request, cell, true, false, &mut effects)
5279 }
5280 Event::HandoffRequestAt { request, cell, .. } => {
5281 state.request(request, cell, true, true, &mut effects)
5282 }
5283 Event::WebSocketRequestAt {
5284 request,
5285 cell,
5286 websocket,
5287 ..
5288 } => state.websocket_request(request, cell, websocket, &mut effects),
5289 Event::WorkerRequest { request } => state.worker_request(request, &mut effects),
5290 Event::BeginPreserve => state.begin_preserve(&mut effects),
5291 Event::Cancel { request } => state.cancel(request, &mut effects),
5292 Event::ActivityFinished { request } => state.activity_finished(request, &mut effects),
5293 Event::Output {
5294 request,
5295 channel,
5296 position,
5297 } => state.output(request, channel, position, &mut effects),
5298 Event::DurableReached { op, result, source } => {
5299 state.durable_reached(op, result, source, &mut effects)
5300 }
5301 Event::OwnershipVerified { op, result } => {
5302 state.ownership_verified(op, result, &mut effects)
5303 }
5304 Event::WebSocketOpened {
5305 cell,
5306 websocket,
5307 kind,
5308 } => state.websocket_opened(&cell, websocket, kind, &mut effects),
5309 Event::WebSocketClosed { cell, websocket } => {
5310 state.websocket_closed(&cell, websocket, &mut effects)
5311 }
5312 Event::AlarmObserved {
5313 cell,
5314 at_ms,
5315 covered,
5316 now_ms,
5317 now_mono_ms,
5318 } => state.alarm_observed(
5319 &cell,
5320 AlarmObservation {
5321 at_ms,
5322 covered,
5323 firing_settled: false,
5324 },
5325 now_ms,
5326 now_mono_ms,
5327 &mut effects,
5328 ),
5329 Event::AlarmFinished {
5330 op,
5331 cell,
5332 epoch,
5333 now_ms,
5334 now_mono_ms,
5335 result,
5336 } => state.alarm_finished(op, (cell, epoch), now_ms, now_mono_ms, result, &mut effects),
5337 Event::WakeHint { cell } => state.wake_hint(cell, &mut effects),
5338 Event::WakeHintAt { cell, .. } => state.wake_hint(cell, &mut effects),
5339 Event::OwnerRead { op, now_ms, result } => {
5340 state.owner_read(op, now_ms, result, &mut effects)
5341 }
5342 Event::NodeLeaseRead { op, now_ms, result } => {
5343 state.node_lease_read(op, now_ms, result, &mut effects)
5344 }
5345 Event::CapacityPeersRead { op, now_ms, result } => {
5346 state.capacity_peers_read(op, now_ms, result, &mut effects)
5347 }
5348 Event::OwnerCasCompleted { op, result } => {
5349 state.owner_cas_completed(op, result, &mut effects)
5350 }
5351 Event::OwnerReleased { op, result } => state.owner_released(op, result, &mut effects),
5352 Event::SuccessorAdopted { op, result } => state.successor_adopted(op, result, &mut effects),
5353 Event::RestoreCompleted { op, result } => state.restore_completed(op, result, &mut effects),
5354 Event::RuntimeStarted {
5355 op,
5356 isolate,
5357 generation,
5358 result,
5359 } => state.runtime_started(op, isolate, generation, result, &mut effects),
5360 Event::GenerationChanged {
5361 generation,
5362 max_age_ms,
5363 eager_classes,
5364 ..
5365 } => state.generation_changed(generation, max_age_ms, &eager_classes),
5366 Event::Published { op, result } => state.published(op, result, &mut effects),
5367 Event::DurabilityChecked { op, result } => {
5368 state.durability_checked(op, result, &mut effects)
5369 }
5370 Event::RuntimeStopped { op } => state.runtime_stopped(op, &mut effects),
5371 Event::Evict { cell } => state.evict(&cell, &mut effects),
5372 Event::LoadSampled { load, now_mono_ms } => {
5373 state.load_sampled(load, now_mono_ms, &mut effects)
5374 }
5375 Event::InvalidateRemote { cell, node, epoch } => {
5376 state.invalidate_remote(&cell, &node, epoch)
5377 }
5378 Event::NodeFenced => state.fence_node(&mut effects),
5379 Event::ReleaseAll => state.release_all(&mut effects),
5380 }
5381 state.pump_activations(&mut effects);
5382 state.pump_release(&mut effects);
5383 state.pump_swap(&mut effects);
5384 if cfg!(debug_assertions) {
5385 state.validate().expect("state invariant");
5386 }
5387 state.arm_operation_deadlines(&mut effects);
5388 effects
5389}
5390
5391fn same_node_lease(left: &NodeLeaseRecord, right: &NodeLeaseRecord) -> bool {
5392 left.node == right.node
5393 && left.addr == right.addr
5394 && left.expires_ms == right.expires_ms
5395 && left.peer_protocol == right.peer_protocol
5396 && left.generation == right.generation
5397 // The folded log state distinguishes "our record, untouched" from
5398 // "our record, fenced to recovering by a peer":
5399 // ignoring it let an ambiguous renewal's readback adopt recovery's
5400 // etag and the NEXT renewal un-fenced the recovery. Any difference
5401 // here is authority loss.
5402 && left.log_state == right.log_state
5403}
5404
5405fn phase_occupies_capacity(phase: &Phase) -> bool {
5406 matches!(
5407 phase,
5408 Phase::Acquiring { .. }
5409 | Phase::ReconcilingAcquire { .. }
5410 | Phase::Restoring { .. }
5411 | Phase::Starting { .. }
5412 | Phase::Publishing { .. }
5413 | Phase::EnsuringDurability { .. }
5414 | Phase::Cleaning { .. }
5415 | Phase::Resident { .. }
5416 )
5417}
5418
5419fn phase_holds_activation(phase: &Phase) -> bool {
5420 matches!(
5421 phase,
5422 Phase::ReadingOwner { .. }
5423 | Phase::ReadingNodeLease { .. }
5424 | Phase::RecoveringOwnerLog { .. }
5425 | Phase::ReadingCapacity { .. }
5426 | Phase::WaitingCapacity
5427 | Phase::Acquiring { .. }
5428 | Phase::ReconcilingAcquire { .. }
5429 | Phase::Restoring { .. }
5430 | Phase::Starting { .. }
5431 | Phase::Publishing { .. }
5432 | Phase::Cleaning { .. }
5433 )
5434}
5435
5436/// Identify phases that cannot exist outside one admitted cold route.
5437///
5438/// `Starting` and `Publishing` also serve a live generation swap, so the swap
5439/// flag disambiguates them. `Cleaning` has cold and resident entry points and
5440/// is therefore not a safe converse even though it retains an existing permit.
5441fn phase_requires_activation_permit(phase: &Phase, swapping: bool) -> bool {
5442 matches!(
5443 phase,
5444 Phase::ReadingOwner { .. }
5445 | Phase::ReadingNodeLease { .. }
5446 | Phase::RecoveringOwnerLog { .. }
5447 | Phase::ReadingCapacity { .. }
5448 | Phase::WaitingCapacity
5449 | Phase::Acquiring { .. }
5450 | Phase::ReconcilingAcquire { .. }
5451 | Phase::Restoring { .. }
5452 ) || (!swapping && matches!(phase, Phase::Starting { .. } | Phase::Publishing { .. }))
5453}
5454
5455/// The one gate every phase change passes through: it keeps `occupied`
5456/// equal to the number of cells in a capacity-occupying phase, so nothing
5457/// ever has to count them. `validate` asserts the equality by walking.
5458fn set_phase(occupied: &mut usize, cell: &mut Cell, phase: Phase) {
5459 if !matches!(&phase, Phase::Resident { .. }) {
5460 cell.quiescing = false;
5461 }
5462 // A swap lives on exactly these phases. Any other change — an eviction
5463 // that won the race, a fence, a failed start — ends it, and the cell
5464 // picks the current generation on its next activation instead.
5465 if !matches!(
5466 &phase,
5467 Phase::Resident { .. }
5468 | Phase::Cleaning {
5469 cause: StopCause::Swap,
5470 ..
5471 }
5472 | Phase::Starting { .. }
5473 | Phase::Publishing { .. }
5474 ) {
5475 cell.swapping = false;
5476 cell.swap_cancelled = false;
5477 }
5478 match (
5479 phase_occupies_capacity(&cell.phase),
5480 phase_occupies_capacity(&phase),
5481 ) {
5482 (false, true) => *occupied += 1,
5483 (true, false) => *occupied -= 1,
5484 _ => {}
5485 }
5486 cell.phase = phase;
5487}
5488
5489/// The in-flight operation a phase is waiting on, if it is waiting on one.
5490fn phase_op(phase: &Phase) -> Option<OpId> {
5491 match phase {
5492 Phase::ReadingOwner { op }
5493 | Phase::ReadingNodeLease { op, .. }
5494 | Phase::ReadingCapacity { op, .. }
5495 | Phase::Acquiring { op, .. }
5496 | Phase::ReconcilingAcquire { op, .. }
5497 | Phase::Restoring { op, .. }
5498 | Phase::Starting { op, .. }
5499 | Phase::Publishing { op, .. }
5500 | Phase::EnsuringDurability { op, .. }
5501 | Phase::Cleaning { op, .. }
5502 | Phase::Adopting { op, .. } => Some(*op),
5503 _ => None,
5504 }
5505}
5506
5507fn runtime_epoch(phase: &Phase) -> Option<Epoch> {
5508 match phase {
5509 Phase::Publishing { epoch, .. }
5510 | Phase::EnsuringDurability { epoch, .. }
5511 | Phase::Cleaning { epoch, .. }
5512 | Phase::Resident { epoch } => Some(*epoch),
5513 _ => None,
5514 }
5515}