Diffinery

homeflare/celldpublic

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