Diffinery

homeflare/celldpublic

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