Diffinery

homeflare/celldpublic

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