Diffinery

homeflare/celldpublic

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