Diffinery

homeflare/celldpublic

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