Diffinery

homeflare/celldpublic

4386 lines · 172.3 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 dead_node_reconciliation;
15pub mod gate;
16pub mod isolate;
17pub mod peer;
18pub mod pressure;
19pub mod restore;
20pub mod routing;
21pub mod schedule;
22pub mod sqlite;
23pub mod wake;
24
25mod types;
26pub use types::*;
27
28#[derive(Clone, Debug, PartialEq, Eq)]
29enum Activation {
30 Claim(Claim),
31 Restore(RestoreSpec),
32}
33
34#[derive(Clone, Debug, PartialEq, Eq)]
35enum ColdStart {
36 ReadOwner,
37 Restore(RestoreSpec),
38}
39
40/// Facts already decided by ownership resolution that select a safe restore
41/// source. The effect adapter must not rediscover or guess these.
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub struct RestoreSpec {
44 pub epoch: Epoch,
45 /// This activation conditionally created epoch one, so no replica can
46 /// precede it.
47 pub fresh: bool,
48 /// Ownership was seized from a different node (or a released record), so
49 /// a previous local eviction cache is not authoritative.
50 pub took_over: bool,
51 /// The node-level lease handoff proved that this exact local epoch remains
52 /// authoritative. The adapter must not consult the remote replica.
53 pub resume_local: bool,
54}
55
56#[derive(Clone, Debug, PartialEq, Eq)]
57pub struct Claim {
58 pub guard: CasGuard,
59 pub epoch: Epoch,
60 pub takeover: bool,
61 /// Ambiguous acquires already reconciled for this claim.
62 ///
63 /// An ambiguous compare-and-swap is re-read rather than retried blindly,
64 /// which is correct — it may have applied. But the re-read leads to
65 /// another acquire, and if that is ambiguous too the cycle repeats. With
66 /// no bound a persistently unanswered store turns a request that used to
67 /// hang into one that spins, which is worse: it burns a slot and an
68 /// object-store budget forever instead of merely waiting.
69 pub reconciles: u32,
70}
71
72/// How many times one claim may reconcile an ambiguous acquire before the
73/// request is failed and the caller left to decide. Small: each pass is a full
74/// read plus a write, and a store answering ambiguously three times running is
75/// not about to start answering.
76pub const MAX_ACQUIRE_RECONCILES: u32 = 3;
77
78/// Phases map onto the Durable Objects lifecycle states where Cloudflare has
79/// a name for them:
80///
81/// - `Resident` is active or idle in memory (states 1-3).
82/// - `Dormant` is out of memory but still owned by this node, so the cell has
83/// not been moved off its host. A dormant cell with surviving hibernatable
84/// sockets is *hibernated* (state 4); see [`Core::is_hibernated`].
85/// - `Inactive` is out of memory and owned by nobody: removed from the host,
86/// needing a cold start (state 5, and the initial state of every cell).
87///
88/// Note that celld and Cloudflare use "evict" differently. Cloudflare evicts a
89/// cell *off its host*, which produces `Inactive`. celld evicts a cell *out of
90/// memory*, which produces `Dormant`, and shedding is what then publishes it
91/// unowned.
92#[derive(Clone, Debug, PartialEq, Eq)]
93pub enum Phase {
94 Inactive,
95 /// Cold demand queued behind `max_activations`, before any I/O begins.
96 WaitingActivation,
97 ReadingOwner {
98 op: OpId,
99 },
100 ReadingNodeLease {
101 op: OpId,
102 owner: OwnerRecord,
103 },
104 ReadingCapacity {
105 op: OpId,
106 claim: Claim,
107 },
108 WaitingCapacity,
109 Acquiring {
110 op: OpId,
111 claim: Claim,
112 },
113 ReconcilingAcquire {
114 op: OpId,
115 claim: Claim,
116 },
117 Restoring {
118 op: OpId,
119 spec: RestoreSpec,
120 },
121 Starting {
122 op: OpId,
123 epoch: Epoch,
124 },
125 Publishing {
126 op: OpId,
127 epoch: Epoch,
128 },
129 /// The runtime remains published and routable while replica durability is
130 /// being proved. A failed or ambiguous proof returns to `Resident`.
131 EnsuringDurability {
132 op: OpId,
133 epoch: Epoch,
134 },
135 Cleaning {
136 op: OpId,
137 epoch: Epoch,
138 cause: StopCause,
139 },
140 /// Out of memory, still owned here. Hibernated when sockets survived.
141 Dormant {
142 epoch: Epoch,
143 },
144 Resident {
145 epoch: Epoch,
146 },
147 Remote {
148 node: NodeId,
149 addr: String,
150 epoch: Epoch,
151 peer_protocol: u16,
152 /// Present only for epoch-zero capacity candidates. It identifies the
153 /// exact advisory sample a refusal disproved.
154 capacity_sampled_ms: Option<u64>,
155 },
156 Fenced,
157}
158
159/// The reported name of a phase. Stable across internal renames, because
160/// `/state` and `celld diagnose` publish it.
161fn phase_name(phase: &Phase) -> &'static str {
162 match phase {
163 Phase::Inactive => "inactive",
164 Phase::WaitingActivation => "waiting_activation",
165 Phase::ReadingOwner { .. } => "reading_owner",
166 Phase::ReadingNodeLease { .. } => "reading_node_lease",
167 Phase::ReadingCapacity { .. } => "reading_capacity",
168 Phase::WaitingCapacity => "waiting_capacity",
169 Phase::Acquiring { .. } => "acquiring",
170 Phase::ReconcilingAcquire { .. } => "reconciling_acquire",
171 Phase::Restoring { .. } => "restoring",
172 Phase::Starting { .. } => "starting",
173 Phase::Publishing { .. } => "publishing",
174 Phase::EnsuringDurability { .. } => "ensuring_durability",
175 Phase::Cleaning { .. } => "cleaning",
176 Phase::Dormant { .. } => "dormant",
177 Phase::Resident { .. } => "resident",
178 Phase::Remote { .. } => "remote",
179 Phase::Fenced => "fenced",
180 }
181}
182
183/// One local write response held open by the output gate.
184#[derive(Clone, Debug, PartialEq, Eq)]
185struct GatedWrite {
186 request: RequestId,
187 cell: CellId,
188 epoch: Epoch,
189 position: u64,
190}
191
192#[derive(Clone, Debug)]
193struct Cell {
194 phase: Phase,
195 requests: BTreeSet<RequestId>,
196 websockets: BTreeMap<WebSocketId, WebSocketKind>,
197 waiting_for: Option<Activation>,
198 waiting_activation: Option<ColdStart>,
199 /// The in-flight release of this cell's ownership record, if any.
200 releasing: Option<OpId>,
201 /// Whether the eviction now under way hands this cell to the fleet.
202 evict_rebalance: bool,
203 alarm: Option<AlarmState>,
204 alarm_wake: bool,
205 /// Startup, rather than a request or alarm, demands this activation.
206 resume_demand: bool,
207 /// When this cell's eviction was last refused, if it has been.
208 ///
209 /// A cell that cannot prove its replica durable goes back to residency,
210 /// and being cold is exactly why nobody registered it -- so it settles at
211 /// the head of the eviction order and is chosen again on the next pass,
212 /// and the one after. Enough of those and the node has no shed candidate
213 /// it will ever succeed with. Recording the refusal lets the order prefer
214 /// cells that have not just failed, while still coming back to them when
215 /// they are all that is left.
216 eviction_refused_mono_ms: Option<u64>,
217 /// When this cell last did something, on the remembered monotonic clock.
218 ///
219 /// Eviction order is the whole reason this exists. Without it the shed
220 /// candidate is whichever cell sorts first by id, so a node under
221 /// sustained pressure evicts its alphabetically-first cell over and over
222 /// -- restoring and shedding the busiest cell on the node while an idle
223 /// one further down the alphabet is never touched.
224 last_used_mono_ms: u64,
225}
226
227#[derive(Clone, Debug, PartialEq, Eq)]
228enum AlarmState {
229 Armed {
230 at_ms: i64,
231 generation: u64,
232 covered: bool,
233 },
234 Firing {
235 op: OpId,
236 at_ms: i64,
237 generation: u64,
238 covered: bool,
239 },
240}
241
242#[derive(Clone, Debug)]
243struct HeldNodeLease {
244 spec: NodeLeaseSpec,
245 record: NodeLeaseRecord,
246 last_ok_mono_ms: u64,
247 last_attempt_mono_ms: u64,
248 timer_generation: u64,
249 idle_since_mono_ms: Option<u64>,
250 shadow_release_reported: bool,
251}
252
253#[derive(Clone, Debug)]
254struct PendingNodeLease {
255 spec: NodeLeaseSpec,
256 desired: NodeLeaseRecord,
257 prior: Option<HeldNodeLease>,
258 /// This read follows a write whose result was ambiguous. It may prove the
259 /// desired record landed, but must not turn a failed create into an
260 /// unbounded read/write loop.
261 readback_only: bool,
262 /// The monotonic instant `desired.expires_ms` was computed from.
263 ///
264 /// Authority is bounded by what the *bucket* says, and the bucket says
265 /// `expires_ms`, which is sampled here rather than when the write lands.
266 /// Anchoring the local fence deadline to the write's completion instead
267 /// would let this node serve for the whole duration of the round trip
268 /// after every peer is entitled to declare it dead -- the store is under
269 /// no obligation to answer quickly, so that window is unbounded.
270 anchor_mono_ms: u64,
271 /// This initial CAS replaces the exact live generation certified by the
272 /// clean local shutdown. Renewals never set this bit.
273 resume_local: bool,
274}
275
276#[derive(Clone, Debug)]
277enum NodeAuthority {
278 Unstarted,
279 /// Lazy lifecycle with no live lease. The spec is retained so the next
280 /// local dependency can acquire before touching cell ownership. Named
281 /// `Lapsed`, not `Inactive`: `inactive` is a cell state (state 5, gone
282 /// from this host) and must mean only that.
283 Lapsed(NodeLeaseSpec),
284 Reading {
285 op: OpId,
286 pending: PendingNodeLease,
287 },
288 Writing {
289 op: OpId,
290 pending: PendingNodeLease,
291 },
292 Held(HeldNodeLease),
293 /// A continuous node whose initial acquisition did not succeed, waiting to
294 /// try again.
295 ///
296 /// `StartNodeLease` is emitted exactly once, at process start, so without
297 /// this the first failed acquisition is permanent: the process stays up,
298 /// holds no authority, and answers every request `NodeUnavailable` for as
299 /// long as it runs. One slow or rate-limited bucket response at startup
300 /// should not cost a node its whole lifetime. A lazy node already
301 /// recovers, because its next request re-acquires from `Lapsed`.
302 Retrying {
303 spec: NodeLeaseSpec,
304 generation: u64,
305 },
306 Failed,
307 Fenced,
308}
309
310impl Default for Cell {
311 fn default() -> Self {
312 Self {
313 phase: Phase::Inactive,
314 requests: BTreeSet::new(),
315 websockets: BTreeMap::new(),
316 waiting_for: None,
317 waiting_activation: None,
318 releasing: None,
319 evict_rebalance: false,
320 alarm: None,
321 alarm_wake: false,
322 resume_demand: false,
323 eviction_refused_mono_ms: None,
324 last_used_mono_ms: 0,
325 }
326 }
327}
328
329/// All authoritative coordination state for the first vertical slice.
330pub struct State {
331 node: NodeId,
332 config: Config,
333 fenced: bool,
334 /// A shutdown handoff is under way: every resident cell is to be
335 /// released, pumped at most `max_releases` at a time. Sticky -- a
336 /// draining node never goes back to serving.
337 draining: bool,
338 /// An exact clean predecessor was replaced and its local inventory is
339 /// being scanned or materialized. Readiness remains false until every
340 /// discovered cell either publishes or fails closed.
341 resuming: bool,
342 resuming_cells: BTreeSet<CellId>,
343 next_op: OpId,
344 next_timer_generation: u64,
345 cells: BTreeMap<CellId, Cell>,
346 request_cells: BTreeMap<RequestId, CellId>,
347 /// Local routes handed to the executor but not yet reported complete.
348 /// These are eviction pins: the adapter may still be running user code.
349 active_requests: BTreeMap<RequestId, CellId>,
350 /// Reverse index of `active_requests`: how many active requests target
351 /// each cell. `is_active` reads it in O(1) where scanning the values was
352 /// O(active_requests), and `worker_request` calls `is_active` once per
353 /// resident cell — the product wedged cold-cell activation, the rate
354 /// falling with the cell count (engine/pathological-load.md).
355 active_cells: BTreeMap<CellId, usize>,
356 /// Local write responses withheld by the output gate until their cell is
357 /// proven durable to the written position, keyed by the durability op. An
358 /// open gate makes its cell active, so the cell cannot be evicted
359 /// underneath it; a fence drains these to a failed response so a write is
360 /// never acknowledged after the node loses authority.
361 gated_writes: BTreeMap<OpId, GatedWrite>,
362 /// Requests whose activity ended while a write of theirs was still on the
363 /// output gate. The pin outlives the activity: it keeps the cell from being
364 /// evicted under the gate, and keeps a later write of the same request able
365 /// to open one. See `activity_finished`.
366 gate_pinned: BTreeSet<RequestId>,
367 /// Last resident selected for top-level Worker execution. Cell IDs are
368 /// ordered, so this is enough to replay a fair round-robin without shell
369 /// atomics or registry iteration order leaking into behavior.
370 worker_cursor: Option<CellId>,
371 activity: ActivitySnapshot,
372 activation_waiters: VecDeque<CellId>,
373 /// Cells holding a complete cold-route admission. Keeping this explicit,
374 /// instead of inferring it from executor tasks, makes the concurrency bound
375 /// part of the replayable state machine.
376 activation_permits: BTreeSet<CellId>,
377 /// Cells with an eviction in flight -- from the durability proof through
378 /// the runtime stop. Explicit for the same reason as the activation
379 /// permits: the bound belongs in the replayable state machine rather than
380 /// being implied by how many executor tasks happen to exist.
381 eviction_permits: BTreeSet<CellId>,
382 /// Cells waiting for a residency slot, in arrival order. FIFO is the
383 /// whole admission policy: waking every waiter on a release and letting
384 /// them race is unfair by construction — under sustained eviction a
385 /// waiter can time out while thousands of slots are freed around it.
386 /// The queue converts "eventually, probably" into a bound: a waiter with
387 /// `k` waiters ahead of it is admitted within `k` releases, so no
388 /// arrival pattern can starve it.
389 capacity_waiters: VecDeque<CellId>,
390 /// Requests received as epoch-zero capacity handoffs. Keeping the mode on
391 /// the request rather than in the HTTP adapter makes the admit/refuse race
392 /// atomic with every other lifecycle transition.
393 capacity_requests: BTreeSet<RequestId>,
394 /// Reservations made against each unchanged advisory sample. Concurrent
395 /// lookups are applied one event at a time, so projected load cannot pick
396 /// the same advertised final slot twice by accident.
397 capacity_reservations: BTreeMap<NodeId, usize>,
398 capacity_samples: BTreeMap<NodeId, u64>,
399 /// A refusal disproves exactly one load sample. The node becomes eligible
400 /// again only after its lease advertises a newer sample.
401 capacity_rejections: BTreeMap<NodeId, u64>,
402 /// Live routing authority is shared by every cell owned by the same node.
403 /// Keeping that cache here makes expiry and invalidation deterministic,
404 /// rather than an invisible executor optimization.
405 node_lease_cache: BTreeMap<NodeId, NodeLeaseRecord>,
406 /// Start/publish effects invalidated by fencing may still commit. Their
407 /// late completion must trigger compensating cleanup, not be ignored.
408 retired_runtime_ops: BTreeMap<OpId, (CellId, Epoch)>,
409 /// The cell each in-flight cell-scoped operation belongs to. Completion
410 /// events name only the op; this index is what makes resolving one a
411 /// lookup instead of a walk of every cell.
412 cell_ops: BTreeMap<OpId, CellId>,
413 /// How many cells currently occupy capacity, maintained at every phase
414 /// transition. `has_capacity` asks on every admission and `validate` on
415 /// every debug event; counting by walking the map priced both by the
416 /// total cell count rather than the answer.
417 occupied: usize,
418 node_authority: NodeAuthority,
419 /// Requests admitted while a lazy node is inactive. They are not entered
420 /// into per-cell routing state until the node lease is authoritative, so
421 /// a failed lease acquisition cannot create cell ownership.
422 node_lease_waiters: BTreeMap<RequestId, CellId>,
423 /// Alarm/wake demand has no request to complete, but it obeys the same
424 /// acquire-before-ownership rule.
425 node_wake_waiters: BTreeSet<CellId>,
426 lazy_lease_shadow: LeaseLifecycleShadowBatch,
427 next_shadow_sequence: u64,
428 /// The most recent wall-clock instant any event carried. Alarms are wall
429 /// clock, so judging whether one is imminent needs this rather than the
430 /// monotonic reading next to it.
431 now_ms: u64,
432 /// The most recent monotonic instant any event carried. Not a clock read:
433 /// the core never asks what time it is, it remembers what it was told, so
434 /// a handler that was not handed a timestamp can still arm a deadline
435 /// relative to the event being processed.
436 now_mono_ms: u64,
437 /// How far down the current sample asked the node to shed.
438 ///
439 /// The walk down runs at eviction speed rather than sample speed: each
440 /// completed eviction starts the next while residency is still above this
441 /// floor. Without one it is a cell per sample, so a node fifteen over its
442 /// watermark refuses work for fifteen sampling periods. Recomputed every
443 /// sample, so a resource trigger comes down by a proportion of what was
444 /// last measured rather than aiming at a cell count that means nothing to
445 /// it.
446 shed_floor: usize,
447 /// The measurement the current shed floor was set from, and its value. A
448 /// later latched sample compares against this: a completed cut that left
449 /// the number flat makes another cut futile.
450 ///
451 /// The measurement travels with the value because the two are not
452 /// comparable. When the latches change, so does the number the walk down
453 /// reads, and comparing a fresh resident set size against a stale in-use
454 /// figure finds them flat by coincidence.
455 shed_cut: Option<(pressure::Metric, u64, usize)>,
456 /// Which ceilings are latched. Held apart from `shed_reason`, which names
457 /// only the more serious crossing.
458 latches: pressure::Latches,
459 /// The shedding latch. celld kept this in the executor, which meant the
460 /// hysteresis -- the part with actual behaviour -- was the one piece the
461 /// simulation could not reach. It is carried here so a sample
462 /// sequence is replayable.
463 shedding: bool,
464 /// Which resource is holding the latch, for the effect the shell logs.
465 shed_reason: Option<&'static str>,
466}
467
468impl State {
469 pub fn new(node: impl Into<NodeId>, config: Config) -> Self {
470 assert!(config.max_evictions > 0, "max_evictions must be positive");
471 assert!(config.max_releases > 0, "max_releases must be positive");
472 assert!(
473 config.max_activations > 0,
474 "max_activations must be positive"
475 );
476 Self {
477 node: node.into(),
478 config,
479 fenced: false,
480 draining: false,
481 resuming: false,
482 resuming_cells: BTreeSet::new(),
483 next_op: 1,
484 next_timer_generation: 1,
485 cells: BTreeMap::new(),
486 request_cells: BTreeMap::new(),
487 active_requests: BTreeMap::new(),
488 active_cells: BTreeMap::new(),
489 gated_writes: BTreeMap::new(),
490 gate_pinned: BTreeSet::new(),
491 worker_cursor: None,
492 activity: ActivitySnapshot::default(),
493 activation_waiters: VecDeque::new(),
494 activation_permits: BTreeSet::new(),
495 eviction_permits: BTreeSet::new(),
496 capacity_waiters: VecDeque::new(),
497 capacity_requests: BTreeSet::new(),
498 capacity_reservations: BTreeMap::new(),
499 capacity_samples: BTreeMap::new(),
500 capacity_rejections: BTreeMap::new(),
501 node_lease_cache: BTreeMap::new(),
502 retired_runtime_ops: BTreeMap::new(),
503 cell_ops: BTreeMap::new(),
504 occupied: 0,
505 node_authority: NodeAuthority::Unstarted,
506 node_lease_waiters: BTreeMap::new(),
507 node_wake_waiters: BTreeSet::new(),
508 lazy_lease_shadow: LeaseLifecycleShadowBatch::default(),
509 next_shadow_sequence: 1,
510 now_ms: 0,
511 now_mono_ms: 0,
512 shed_floor: 0,
513 shed_cut: None,
514 latches: pressure::Latches::default(),
515 shedding: false,
516 shed_reason: None,
517 }
518 }
519
520 pub fn node(&self) -> &str {
521 &self.node
522 }
523
524 pub fn is_fenced(&self) -> bool {
525 self.fenced
526 }
527
528 /// Authority is the lease's published validity evaluated at ask time on
529 /// the monotonic clock — not the `Held` variant. A peer treats the record
530 /// as dead the instant `now_ms` reaches `expires_ms`, so a holder whose
531 /// lease lapsed must answer `false` here even if `Timer::NodeLeaseFence`
532 /// has not fired yet: the timer is the liveness backstop that halts the
533 /// process, never the safety mechanism. A suspended VM's timer fires
534 /// late, but a request evaluated after resume still refuses. The `<` /
535 /// `>=` polarity matches the fence timer at `handle_timer`, so the
536 /// predicate and the timer cannot disagree.
537 pub fn node_authoritative(&self) -> bool {
538 if !self.config.require_node_lease {
539 return !self.fenced;
540 }
541 let fresh = |held: &HeldNodeLease| {
542 self.now_mono_ms.saturating_sub(held.last_ok_mono_ms) < held.spec.ttl_ms
543 };
544 match &self.node_authority {
545 NodeAuthority::Held(held) => fresh(held),
546 NodeAuthority::Reading { pending, .. } | NodeAuthority::Writing { pending, .. } => {
547 pending.prior.as_ref().is_some_and(fresh)
548 }
549 _ => false,
550 }
551 }
552
553 /// Whether the process can accept new traffic. An idle lazy node is ready
554 /// even though it intentionally holds no authority: a DO request first
555 /// acquires the lease, while stateless Worker traffic needs none.
556 pub fn ready_to_serve(&self) -> bool {
557 if self.fenced || self.resuming {
558 return false;
559 }
560 self.node_authoritative()
561 || matches!(
562 &self.node_authority,
563 NodeAuthority::Lapsed(NodeLeaseSpec {
564 mode: NodeLeaseMode::Lazy,
565 ..
566 }) | NodeAuthority::Reading {
567 pending: PendingNodeLease {
568 spec: NodeLeaseSpec {
569 mode: NodeLeaseMode::Lazy,
570 ..
571 },
572 prior: None,
573 ..
574 },
575 ..
576 } | NodeAuthority::Writing {
577 pending: PendingNodeLease {
578 spec: NodeLeaseSpec {
579 mode: NodeLeaseMode::Lazy,
580 ..
581 },
582 prior: None,
583 ..
584 },
585 ..
586 }
587 )
588 }
589
590 pub fn phase(&self, cell: &str) -> Option<&Phase> {
591 self.cells.get(cell).map(|cell| &cell.phase)
592 }
593
594 /// Which resource is currently holding the shedding latch, if any.
595 ///
596 /// A node that is refusing work should be able to say why; without this
597 /// the operator sees only that admissions stopped.
598 pub fn shed_reason(&self) -> Option<&'static str> {
599 self.shed_reason
600 }
601
602 /// Whether this node is currently shedding, for peers ranking it as a
603 /// placement target. A node that says no while walking down invites the
604 /// work it is trying to get rid of.
605 pub fn shedding(&self) -> bool {
606 self.shedding
607 }
608
609 /// Host-side sockets open across every cell. Each one pins its cell
610 /// against eviction, so a node holding many is a poor landing place
611 /// even when its residency looks unremarkable.
612 pub fn host_websockets(&self) -> usize {
613 self.cells.values().map(|cell| cell.websockets.len()).sum()
614 }
615
616 /// Does this cell still hold that socket? False when the core declined
617 /// it, so the shell can answer the opener instead of closing underneath.
618 pub fn holds_websocket(&self, id: &str, websocket: WebSocketId) -> bool {
619 self.cells
620 .get(id)
621 .is_some_and(|cell| cell.websockets.contains_key(&websocket))
622 }
623
624 pub fn occupied(&self) -> usize {
625 self.occupied
626 }
627
628 /// Are fewer than `ceiling` cells occupying capacity?
629 fn occupied_below(&self, ceiling: usize) -> bool {
630 self.occupied < ceiling
631 }
632
633 pub fn residents(&self) -> Vec<CellId> {
634 self.cells
635 .iter()
636 .filter(|(_, cell)| {
637 matches!(
638 cell.phase,
639 Phase::Resident { .. } | Phase::EnsuringDurability { .. }
640 )
641 })
642 .map(|(id, _)| id.clone())
643 .collect()
644 }
645
646 /// Return the exact management projection for the current event boundary.
647 /// Activations are not visible until publication; a runtime being held for
648 /// durability remains visible because it is still published and routable.
649 pub fn presence_snapshot(&self) -> PresenceSnapshot {
650 let cells = self
651 .cells
652 .iter()
653 .filter_map(|(id, cell)| match cell.phase {
654 Phase::Resident { epoch } | Phase::EnsuringDurability { epoch, .. } => {
655 Some(PresenceCell {
656 id: id.clone(),
657 epoch,
658 })
659 }
660 _ => None,
661 })
662 .collect();
663 PresenceSnapshot {
664 serving: self.ready_to_serve(),
665 cells,
666 activity: self.activity,
667 lazy_lease_shadow: self.lazy_lease_shadow.clone(),
668 }
669 }
670
671 pub fn waiting(&self) -> Vec<CellId> {
672 self.capacity_waiters.iter().cloned().collect()
673 }
674
675 pub fn activation_waiting(&self) -> Vec<CellId> {
676 self.activation_waiters.iter().cloned().collect()
677 }
678
679 pub fn activating(&self) -> usize {
680 self.activation_permits.len()
681 }
682
683 /// Evictions in flight, from the durability proof through the runtime
684 /// stop. During a drain this saturates at `max_releases`.
685 pub fn evicting(&self) -> usize {
686 self.eviction_permits.len()
687 }
688
689 /// How many cells sit in each phase, by a stable short name, omitting the
690 /// phases with no cells.
691 ///
692 /// A node that refuses cells is diagnosed by where its cells are, and
693 /// `occupied` cannot say: it counts residency, so a node holding thousands
694 /// of cells part-way through a cold start reports almost none. A fleet held
695 /// that state for fifteen minutes and the record could not say what the
696 /// cells were doing (issue #50).
697 ///
698 /// The names are part of the operator interface. A chart and a human read
699 /// them, so they do not change with an internal rename.
700 pub fn phase_census(&self) -> Vec<(&'static str, usize)> {
701 let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
702 for cell in self.cells.values() {
703 *counts.entry(phase_name(&cell.phase)).or_default() += 1;
704 }
705 counts.into_iter().collect()
706 }
707
708 /// Cold routes that have not finished: cells that hold an activation
709 /// permit plus cells queued behind the activation ceiling. A capacity
710 /// waiter already holds a permit, so this counts every cell once. A
711 /// rollout waits for zero before it removes more warm capacity.
712 pub fn activation_backlog(&self) -> usize {
713 self.activation_permits.len() + self.activation_waiters.len()
714 }
715
716 /// Ownership releases still in flight. The shutdown drain waits for
717 /// zero: a released cell stops occupying capacity before its record
718 /// write commits, so an exit gated on occupancy alone can outrun its
719 /// own releases and leave records a successor must wait out the node
720 /// lease for -- the takeover-at-once promise broken on every real
721 /// store, where the write loses a race against a 50ms drain poll that
722 /// a local fixture always wins.
723 pub fn releasing(&self) -> usize {
724 self.cells
725 .values()
726 .filter(|cell| cell.releasing.is_some())
727 .count()
728 }
729
730 /// Cheap internal consistency gate run by both executors after every event.
731 pub fn validate(&self) -> Result<(), String> {
732 if !self.occupied_below(self.config.max_resident.saturating_add(1)) {
733 return Err(format!(
734 "occupied {} exceeds ceiling {}",
735 self.occupied(),
736 self.config.max_resident
737 ));
738 }
739 let eviction_ceiling = if self.draining {
740 self.config.max_releases.max(self.config.max_evictions)
741 } else {
742 self.config.max_evictions
743 };
744 if self.eviction_permits.len() > eviction_ceiling {
745 return Err(format!(
746 "evicting {} exceeds ceiling {}",
747 self.eviction_permits.len(),
748 eviction_ceiling
749 ));
750 }
751 if self.activation_permits.len() > self.config.max_activations {
752 return Err(format!(
753 "activating {} exceeds ceiling {}",
754 self.activation_permits.len(),
755 self.config.max_activations
756 ));
757 }
758
759 let mut activation_queued = BTreeSet::new();
760 for id in &self.activation_waiters {
761 if !activation_queued.insert(id) {
762 return Err(format!("activation waiter {id:?} is queued twice"));
763 }
764 let Some(cell) = self.cells.get(id) else {
765 return Err(format!("activation waiter {id:?} has no cell state"));
766 };
767 if cell.phase != Phase::WaitingActivation || cell.waiting_activation.is_none() {
768 return Err(format!("activation waiter {id:?} is not waiting"));
769 }
770 if self.activation_permits.contains(id) {
771 return Err(format!("activation waiter {id:?} also holds a permit"));
772 }
773 }
774 for id in &self.activation_permits {
775 let Some(cell) = self.cells.get(id) else {
776 return Err(format!("activation permit {id:?} has no cell state"));
777 };
778 if !phase_holds_activation(&cell.phase) {
779 return Err(format!(
780 "activation permit {id:?} is held in terminal phase {:?}",
781 cell.phase
782 ));
783 }
784 }
785
786 let mut queued = BTreeSet::new();
787 for id in &self.capacity_waiters {
788 if !queued.insert(id) {
789 return Err(format!("capacity waiter {id:?} is queued twice"));
790 }
791 let Some(cell) = self.cells.get(id) else {
792 return Err(format!("capacity waiter {id:?} has no cell state"));
793 };
794 if cell.phase != Phase::WaitingCapacity || cell.waiting_for.is_none() {
795 return Err(format!("capacity waiter {id:?} is not waiting"));
796 }
797 }
798 for (id, cell) in &self.cells {
799 let is_activation_queued = activation_queued.contains(id);
800 if (cell.phase == Phase::WaitingActivation) != is_activation_queued {
801 return Err(format!("cell {id:?} activation queue and phase disagree"));
802 }
803 let is_queued = queued.contains(id);
804 if (cell.phase == Phase::WaitingCapacity) != is_queued {
805 return Err(format!("cell {id:?} queue and phase disagree"));
806 }
807 for request in &cell.requests {
808 if self.request_cells.get(request) != Some(id) {
809 return Err(format!(
810 "request {request} index disagrees with cell {id:?}"
811 ));
812 }
813 }
814 // Every in-flight cell op must be resolvable through the index,
815 // or its completion event will never find this cell.
816 let indexed = |op: OpId| self.cell_ops.get(&op) == Some(id);
817 if let Some(op) = phase_op(&cell.phase) {
818 if !indexed(op) {
819 return Err(format!("cell {id:?} phase op {op} is not indexed"));
820 }
821 }
822 if let Some(AlarmState::Firing { op, .. }) = cell.alarm {
823 if !indexed(op) {
824 return Err(format!("cell {id:?} firing alarm op {op} is not indexed"));
825 }
826 }
827 if let Some(op) = cell.releasing {
828 if !indexed(op) {
829 return Err(format!("cell {id:?} release op {op} is not indexed"));
830 }
831 }
832 }
833 let walked = self
834 .cells
835 .values()
836 .filter(|cell| phase_occupies_capacity(&cell.phase))
837 .count();
838 if walked != self.occupied {
839 return Err(format!(
840 "occupied counter {} disagrees with the walk {walked}",
841 self.occupied
842 ));
843 }
844 for (request, id) in &self.request_cells {
845 if !self
846 .cells
847 .get(id)
848 .is_some_and(|cell| cell.requests.contains(request))
849 {
850 return Err(format!("request index {request} has no matching waiter"));
851 }
852 }
853 for (request, id) in &self.node_lease_waiters {
854 if self.request_cells.contains_key(request)
855 || self.active_requests.contains_key(request)
856 {
857 return Err(format!(
858 "request {request} waits for node authority and is already routed"
859 ));
860 }
861 if id.is_empty() {
862 return Err(format!("request {request} has an empty node-lease target"));
863 }
864 }
865 // The reverse index must agree with the map it summarizes, exactly.
866 let mut recount: BTreeMap<CellId, usize> = BTreeMap::new();
867 for id in self.active_requests.values() {
868 *recount.entry(id.clone()).or_insert(0) += 1;
869 }
870 if recount != self.active_cells {
871 return Err(format!(
872 "active_cells index {:?} disagrees with active_requests {:?}",
873 self.active_cells, recount
874 ));
875 }
876 for (request, id) in &self.active_requests {
877 if self.request_cells.contains_key(request) {
878 return Err(format!("request {request} is both pending and active"));
879 }
880 if !self.cells.get(id).is_some_and(|cell| {
881 matches!(
882 cell.phase,
883 Phase::Resident { .. } | Phase::EnsuringDurability { .. }
884 )
885 }) {
886 return Err(format!(
887 "active request {request} has no resident cell {id:?}"
888 ));
889 }
890 }
891 for (op, gate) in &self.gated_writes {
892 // A held write keeps its request pinned, so the cell cannot be
893 // evicted underneath the gate and a later write of the same
894 // request can still find it.
895 if self.active_requests.get(&gate.request) != Some(&gate.cell) {
896 return Err(format!(
897 "gated write op {op} for request {} is not pinned on {:?}",
898 gate.request, gate.cell
899 ));
900 }
901 }
902 for (id, cell) in &self.cells {
903 if matches!(cell.alarm, Some(AlarmState::Firing { .. }))
904 && !matches!(cell.phase, Phase::Resident { .. })
905 {
906 return Err(format!("cell {id:?} is firing an alarm while not resident"));
907 }
908 if cell
909 .websockets
910 .values()
911 .any(|kind| matches!(kind, WebSocketKind::Regular | WebSocketKind::Outbound))
912 && !matches!(
913 cell.phase,
914 Phase::Resident { .. } | Phase::EnsuringDurability { .. }
915 )
916 {
917 return Err(format!(
918 "cell {id:?} has a live transport while not resident"
919 ));
920 }
921 }
922 Ok(())
923 }
924
925 fn op(&mut self) -> OpId {
926 let op = self.next_op;
927 self.next_op = self.next_op.checked_add(1).expect("operation id exhausted");
928 op
929 }
930
931 /// Allocate an op that will live in `cell`'s phase, alarm, or release
932 /// slot, and index it.
933 fn cell_op(&mut self, cell: &str) -> OpId {
934 let op = self.op();
935 self.cell_ops.insert(op, cell.to_string());
936 op
937 }
938
939 /// Resolve a completion's op to its cell, consuming the index entry —
940 /// but only when `predicate` confirms the cell still holds the op. On a
941 /// mismatch the entry stays: the op's real completion has not arrived
942 /// yet (an expiry can probe the wrong handler), and it must still find
943 /// its way here later.
944 fn take_cell_op(&mut self, op: OpId, predicate: impl Fn(&Cell) -> bool) -> Option<CellId> {
945 let id = self.cell_ops.get(&op)?.clone();
946 if !self.cells.get(&id).is_some_and(predicate) {
947 return None;
948 }
949 self.cell_ops.remove(&op);
950 Some(id)
951 }
952
953 fn has_capacity(&self) -> bool {
954 // Residency is a hard cap, known exactly and counted -- never sampled.
955 // A node at its cell cap is at capacity, not overloaded: it refuses
956 // more and holds what it has, rather than shedding a live cell it must
957 // then place again elsewhere. The only sampled fact that refuses
958 // admission is genuine memory pressure, which a cell count
959 // cannot see.
960 self.occupied_below(self.config.max_resident) && !self.shedding
961 }
962
963 pub fn is_active(&self, id: &str) -> bool {
964 self.active_cells.contains_key(id)
965 || self.cells.get(id).is_some_and(|cell| {
966 cell.websockets
967 .values()
968 .any(|kind| matches!(kind, WebSocketKind::Regular | WebSocketKind::Outbound))
969 })
970 }
971
972 /// Record `request` as active on `cell`, keeping the `active_cells`
973 /// reverse index in step with `active_requests`. Every insert into
974 /// `active_requests` goes through here so the two never disagree.
975 fn activate_request(&mut self, request: RequestId, cell: CellId) {
976 *self.active_cells.entry(cell.clone()).or_insert(0) += 1;
977 self.active_requests.insert(request, cell);
978 }
979
980 /// Drop `request` from the active set, decrementing its cell's index and
981 /// forgetting the cell once no request targets it. Returns the cell the
982 /// request held, as `active_requests.remove` did.
983 fn deactivate_request(&mut self, request: RequestId) -> Option<CellId> {
984 let cell = self.active_requests.remove(&request)?;
985 if let Some(count) = self.active_cells.get_mut(&cell) {
986 *count -= 1;
987 if *count == 0 {
988 self.active_cells.remove(&cell);
989 }
990 }
991 Some(cell)
992 }
993
994 /// Hibernated (Durable Objects state 4): out of memory, still on this
995 /// host, with WebSocket clients parked at the network layer. Nothing in
996 /// memory survives -- the next event runs the constructor again, exactly
997 /// as a cold start does -- so the surviving sockets are the whole of the
998 /// difference from `Inactive`.
999 pub fn is_hibernated(&self, id: &str) -> bool {
1000 self.cells.get(id).is_some_and(|cell| {
1001 matches!(cell.phase, Phase::Dormant { .. })
1002 && cell
1003 .websockets
1004 .values()
1005 .any(|kind| matches!(kind, WebSocketKind::Hibernatable))
1006 })
1007 }
1008
1009 /// Hibernatable (Durable Objects state 2): resident, doing no work, and
1010 /// holding nothing that must survive in memory. State 3 is the negation --
1011 /// resident and idle, but pinned by a `Regular` or `Outbound` socket that
1012 /// cannot outlive the isolate.
1013 ///
1014 /// This is the cell's own criteria, not a decision to evict. celld also
1015 /// refuses eviction for an imminent or uncovered alarm and for state the
1016 /// bucket cannot restore; those are policy and are checked separately.
1017 pub fn is_hibernatable(&self, id: &str) -> bool {
1018 self.cells
1019 .get(id)
1020 .is_some_and(|cell| matches!(cell.phase, Phase::Resident { .. }))
1021 && !self.is_active(id)
1022 }
1023
1024 pub fn websocket_count(&self, id: &str) -> usize {
1025 self.cells.get(id).map_or(0, |cell| cell.websockets.len())
1026 }
1027
1028 /// Does anything local still need this process's node authority?
1029 ///
1030 /// The question every caller but the shadow snapshot actually asks, and
1031 /// asking it directly is what makes it cheap: no set, no cloned ids, and
1032 /// a stop at the first dependent cell.
1033 ///
1034 /// Counting instead put an `O(n log n)` walk of every resident cell on
1035 /// the path taken after *every* state transition, which is to say on
1036 /// every request. A profile of `/c/hello` with 800 resident cells spent
1037 /// more time in `BTreeSet<String>` than in the request: throughput fell
1038 /// from 57k to 3.5k rps, linearly in the number of resident cells.
1039 fn node_lease_is_depended_on(&self) -> bool {
1040 !self.node_lease_waiters.is_empty()
1041 || !self.node_wake_waiters.is_empty()
1042 || self
1043 .cells
1044 .values()
1045 .any(|cell| phase_depends_on_node_lease(&cell.phase) || !cell.websockets.is_empty())
1046 }
1047
1048 /// How many distinct local cell lifecycles require this process's node
1049 /// authority. Hibernated cells do not pin a lazy lease by themselves, but
1050 /// a hibernated cell does, because its host-held WebSocket outlives the
1051 /// isolate.
1052 ///
1053 /// The exact figure, for the shadow snapshot that reports it. Everything
1054 /// else wants [`node_lease_is_depended_on`](Self::node_lease_is_depended_on),
1055 /// which answers the same question without building the set.
1056 fn node_lease_dependency_count(&self) -> usize {
1057 let mut cells = BTreeSet::new();
1058 cells.extend(self.node_lease_waiters.values().cloned());
1059 cells.extend(self.node_wake_waiters.iter().cloned());
1060 for (id, cell) in &self.cells {
1061 if phase_depends_on_node_lease(&cell.phase) || !cell.websockets.is_empty() {
1062 cells.insert(id.clone());
1063 }
1064 }
1065 cells.len()
1066 }
1067
1068 /// Update idle/liveness bookkeeping after every state transition. This is
1069 /// deliberately derived from core state rather than an executor-owned
1070 /// active-cell counter, which used to let the model and production drift.
1071 fn update_node_lease_dependencies(&mut self, now_mono_ms: u64) {
1072 let depended_on = self.node_lease_is_depended_on();
1073 let held = match &mut self.node_authority {
1074 NodeAuthority::Held(held) => Some(held),
1075 NodeAuthority::Reading { pending, .. } | NodeAuthority::Writing { pending, .. } => {
1076 pending.prior.as_mut()
1077 }
1078 _ => None,
1079 };
1080 let Some(held) = held else {
1081 return;
1082 };
1083 if !depended_on {
1084 held.idle_since_mono_ms.get_or_insert(now_mono_ms);
1085 } else {
1086 held.idle_since_mono_ms = None;
1087 held.shadow_release_reported = false;
1088 }
1089 }
1090
1091 fn record_shadow_release(
1092 &mut self,
1093 held: &HeldNodeLease,
1094 now_ms: u64,
1095 now_mono_ms: u64,
1096 effects: &mut Vec<Effect>,
1097 ) {
1098 const MAX_SHADOW_DECISIONS: usize = 8;
1099 let sequence = self.next_shadow_sequence;
1100 self.next_shadow_sequence = self.next_shadow_sequence.saturating_add(1);
1101 if self.lazy_lease_shadow.decisions.len() == MAX_SHADOW_DECISIONS {
1102 self.lazy_lease_shadow.decisions.remove(0);
1103 self.lazy_lease_shadow.dropped = self.lazy_lease_shadow.dropped.saturating_add(1);
1104 }
1105 let idle_ms = held
1106 .idle_since_mono_ms
1107 .map_or(0, |inactive| now_mono_ms.saturating_sub(inactive));
1108 self.lazy_lease_shadow
1109 .decisions
1110 .push(LeaseLifecycleShadowDecision {
1111 sequence,
1112 observed_at_ms: now_ms,
1113 snapshot: LeaseLifecycleShadowSnapshot {
1114 mode: NodeLeaseMode::Shadow,
1115 active_cells: self.node_lease_dependency_count(),
1116 serving_cells: self.residents().len(),
1117 idle_ms,
1118 linger_ms: held.spec.linger_ms,
1119 lease_active: true,
1120 elapsed_since_ok_ms: now_mono_ms.saturating_sub(held.last_ok_mono_ms),
1121 elapsed_since_renew_ms: now_mono_ms.saturating_sub(held.last_attempt_mono_ms),
1122 ttl_ms: held.spec.ttl_ms,
1123 shadow_release_reported: false,
1124 },
1125 expected: LeaseLifecycleShadowExpected {
1126 shadow_release: true,
1127 authority_action: NodeLeaseAuthorityAction::Renew,
1128 },
1129 });
1130 effects.push(Effect::ObserveNodeLeaseShadowRelease { sequence });
1131 }
1132
1133 fn complete_request(
1134 &mut self,
1135 id: &str,
1136 request: RequestId,
1137 result: Result<Route, RequestError>,
1138 effects: &mut Vec<Effect>,
1139 ) {
1140 self.capacity_requests.remove(&request);
1141 match &result {
1142 Ok(Route::Local) => {
1143 self.activate_request(request, id.to_string());
1144 let now = self.now_mono_ms;
1145 if let Some(cell) = self.cells.get_mut(id) {
1146 cell.last_used_mono_ms = now;
1147 }
1148 }
1149 Ok(Route::Remote { .. }) => {
1150 self.activity.proxied = self.activity.proxied.saturating_add(1);
1151 }
1152 Err(_) => {}
1153 }
1154 effects.push(Effect::Complete { request, result });
1155 }
1156
1157 fn record_acquisition(&mut self, spec: &RestoreSpec) {
1158 self.activity.acquired = self.activity.acquired.saturating_add(1);
1159 if spec.took_over {
1160 self.activity.expired_owner_leases =
1161 self.activity.expired_owner_leases.saturating_add(1);
1162 }
1163 if spec.epoch > 1 {
1164 self.activity.advanced_epochs = self.activity.advanced_epochs.saturating_add(1);
1165 }
1166 }
1167
1168 fn worker_request(&mut self, request: RequestId, effects: &mut Vec<Effect>) {
1169 let route = self
1170 .cells
1171 .iter()
1172 .filter_map(|(id, cell)| {
1173 let (epoch, retired_durability) = match cell.phase {
1174 Phase::Resident { epoch } => (epoch, None),
1175 Phase::EnsuringDurability { op, epoch } => (epoch, Some(op)),
1176 _ => return None,
1177 };
1178 if self.is_active(id) || matches!(cell.alarm, Some(AlarmState::Firing { .. })) {
1179 return None;
1180 }
1181 Some((id.clone(), epoch, retired_durability))
1182 })
1183 .find(|(id, _, _)| self.worker_cursor.as_ref().is_none_or(|cursor| id > cursor))
1184 .or_else(|| {
1185 self.cells.iter().find_map(|(id, cell)| {
1186 let (epoch, retired_durability) = match cell.phase {
1187 Phase::Resident { epoch } => (epoch, None),
1188 Phase::EnsuringDurability { op, epoch } => (epoch, Some(op)),
1189 _ => return None,
1190 };
1191 (!self.is_active(id) && !matches!(cell.alarm, Some(AlarmState::Firing { .. })))
1192 .then(|| (id.clone(), epoch, retired_durability))
1193 })
1194 })
1195 .map(|(cell, epoch, retired_durability)| WorkerRoute {
1196 cell,
1197 epoch,
1198 retired_durability,
1199 });
1200
1201 if let Some(route) = &route {
1202 self.worker_cursor = Some(route.cell.clone());
1203 self.activate_request(request, route.cell.clone());
1204 if let Some(cell) = self.cells.get_mut(&route.cell) {
1205 if matches!(cell.phase, Phase::EnsuringDurability { .. }) {
1206 // Same rescue as `request_authorized`: the permit taken
1207 // at nomination comes back with the cell.
1208 if let Some(stale) = phase_op(&cell.phase) {
1209 self.cell_ops.remove(&stale);
1210 }
1211 set_phase(
1212 &mut self.occupied,
1213 cell,
1214 Phase::Resident { epoch: route.epoch },
1215 );
1216 self.eviction_permits.remove(&route.cell);
1217 }
1218 cell.last_used_mono_ms = self.now_mono_ms;
1219 }
1220 }
1221 effects.push(Effect::CompleteWorker { request, route });
1222 }
1223
1224 fn finish_requests(
1225 &mut self,
1226 id: &str,
1227 cell: &mut Cell,
1228 result: Result<Route, RequestError>,
1229 effects: &mut Vec<Effect>,
1230 ) {
1231 for request in std::mem::take(&mut cell.requests) {
1232 self.request_cells.remove(&request);
1233 self.complete_request(id, request, result.clone(), effects);
1234 }
1235 }
1236
1237 fn begin_cold_route(
1238 &mut self,
1239 id: &str,
1240 cell: &mut Cell,
1241 start: ColdStart,
1242 effects: &mut Vec<Effect>,
1243 ) {
1244 debug_assert!(self.activation_permits.contains(id));
1245 cell.waiting_activation = None;
1246 match start {
1247 ColdStart::ReadOwner => {
1248 let op = self.cell_op(id);
1249 set_phase(&mut self.occupied, cell, Phase::ReadingOwner { op });
1250 effects.push(Effect::ReadOwner {
1251 op,
1252 cell: id.to_string(),
1253 });
1254 }
1255 ColdStart::Restore(spec) => {
1256 self.activate_or_wait(id, cell, Activation::Restore(spec), effects)
1257 }
1258 }
1259 }
1260
1261 fn admit_or_queue_activation(
1262 &mut self,
1263 id: &str,
1264 cell: &mut Cell,
1265 start: ColdStart,
1266 effects: &mut Vec<Effect>,
1267 ) {
1268 if self.activation_permits.contains(id) {
1269 self.begin_cold_route(id, cell, start, effects);
1270 } else if self.activation_permits.len() < self.config.max_activations {
1271 self.activation_permits.insert(id.to_string());
1272 self.begin_cold_route(id, cell, start, effects);
1273 } else {
1274 set_phase(&mut self.occupied, cell, Phase::WaitingActivation);
1275 cell.waiting_activation = Some(start);
1276 self.activation_waiters.push_back(id.to_string());
1277 }
1278 }
1279
1280 fn pump_activations(&mut self, effects: &mut Vec<Effect>) {
1281 self.activation_permits.retain(|id| {
1282 self.cells
1283 .get(id)
1284 .is_some_and(|cell| phase_holds_activation(&cell.phase))
1285 });
1286
1287 while self.activation_permits.len() < self.config.max_activations {
1288 let Some(id) = self.activation_waiters.pop_front() else {
1289 break;
1290 };
1291 let Some(mut cell) = self.cells.remove(&id) else {
1292 continue;
1293 };
1294 if cell.phase != Phase::WaitingActivation {
1295 self.cells.insert(id, cell);
1296 continue;
1297 }
1298 let Some(start) = cell.waiting_activation.take() else {
1299 self.cells.insert(id, cell);
1300 continue;
1301 };
1302 if cell.requests.is_empty() && !cell.alarm_wake && !cell.resume_demand {
1303 set_phase(
1304 &mut self.occupied,
1305 &mut cell,
1306 match start {
1307 ColdStart::ReadOwner => Phase::Inactive,
1308 ColdStart::Restore(spec) => Phase::Dormant { epoch: spec.epoch },
1309 },
1310 );
1311 } else {
1312 self.activation_permits.insert(id.clone());
1313 self.begin_cold_route(&id, &mut cell, start, effects);
1314 }
1315 self.cells.insert(id, cell);
1316 }
1317 }
1318
1319 /// Adopt the exact epochs encoded by a clean predecessor's local paths.
1320 /// The node lease CAS that caused this event is the ownership proof, so
1321 /// this path deliberately emits no per-cell ownership effects.
1322 fn local_cells_read(
1323 &mut self,
1324 result: Result<Vec<LocalCell>, Failure>,
1325 effects: &mut Vec<Effect>,
1326 ) {
1327 if !self.resuming {
1328 return;
1329 }
1330 let Ok(mut cells) = result else {
1331 self.resuming = false;
1332 return;
1333 };
1334 cells.sort();
1335 cells.dedup();
1336 if cells.len() > self.config.max_resident || !self.cells.is_empty() {
1337 self.resuming = false;
1338 return;
1339 }
1340 for local in cells {
1341 let mut cell = Cell {
1342 resume_demand: true,
1343 ..Cell::default()
1344 };
1345 self.resuming_cells.insert(local.id.clone());
1346 self.admit_or_queue_activation(
1347 &local.id,
1348 &mut cell,
1349 ColdStart::Restore(RestoreSpec {
1350 epoch: local.epoch,
1351 fresh: false,
1352 took_over: false,
1353 resume_local: true,
1354 }),
1355 effects,
1356 );
1357 self.cells.insert(local.id, cell);
1358 }
1359 if self.resuming_cells.is_empty() {
1360 self.resuming = false;
1361 }
1362 }
1363
1364 fn settle_local_resume(&mut self, id: &str) {
1365 if self.resuming_cells.remove(id) && self.resuming_cells.is_empty() {
1366 self.resuming = false;
1367 }
1368 if let Some(cell) = self.cells.get_mut(id) {
1369 cell.resume_demand = false;
1370 }
1371 }
1372
1373 fn begin_activation(
1374 &mut self,
1375 id: &str,
1376 cell: &mut Cell,
1377 activation: Activation,
1378 effects: &mut Vec<Effect>,
1379 ) {
1380 debug_assert!(self.has_capacity());
1381 cell.waiting_for = None;
1382 let op = self.cell_op(id);
1383 match activation {
1384 Activation::Claim(claim) => {
1385 set_phase(
1386 &mut self.occupied,
1387 cell,
1388 Phase::Acquiring {
1389 op,
1390 claim: claim.clone(),
1391 },
1392 );
1393 effects.push(Effect::CasOwner {
1394 op,
1395 cell: id.to_string(),
1396 guard: claim.guard,
1397 epoch: claim.epoch,
1398 takeover: claim.takeover,
1399 });
1400 }
1401 Activation::Restore(spec) => {
1402 set_phase(
1403 &mut self.occupied,
1404 cell,
1405 Phase::Restoring {
1406 op,
1407 spec: spec.clone(),
1408 },
1409 );
1410 effects.push(Effect::Restore {
1411 op,
1412 cell: id.to_string(),
1413 spec,
1414 });
1415 }
1416 }
1417 }
1418
1419 fn activate_or_wait(
1420 &mut self,
1421 id: &str,
1422 cell: &mut Cell,
1423 activation: Activation,
1424 effects: &mut Vec<Effect>,
1425 ) {
1426 if cell.requests.is_empty() && !cell.alarm_wake && !cell.resume_demand {
1427 set_phase(
1428 &mut self.occupied,
1429 cell,
1430 match activation {
1431 Activation::Claim(_) => Phase::Inactive,
1432 Activation::Restore(spec) => Phase::Dormant { epoch: spec.epoch },
1433 },
1434 );
1435 } else if self.has_capacity() {
1436 self.begin_activation(id, cell, activation, effects);
1437 } else {
1438 set_phase(&mut self.occupied, cell, Phase::WaitingCapacity);
1439 cell.waiting_for = Some(activation);
1440 self.capacity_waiters.push_back(id.to_string());
1441 self.shed_one(effects);
1442 }
1443 }
1444
1445 fn pump_capacity(&mut self, effects: &mut Vec<Effect>) {
1446 while self.has_capacity() {
1447 let Some(id) = self.capacity_waiters.pop_front() else {
1448 break;
1449 };
1450 let Some(mut cell) = self.cells.remove(&id) else {
1451 continue;
1452 };
1453 if cell.phase != Phase::WaitingCapacity {
1454 self.cells.insert(id, cell);
1455 continue;
1456 }
1457 let Some(activation) = cell.waiting_for.take() else {
1458 self.cells.insert(id, cell);
1459 continue;
1460 };
1461 if cell.requests.is_empty() && !cell.alarm_wake && !cell.resume_demand {
1462 set_phase(
1463 &mut self.occupied,
1464 &mut cell,
1465 match activation {
1466 Activation::Claim(_) => Phase::Inactive,
1467 Activation::Restore(spec) => Phase::Dormant { epoch: spec.epoch },
1468 },
1469 );
1470 } else {
1471 self.begin_activation(&id, &mut cell, activation, effects);
1472 }
1473 self.cells.insert(id, cell);
1474 }
1475 self.shed_one(effects);
1476 }
1477
1478 fn start_node_lease(&mut self, now_ms: u64, spec: NodeLeaseSpec, effects: &mut Vec<Effect>) {
1479 if !matches!(
1480 self.node_authority,
1481 NodeAuthority::Unstarted | NodeAuthority::Failed | NodeAuthority::Lapsed(_)
1482 ) {
1483 return;
1484 }
1485 if spec.mode == NodeLeaseMode::Lazy {
1486 self.node_authority = NodeAuthority::Lapsed(spec);
1487 return;
1488 }
1489 self.begin_node_lease_acquisition(now_ms, spec, effects);
1490 }
1491
1492 fn begin_node_lease_acquisition(
1493 &mut self,
1494 now_ms: u64,
1495 spec: NodeLeaseSpec,
1496 effects: &mut Vec<Effect>,
1497 ) {
1498 let desired = NodeLeaseRecord {
1499 node: self.node.clone(),
1500 addr: spec.addr.clone(),
1501 expires_ms: now_ms.saturating_add(spec.ttl_ms),
1502 peer_protocol: spec.peer_protocol,
1503 generation: spec.generation.clone(),
1504 etag: String::new(),
1505 };
1506 let pending = PendingNodeLease {
1507 spec,
1508 desired,
1509 prior: None,
1510 readback_only: false,
1511 anchor_mono_ms: self.now_mono_ms,
1512 resume_local: false,
1513 };
1514 let op = self.op();
1515 self.node_authority = NodeAuthority::Reading { op, pending };
1516 effects.push(Effect::ReadSelfNodeLease { op });
1517 }
1518
1519 fn fail_initial_node_lease(&mut self, spec: NodeLeaseSpec, effects: &mut Vec<Effect>) {
1520 self.node_authority = if spec.mode == NodeLeaseMode::Lazy {
1521 // The next request re-acquires from here.
1522 NodeAuthority::Lapsed(spec)
1523 } else {
1524 // Nothing else will ever ask: `StartNodeLease` is a one-shot at
1525 // process start. Arm the retry here or this node is done serving.
1526 // The renewal cadence is the right interval -- it is already the
1527 // rate this fleet has decided its bucket can carry.
1528 let generation = self.next_timer_generation;
1529 self.next_timer_generation = self
1530 .next_timer_generation
1531 .checked_add(1)
1532 .expect("timer generation exhausted");
1533 let retry_after = (spec.ttl_ms / 3).max(1);
1534 effects.push(Effect::ScheduleTimer {
1535 timer: Timer::NodeLeaseRenew { generation },
1536 at_mono_ms: self.now_mono_ms.saturating_add(retry_after),
1537 });
1538 NodeAuthority::Retrying { spec, generation }
1539 };
1540 for (request, _) in std::mem::take(&mut self.node_lease_waiters) {
1541 effects.push(Effect::Complete {
1542 request,
1543 result: Err(RequestError::NodeUnavailable),
1544 });
1545 }
1546 self.node_wake_waiters.clear();
1547 }
1548
1549 /// A lease write landed. Decide whether it actually preserved authority,
1550 /// and if so install it anchored to the instant its `expires_ms` was
1551 /// sampled.
1552 ///
1553 /// A renewal that lands at or after the PRIOR lease's expiry has not
1554 /// extended anything: every peer was already entitled to read that record,
1555 /// find it dead, and seize this node's cells, and one of them may have
1556 /// begun doing exactly that. Rewriting `nodes/<node>.json` does not
1557 /// retract a takeover already in flight -- the ownership compare-and-swap
1558 /// a peer is about to issue is guarded on the ownership record's ETag,
1559 /// which a resident owner never touches -- so resurrecting the lease here
1560 /// is precisely how two nodes end up serving one cell. The gap is a fence,
1561 /// not a hiccup.
1562 fn complete_node_lease_write(
1563 &mut self,
1564 pending: PendingNodeLease,
1565 record: NodeLeaseRecord,
1566 now_mono_ms: u64,
1567 effects: &mut Vec<Effect>,
1568 ) {
1569 // The record just published expires at `anchor + ttl`. A round trip
1570 // that outlived that window landed a lease which is already dead to
1571 // every peer reading the bucket, so this process must not act on it --
1572 // and acting on it is exactly what installing it does, because
1573 // `hold_node_lease` drains the waiting requests inline, before the
1574 // past-due fence timer it arms can possibly be delivered.
1575 let expired = now_mono_ms.saturating_sub(pending.anchor_mono_ms) >= pending.spec.ttl_ms;
1576 match &pending.prior {
1577 // A renewal only preserves authority if it lands while the PRIOR
1578 // lease is still valid. Losing that continuity means peers were
1579 // already entitled to seize this node's cells.
1580 Some(prior) => {
1581 if expired || now_mono_ms.saturating_sub(prior.last_ok_mono_ms) >= prior.spec.ttl_ms
1582 {
1583 self.fence_node(effects);
1584 return;
1585 }
1586 }
1587 // An initial acquisition that lands expired never became
1588 // authoritative: this node owns nothing and is serving nothing, so
1589 // there is no runtime to fence and no reason to halt. Fail the
1590 // waiters and let a later request retry from a fresh sample.
1591 None => {
1592 if expired {
1593 self.fail_initial_node_lease(pending.spec, effects);
1594 return;
1595 }
1596 }
1597 }
1598 let resume_local = pending.resume_local;
1599 self.hold_node_lease(
1600 pending.spec,
1601 record,
1602 pending.prior,
1603 pending.anchor_mono_ms,
1604 resume_local,
1605 effects,
1606 );
1607 }
1608
1609 /// Install a held lease. `anchor_mono_ms` is the monotonic instant the
1610 /// record's `expires_ms` was computed from -- NOT the instant the write
1611 /// completed. See [`PendingNodeLease::anchor_mono_ms`].
1612 fn hold_node_lease(
1613 &mut self,
1614 spec: NodeLeaseSpec,
1615 record: NodeLeaseRecord,
1616 prior: Option<HeldNodeLease>,
1617 anchor_mono_ms: u64,
1618 resume_local: bool,
1619 effects: &mut Vec<Effect>,
1620 ) {
1621 let generation = self.next_timer_generation;
1622 self.next_timer_generation = self
1623 .next_timer_generation
1624 .checked_add(1)
1625 .expect("timer generation exhausted");
1626 let renew_after = (spec.ttl_ms / 3).max(1);
1627 effects.push(Effect::ScheduleTimer {
1628 timer: Timer::NodeLeaseRenew { generation },
1629 at_mono_ms: anchor_mono_ms.saturating_add(renew_after),
1630 });
1631 // Exactly the published deadline. A peer treats the record as live
1632 // while `expires_ms > now_ms`, so this node must have stopped serving
1633 // by the time `now_ms` reaches `expires_ms` -- not one millisecond
1634 // after it.
1635 effects.push(Effect::ScheduleTimer {
1636 timer: Timer::NodeLeaseFence { generation },
1637 at_mono_ms: anchor_mono_ms.saturating_add(spec.ttl_ms),
1638 });
1639 let idle_since_mono_ms = prior
1640 .as_ref()
1641 .and_then(|held| held.idle_since_mono_ms)
1642 .or_else(|| (!self.node_lease_is_depended_on()).then_some(anchor_mono_ms));
1643 let shadow_release_reported = prior
1644 .as_ref()
1645 .is_some_and(|held| held.shadow_release_reported);
1646 self.node_authority = NodeAuthority::Held(HeldNodeLease {
1647 spec,
1648 record,
1649 last_ok_mono_ms: anchor_mono_ms,
1650 last_attempt_mono_ms: anchor_mono_ms,
1651 timer_generation: generation,
1652 idle_since_mono_ms,
1653 shadow_release_reported,
1654 });
1655 if resume_local {
1656 self.resuming = true;
1657 effects.push(Effect::ReadLocalCells);
1658 }
1659 self.drain_node_lease_waiters(effects);
1660 }
1661
1662 fn resume_node_lease_after_failure(
1663 &mut self,
1664 prior: HeldNodeLease,
1665 now_mono_ms: u64,
1666 effects: &mut Vec<Effect>,
1667 ) {
1668 let retry_after = (prior.spec.ttl_ms / 3).max(1);
1669 effects.push(Effect::ScheduleTimer {
1670 timer: Timer::NodeLeaseRenew {
1671 generation: prior.timer_generation,
1672 },
1673 at_mono_ms: now_mono_ms.saturating_add(retry_after),
1674 });
1675 self.node_authority = NodeAuthority::Held(prior);
1676 }
1677
1678 fn release_or_fence_node_lease(&mut self, held: HeldNodeLease, effects: &mut Vec<Effect>) {
1679 if held.spec.mode == NodeLeaseMode::Lazy && !self.node_lease_is_depended_on() {
1680 self.node_authority = NodeAuthority::Lapsed(held.spec);
1681 effects.push(Effect::ObserveNodeLeaseReleased);
1682 } else {
1683 self.fence_node(effects);
1684 }
1685 }
1686
1687 fn begin_node_lease_write(
1688 &mut self,
1689 pending: PendingNodeLease,
1690 guard: CasGuard,
1691 effects: &mut Vec<Effect>,
1692 ) {
1693 let op = self.op();
1694 let record = pending.desired.clone();
1695 let authority_expires_ms = pending.prior.as_ref().map(|prior| prior.record.expires_ms);
1696 self.node_authority = NodeAuthority::Writing { op, pending };
1697 effects.push(Effect::CasNodeLease {
1698 op,
1699 guard,
1700 record,
1701 authority_expires_ms,
1702 });
1703 }
1704
1705 fn read_self_node_lease(
1706 &mut self,
1707 op: OpId,
1708 now_ms: u64,
1709 now_mono_ms: u64,
1710 result: Result<Option<NodeLeaseRecord>, Failure>,
1711 effects: &mut Vec<Effect>,
1712 ) {
1713 let authority = std::mem::replace(&mut self.node_authority, NodeAuthority::Failed);
1714 let NodeAuthority::Reading {
1715 op: current,
1716 pending,
1717 } = authority
1718 else {
1719 self.node_authority = authority;
1720 return;
1721 };
1722 if current != op {
1723 self.node_authority = NodeAuthority::Reading {
1724 op: current,
1725 pending,
1726 };
1727 return;
1728 }
1729 match result {
1730 Err(_) => {
1731 if let Some(prior) = pending.prior {
1732 self.resume_node_lease_after_failure(prior, now_mono_ms, effects);
1733 } else {
1734 self.fail_initial_node_lease(pending.spec, effects);
1735 }
1736 }
1737 Ok(Some(record)) if same_node_lease(&record, &pending.desired) => {
1738 self.complete_node_lease_write(pending, record, now_mono_ms, effects);
1739 }
1740 Ok(Some(record))
1741 if pending
1742 .prior
1743 .as_ref()
1744 .is_some_and(|prior| same_node_lease(&record, &prior.record)) =>
1745 {
1746 let mut prior = pending.prior.expect("checked above");
1747 prior.record.etag = record.etag;
1748 self.resume_node_lease_after_failure(prior, now_mono_ms, effects);
1749 }
1750 Ok(record) if pending.prior.is_some() => {
1751 // A renewal was ambiguous and read-back no longer names our
1752 // exact generation, or the record vanished. Authority is lost.
1753 let _ = record;
1754 self.release_or_fence_node_lease(pending.prior.expect("checked above"), effects);
1755 }
1756 Ok(_) if pending.readback_only => {
1757 // The ambiguous initial write did not publish the exact
1758 // desired generation. Fail this activation; a later request
1759 // may retry from a fresh read, but this one cannot spin.
1760 self.fail_initial_node_lease(pending.spec, effects);
1761 }
1762 Ok(Some(record)) => {
1763 // A configured node id is a singleton key: restarting that
1764 // node replaces its prior process generation immediately. The
1765 // ETag still serializes competing replacements, and a process
1766 // which loses that CAS never becomes authoritative.
1767 let mut pending = pending;
1768 pending.resume_local = pending.prior.is_none()
1769 && !pending.readback_only
1770 && record.expires_ms > now_ms
1771 && pending.spec.resume_generation.as_deref()
1772 == Some(record.generation.as_str());
1773 self.begin_node_lease_write(pending, CasGuard::Match(record.etag), effects);
1774 }
1775 Ok(None) => self.begin_node_lease_write(pending, CasGuard::Absent, effects),
1776 }
1777 }
1778
1779 fn node_lease_cas_completed(
1780 &mut self,
1781 op: OpId,
1782 now_mono_ms: u64,
1783 result: Result<LeaseCasOutcome, Failure>,
1784 effects: &mut Vec<Effect>,
1785 ) {
1786 let authority = std::mem::replace(&mut self.node_authority, NodeAuthority::Failed);
1787 let NodeAuthority::Writing {
1788 op: current,
1789 pending,
1790 } = authority
1791 else {
1792 self.node_authority = authority;
1793 return;
1794 };
1795 if current != op {
1796 self.node_authority = NodeAuthority::Writing {
1797 op: current,
1798 pending,
1799 };
1800 return;
1801 }
1802 match result {
1803 Ok(LeaseCasOutcome::Applied { etag }) => {
1804 let mut record = pending.desired.clone();
1805 record.etag = etag;
1806 self.complete_node_lease_write(pending, record, now_mono_ms, effects);
1807 }
1808 Ok(LeaseCasOutcome::Rejected) if pending.prior.is_some() => {
1809 self.release_or_fence_node_lease(pending.prior.expect("checked above"), effects);
1810 }
1811 Ok(LeaseCasOutcome::Rejected) => {
1812 let read = self.op();
1813 self.node_authority = NodeAuthority::Reading { op: read, pending };
1814 effects.push(Effect::ReadSelfNodeLease { op: read });
1815 }
1816 Err(Failure::Ambiguous) => {
1817 let read = self.op();
1818 let mut pending = pending;
1819 pending.readback_only = true;
1820 self.node_authority = NodeAuthority::Reading { op: read, pending };
1821 effects.push(Effect::ReadSelfNodeLease { op: read });
1822 }
1823 Err(Failure::Definite) => {
1824 if let Some(prior) = pending.prior {
1825 self.resume_node_lease_after_failure(prior, now_mono_ms, effects);
1826 } else {
1827 self.fail_initial_node_lease(pending.spec, effects);
1828 }
1829 }
1830 }
1831 }
1832
1833 /// Arm a deadline for every activation effect this event produced.
1834 ///
1835 /// Done once, centrally, rather than at each of the eleven sites that emit
1836 /// one: those are eleven chances to forget, and a forgotten deadline is
1837 /// invisible until something hangs. The effect list already names every
1838 /// operation the executor is about to start, so it is the natural place to
1839 /// decide which of them are worth watching.
1840 fn arm_operation_deadlines(&mut self, effects: &mut Vec<Effect>) {
1841 let Some(deadline_ms) = self.config.operation_deadline_ms else {
1842 return;
1843 };
1844 let watched: Vec<OpId> = effects
1845 .iter()
1846 .filter_map(|effect| match effect {
1847 // Every operation that holds something back. The activation
1848 // stages hold a caller; a durability proof holds an eviction;
1849 // a firing alarm holds the cell out of dormancy. All three
1850 // keep the ownership record claimed while they wait.
1851 //
1852 // `StopRuntime` is the deliberate exception. It has no failure
1853 // handling to reuse -- a stop cannot fail, it can only not
1854 // finish -- so abandoning one would mean declaring a runtime
1855 // gone while it may still be running. That needs a decision,
1856 // not a timer.
1857 // A restore is a sequence of individually bounded object-store
1858 // requests. Its total duration scales with the replica. The
1859 // shell cannot cancel the task, so retiring the core op would
1860 // discard late success and let another request duplicate it.
1861 Effect::Restore { .. } => None,
1862 Effect::ReadOwner { op, .. }
1863 | Effect::ReadNodeLease { op, .. }
1864 | Effect::ReadCapacityPeers { op, .. }
1865 | Effect::CasOwner { op, .. }
1866 | Effect::StartRuntime { op, .. }
1867 | Effect::Publish { op, .. }
1868 | Effect::EnsureDurable { op, .. }
1869 // A held write response: a swallowed durability proof must not
1870 // hang a client forever.
1871 | Effect::AwaitDurable { op, .. }
1872 | Effect::FireAlarm { op, .. } => Some(*op),
1873 _ => None,
1874 })
1875 .collect();
1876 let at_mono_ms = self.now_mono_ms.saturating_add(deadline_ms);
1877 for op in watched {
1878 effects.push(Effect::ScheduleTimer {
1879 timer: Timer::OperationDeadline { op },
1880 at_mono_ms,
1881 });
1882 }
1883 }
1884
1885 /// An activation effect outlived its deadline.
1886 ///
1887 /// Expiry deliberately reuses each stage's own failure handling rather
1888 /// than introducing a second way to abandon work: the core already knows
1889 /// how to reconcile an ambiguous acquire and how to fail a read, and a
1890 /// deadline is only a different reason for reaching those paths.
1891 ///
1892 /// The classification is the whole substance. A read cannot have committed
1893 /// anything, so it is definite. Everything past it may have taken effect
1894 /// on the far side while the answer was lost, so it is ambiguous — the
1895 /// same distinction that decides whether a retry is safe. Calling a
1896 /// timed-out compare-and-swap definite would let a second attempt
1897 /// overwrite an epoch that had in fact been applied.
1898 fn expire_operation(&mut self, op: OpId, now_ms: u64, effects: &mut Vec<Effect>) {
1899 // A gated write is tracked in `gated_writes`, not the op index.
1900 // Ambiguous is the only safe class: the write may or may not be
1901 // durable, so the client must not be told it succeeded.
1902 if self.gated_writes.contains_key(&op) {
1903 self.durable_reached(op, Err(Failure::Ambiguous), effects);
1904 return;
1905 }
1906 // A peek, not a take: each arm below re-enters the op's own
1907 // completion handler, and that handler consumes the index entry.
1908 let Some(id) = self.cell_ops.get(&op).cloned() else {
1909 // Already answered, superseded, or fenced. A stale deadline has
1910 // nothing to expire, which is the ordinary case.
1911 return;
1912 };
1913 let Some(cell) = self.cells.get(&id) else {
1914 return;
1915 };
1916 // A firing alarm is tracked on the cell rather than in its phase, so
1917 // it is looked for first. Expiry re-arms it exactly as a failed
1918 // handler would, which keeps alarms at-least-once instead of turning
1919 // a stuck handler into a lost one.
1920 if matches!(cell.alarm, Some(AlarmState::Firing { op: current, .. }) if current == op) {
1921 let now_mono_ms = self.now_mono_ms;
1922 self.alarm_finished(op, now_ms, now_mono_ms, Err(Failure::Ambiguous), effects);
1923 return;
1924 }
1925 if phase_op(&cell.phase) != Some(op) {
1926 return;
1927 }
1928 let phase = Some(cell.phase.clone());
1929 match phase {
1930 Some(Phase::ReadingOwner { .. }) => {
1931 self.owner_read(op, 0, Err(Failure::Definite), effects)
1932 }
1933 Some(Phase::ReadingNodeLease { .. }) => {
1934 self.node_lease_read(op, now_ms, Err(Failure::Definite), effects)
1935 }
1936 Some(Phase::ReadingCapacity { .. }) => {
1937 self.capacity_peers_read(op, now_ms, Err(Failure::Definite), effects)
1938 }
1939 Some(Phase::Acquiring { .. }) | Some(Phase::ReconcilingAcquire { .. }) => {
1940 self.owner_cas_completed(op, Err(Failure::Ambiguous), effects)
1941 }
1942 // A restore has no aggregate deadline. Each object-store request
1943 // is bounded in the shell, and the complete task must retain its
1944 // op so a late success cannot be discarded and duplicated.
1945 Some(Phase::Restoring { .. }) => {}
1946 Some(Phase::Starting { .. }) => {
1947 self.runtime_started(op, Err(Failure::Ambiguous), effects)
1948 }
1949 Some(Phase::Publishing { .. }) => self.published(op, Err(Failure::Ambiguous), effects),
1950 // An unprovable snapshot leaves the cell resident. Evicting on a
1951 // proof that never arrived is the one outcome that loses data.
1952 Some(Phase::EnsuringDurability { .. }) => {
1953 self.durability_checked(op, Err(Failure::Ambiguous), effects)
1954 }
1955 _ => {}
1956 }
1957 }
1958
1959 fn timer_fired(
1960 &mut self,
1961 timer: Timer,
1962 now_ms: u64,
1963 now_mono_ms: u64,
1964 effects: &mut Vec<Effect>,
1965 ) {
1966 self.update_node_lease_dependencies(now_mono_ms);
1967 let timer = match timer {
1968 Timer::CellAlarm { cell, generation } => {
1969 self.cell_alarm_timer(&cell, generation, now_ms, now_mono_ms, effects);
1970 return;
1971 }
1972 // An activation deadline is not conditional on node authority: a
1973 // request stalled behind a swallowed effect must be released
1974 // whatever the lease is doing.
1975 Timer::OperationDeadline { op } => {
1976 self.expire_operation(op, now_ms, effects);
1977 return;
1978 }
1979 timer => timer,
1980 };
1981 // A retry has no held lease to validate against, so it is resolved
1982 // before the authority lookup below discards it.
1983 if let NodeAuthority::Retrying { spec, generation } = &self.node_authority {
1984 if matches!(timer, Timer::NodeLeaseRenew { generation: fired } if fired == *generation)
1985 {
1986 let spec = spec.clone();
1987 self.begin_node_lease_acquisition(now_ms, spec, effects);
1988 }
1989 return;
1990 }
1991 let active = match &self.node_authority {
1992 NodeAuthority::Held(held) => Some(held.clone()),
1993 NodeAuthority::Reading { pending, .. } | NodeAuthority::Writing { pending, .. } => {
1994 pending.prior.clone()
1995 }
1996 _ => None,
1997 };
1998 let Some(held) = active else {
1999 return;
2000 };
2001 match timer {
2002 // `>=`, not `>`: a peer stops treating the record as live the
2003 // instant `now_ms` reaches `expires_ms`, so authority must end
2004 // there too. Serving through that one millisecond overlaps a
2005 // takeover that is already entitled to proceed.
2006 Timer::NodeLeaseFence { generation }
2007 if generation == held.timer_generation
2008 && now_mono_ms.saturating_sub(held.last_ok_mono_ms) >= held.spec.ttl_ms =>
2009 {
2010 self.release_or_fence_node_lease(held, effects);
2011 }
2012 // A renew timer that arrives after the lease it belongs to has
2013 // already expired is not a renewal opportunity; authority is
2014 // already gone. Fence rather than issue a write that could
2015 // resurrect it behind a peer's in-flight takeover.
2016 Timer::NodeLeaseRenew { generation }
2017 if generation == held.timer_generation
2018 && now_mono_ms.saturating_sub(held.last_ok_mono_ms) >= held.spec.ttl_ms =>
2019 {
2020 self.release_or_fence_node_lease(held, effects);
2021 }
2022 Timer::NodeLeaseRenew { generation }
2023 if generation == held.timer_generation
2024 && matches!(self.node_authority, NodeAuthority::Held(_)) =>
2025 {
2026 let NodeAuthority::Held(mut prior) =
2027 std::mem::replace(&mut self.node_authority, NodeAuthority::Failed)
2028 else {
2029 unreachable!("held checked above")
2030 };
2031 let idle_ms = prior
2032 .idle_since_mono_ms
2033 .map_or(0, |inactive| now_mono_ms.saturating_sub(inactive));
2034 let idle_long_enough =
2035 prior.idle_since_mono_ms.is_some() && idle_ms >= prior.spec.linger_ms;
2036 if prior.spec.mode == NodeLeaseMode::Shadow
2037 && idle_long_enough
2038 && !prior.shadow_release_reported
2039 {
2040 self.record_shadow_release(&prior, now_ms, now_mono_ms, effects);
2041 prior.shadow_release_reported = true;
2042 }
2043 if prior.spec.mode == NodeLeaseMode::Lazy && idle_long_enough {
2044 self.node_authority = NodeAuthority::Lapsed(prior.spec);
2045 effects.push(Effect::ObserveNodeLeaseReleased);
2046 return;
2047 }
2048 prior.last_attempt_mono_ms = now_mono_ms;
2049 let spec = prior.spec.clone();
2050 let desired = NodeLeaseRecord {
2051 node: self.node.clone(),
2052 addr: spec.addr.clone(),
2053 expires_ms: now_ms.saturating_add(spec.ttl_ms),
2054 peer_protocol: spec.peer_protocol,
2055 generation: spec.generation.clone(),
2056 etag: String::new(),
2057 };
2058 let guard = CasGuard::Match(prior.record.etag.clone());
2059 self.begin_node_lease_write(
2060 PendingNodeLease {
2061 spec,
2062 desired,
2063 prior: Some(prior),
2064 readback_only: false,
2065 anchor_mono_ms: now_mono_ms,
2066 resume_local: false,
2067 },
2068 guard,
2069 effects,
2070 );
2071 }
2072 Timer::CellAlarm { .. } => unreachable!("cell timers returned above"),
2073 _ => {}
2074 }
2075 }
2076
2077 fn schedule_alarm_timer(
2078 &self,
2079 cell: &str,
2080 generation: u64,
2081 at_ms: i64,
2082 now_ms: u64,
2083 now_mono_ms: u64,
2084 effects: &mut Vec<Effect>,
2085 ) {
2086 let at_ms = u64::try_from(at_ms).unwrap_or(0);
2087 effects.push(Effect::ScheduleTimer {
2088 timer: Timer::CellAlarm {
2089 cell: cell.to_string(),
2090 generation,
2091 },
2092 at_mono_ms: now_mono_ms.saturating_add(at_ms.saturating_sub(now_ms)),
2093 });
2094 }
2095
2096 fn alarm_observed(
2097 &mut self,
2098 id: &str,
2099 at_ms: Option<i64>,
2100 covered: bool,
2101 now_ms: u64,
2102 now_mono_ms: u64,
2103 effects: &mut Vec<Effect>,
2104 ) {
2105 let Some(mut cell) = self.cells.remove(id) else {
2106 return;
2107 };
2108 if matches!(cell.phase, Phase::Fenced) {
2109 self.cells.insert(id.to_string(), cell);
2110 return;
2111 }
2112 if let Phase::EnsuringDurability { op, epoch } = cell.phase {
2113 self.cell_ops.remove(&op);
2114 set_phase(&mut self.occupied, &mut cell, Phase::Resident { epoch });
2115 }
2116 // A request that armed this alarm can finish its output gate after
2117 // the alarm has started. Its activity report still carries the same
2118 // cached deadline, but that is not a new arm: replacing `Firing`
2119 // would retire the live op and schedule the due deadline again while
2120 // its handler is still running. Keep the claim and only refresh its
2121 // wake coverage. A real move to another deadline (or to no alarm)
2122 // still replaces the firing state below, and the handler's own final
2123 // observation settles an explicit re-arm to this same deadline.
2124 if let Some(AlarmState::Firing {
2125 at_ms: firing_at_ms,
2126 covered: firing_covered,
2127 ..
2128 }) = &mut cell.alarm
2129 {
2130 if at_ms == Some(*firing_at_ms) {
2131 *firing_covered = covered;
2132 self.cells.insert(id.to_string(), cell);
2133 return;
2134 }
2135 }
2136 let observed_before = match cell.alarm {
2137 Some(AlarmState::Armed { at_ms, .. }) | Some(AlarmState::Firing { at_ms, .. }) => at_ms,
2138 None => -1,
2139 };
2140 // The assignment below replaces a firing alarm unconditionally. Its
2141 // op entry is usually consumed already (`alarm_finished` routes
2142 // through here), but a direct observation can land mid-fire, and the
2143 // replaced op will then never match a lookup again.
2144 if let Some(AlarmState::Firing { op, .. }) = cell.alarm {
2145 self.cell_ops.remove(&op);
2146 }
2147 cell.alarm = at_ms.filter(|at_ms| *at_ms >= 0).map(|at_ms| {
2148 let generation = self.next_timer_generation;
2149 self.next_timer_generation = self
2150 .next_timer_generation
2151 .checked_add(1)
2152 .expect("timer generation exhausted");
2153 self.schedule_alarm_timer(id, generation, at_ms, now_ms, now_mono_ms, effects);
2154 AlarmState::Armed {
2155 at_ms,
2156 generation,
2157 covered,
2158 }
2159 });
2160 if cell.alarm.is_none() {
2161 cell.alarm_wake = false;
2162 }
2163 // Both ways an alarm settles arrive here -- a request that changed it
2164 // and a firing that consumed it (`alarm_finished` routes through this
2165 // function). Saying so once, here, is what keeps the bucket entry
2166 // from depending on the shell noticing each path separately. Only on
2167 // a change: an activity that left the alarm alone has nothing to
2168 // mirror, and re-stating it would put a bucket round trip on the end
2169 // of every request.
2170 let settled = at_ms.filter(|at_ms| *at_ms >= 0).unwrap_or(-1);
2171 if settled != observed_before {
2172 effects.push(Effect::ReconcileWakeEntry {
2173 cell: id.to_string(),
2174 next_alarm_ms: settled,
2175 });
2176 }
2177 self.cells.insert(id.to_string(), cell);
2178 }
2179
2180 fn cell_alarm_timer(
2181 &mut self,
2182 id: &str,
2183 generation: u64,
2184 now_ms: u64,
2185 now_mono_ms: u64,
2186 effects: &mut Vec<Effect>,
2187 ) {
2188 if !self.node_authoritative() {
2189 if let Some(spec) = self.lazy_node_lease_spec() {
2190 self.node_wake_waiters.insert(id.to_string());
2191 if matches!(self.node_authority, NodeAuthority::Lapsed(_)) {
2192 self.begin_node_lease_acquisition(now_ms, spec, effects);
2193 }
2194 effects.push(Effect::ScheduleTimer {
2195 timer: Timer::CellAlarm {
2196 cell: id.to_string(),
2197 generation,
2198 },
2199 at_mono_ms: now_mono_ms.saturating_add(100),
2200 });
2201 }
2202 return;
2203 }
2204 let Some(mut cell) = self.cells.remove(id) else {
2205 return;
2206 };
2207 let Some(AlarmState::Armed {
2208 at_ms,
2209 generation: current,
2210 covered,
2211 }) = cell.alarm
2212 else {
2213 self.cells.insert(id.to_string(), cell);
2214 return;
2215 };
2216 if current != generation {
2217 self.cells.insert(id.to_string(), cell);
2218 return;
2219 }
2220 if i64::try_from(now_ms).unwrap_or(i64::MAX) < at_ms {
2221 self.schedule_alarm_timer(id, generation, at_ms, now_ms, now_mono_ms, effects);
2222 self.cells.insert(id.to_string(), cell);
2223 return;
2224 }
2225 let epoch = match cell.phase {
2226 Phase::Resident { epoch } => epoch,
2227 Phase::EnsuringDurability { op, epoch } => {
2228 self.cell_ops.remove(&op);
2229 set_phase(&mut self.occupied, &mut cell, Phase::Resident { epoch });
2230 epoch
2231 }
2232 Phase::Fenced => {
2233 cell.alarm = None;
2234 self.cells.insert(id.to_string(), cell);
2235 return;
2236 }
2237 Phase::Dormant { epoch } => {
2238 cell.alarm_wake = true;
2239 self.admit_or_queue_activation(
2240 id,
2241 &mut cell,
2242 ColdStart::Restore(RestoreSpec {
2243 epoch,
2244 fresh: false,
2245 took_over: false,
2246 resume_local: false,
2247 }),
2248 effects,
2249 );
2250 effects.push(Effect::ScheduleTimer {
2251 timer: Timer::CellAlarm {
2252 cell: id.to_string(),
2253 generation,
2254 },
2255 at_mono_ms: now_mono_ms.saturating_add(100),
2256 });
2257 self.cells.insert(id.to_string(), cell);
2258 return;
2259 }
2260 Phase::Inactive => {
2261 cell.alarm_wake = true;
2262 self.admit_or_queue_activation(id, &mut cell, ColdStart::ReadOwner, effects);
2263 effects.push(Effect::ScheduleTimer {
2264 timer: Timer::CellAlarm {
2265 cell: id.to_string(),
2266 generation,
2267 },
2268 at_mono_ms: now_mono_ms.saturating_add(100),
2269 });
2270 self.cells.insert(id.to_string(), cell);
2271 return;
2272 }
2273 _ => {
2274 effects.push(Effect::ScheduleTimer {
2275 timer: Timer::CellAlarm {
2276 cell: id.to_string(),
2277 generation,
2278 },
2279 at_mono_ms: now_mono_ms.saturating_add(100),
2280 });
2281 self.cells.insert(id.to_string(), cell);
2282 return;
2283 }
2284 };
2285 let op = self.cell_op(id);
2286 cell.alarm = Some(AlarmState::Firing {
2287 op,
2288 at_ms,
2289 generation,
2290 covered,
2291 });
2292 cell.alarm_wake = false;
2293 self.cells.insert(id.to_string(), cell);
2294 effects.push(Effect::FireAlarm {
2295 op,
2296 cell: id.to_string(),
2297 epoch,
2298 scheduled_ms: at_ms,
2299 });
2300 }
2301
2302 fn alarm_finished(
2303 &mut self,
2304 op: OpId,
2305 now_ms: u64,
2306 now_mono_ms: u64,
2307 result: Result<(Option<i64>, bool), Failure>,
2308 effects: &mut Vec<Effect>,
2309 ) {
2310 let Some(id) = self.take_cell_op(op, |cell| {
2311 matches!(cell.alarm, Some(AlarmState::Firing { op: current, .. }) if current == op)
2312 }) else {
2313 return;
2314 };
2315 let Some(mut cell) = self.cells.remove(&id) else {
2316 return;
2317 };
2318 let Some(AlarmState::Firing {
2319 at_ms,
2320 generation,
2321 covered,
2322 ..
2323 }) = cell.alarm
2324 else {
2325 self.cells.insert(id, cell);
2326 return;
2327 };
2328 match result {
2329 Ok((at_ms, covered)) => {
2330 // Leave the fired alarm in place for `alarm_observed` to
2331 // replace: it assigns unconditionally, and it compares against
2332 // what was there to decide whether the bucket entry has to
2333 // follow. Clearing it here first makes a consumed alarm look
2334 // like it was never armed, and the entry is never deleted.
2335 self.cells.insert(id.clone(), cell);
2336 self.alarm_observed(&id, at_ms, covered, now_ms, now_mono_ms, effects);
2337 }
2338 Err(_) => {
2339 cell.alarm = Some(AlarmState::Armed {
2340 at_ms,
2341 generation,
2342 covered,
2343 });
2344 self.cells.insert(id.clone(), cell);
2345 effects.push(Effect::ScheduleTimer {
2346 timer: Timer::CellAlarm {
2347 cell: id,
2348 generation,
2349 },
2350 at_mono_ms: now_mono_ms.saturating_add(500),
2351 });
2352 }
2353 }
2354 }
2355
2356 fn fence_node(&mut self, effects: &mut Vec<Effect>) {
2357 self.node_authority = NodeAuthority::Fenced;
2358 self.fence(effects);
2359 effects.push(Effect::Halt {
2360 code: 3,
2361 reason: HaltReason::NodeLeaseExpired,
2362 });
2363 }
2364
2365 fn lazy_node_lease_spec(&self) -> Option<NodeLeaseSpec> {
2366 match &self.node_authority {
2367 NodeAuthority::Lapsed(spec) if spec.mode == NodeLeaseMode::Lazy => Some(spec.clone()),
2368 NodeAuthority::Reading { pending, .. } | NodeAuthority::Writing { pending, .. }
2369 if pending.prior.is_none() && pending.spec.mode == NodeLeaseMode::Lazy =>
2370 {
2371 Some(pending.spec.clone())
2372 }
2373 _ => None,
2374 }
2375 }
2376
2377 fn request(
2378 &mut self,
2379 request: RequestId,
2380 id: CellId,
2381 now_ms: u64,
2382 capacity_handoff: bool,
2383 effects: &mut Vec<Effect>,
2384 ) {
2385 if self.request_cells.contains_key(&request)
2386 || self.node_lease_waiters.contains_key(&request)
2387 {
2388 return;
2389 }
2390 if self.fenced {
2391 effects.push(Effect::Complete {
2392 request,
2393 result: Err(RequestError::NodeFenced),
2394 });
2395 return;
2396 }
2397 if capacity_handoff {
2398 self.capacity_requests.insert(request);
2399 }
2400 if self.node_authoritative() {
2401 self.request_authorized(request, id, effects);
2402 return;
2403 }
2404 if let Some(spec) = self.lazy_node_lease_spec() {
2405 self.node_lease_waiters.insert(request, id);
2406 if matches!(self.node_authority, NodeAuthority::Lapsed(_)) {
2407 self.begin_node_lease_acquisition(now_ms, spec, effects);
2408 }
2409 } else {
2410 effects.push(Effect::Complete {
2411 request,
2412 result: Err(RequestError::NodeUnavailable),
2413 });
2414 }
2415 }
2416
2417 fn drain_node_lease_waiters(&mut self, effects: &mut Vec<Effect>) {
2418 let requests = std::mem::take(&mut self.node_lease_waiters);
2419 for (request, cell) in requests {
2420 self.request_authorized(request, cell, effects);
2421 }
2422 let wakes = std::mem::take(&mut self.node_wake_waiters);
2423 for cell in wakes {
2424 self.wake_hint_authorized(cell, effects);
2425 }
2426 }
2427
2428 fn request_authorized(&mut self, request: RequestId, id: CellId, effects: &mut Vec<Effect>) {
2429 let mut cell = self.cells.remove(&id).unwrap_or_default();
2430 match &cell.phase {
2431 Phase::Resident { .. } => {
2432 self.complete_request(&id, request, Ok(Route::Local), effects)
2433 }
2434 Phase::EnsuringDurability { op, epoch } => {
2435 // The runtime is still published, so a new request wins the
2436 // race with voluntary eviction. Retiring the operation makes
2437 // its eventual durability completion harmless. The permit
2438 // taken at nomination comes back with the rescue: leaked, it
2439 // counts against `max_evictions` forever and eventually
2440 // stands every future eviction down.
2441 let epoch = *epoch;
2442 self.cell_ops.remove(op);
2443 set_phase(&mut self.occupied, &mut cell, Phase::Resident { epoch });
2444 self.eviction_permits.remove(&id);
2445 self.complete_request(&id, request, Ok(Route::Local), effects);
2446 }
2447 Phase::Remote {
2448 node,
2449 addr,
2450 epoch,
2451 peer_protocol,
2452 ..
2453 } => effects.push(Effect::Complete {
2454 request,
2455 result: Ok(Route::Remote {
2456 node: node.clone(),
2457 addr: addr.clone(),
2458 epoch: *epoch,
2459 peer_protocol: *peer_protocol,
2460 }),
2461 }),
2462 Phase::Fenced => effects.push(Effect::Complete {
2463 request,
2464 result: Err(RequestError::NodeFenced),
2465 }),
2466 phase => {
2467 cell.requests.insert(request);
2468 self.request_cells.insert(request, id.clone());
2469 match phase {
2470 Phase::Inactive => {
2471 self.admit_or_queue_activation(
2472 &id,
2473 &mut cell,
2474 ColdStart::ReadOwner,
2475 effects,
2476 );
2477 }
2478 Phase::Dormant { epoch } => {
2479 let epoch = *epoch;
2480 self.admit_or_queue_activation(
2481 &id,
2482 &mut cell,
2483 ColdStart::Restore(RestoreSpec {
2484 epoch,
2485 fresh: false,
2486 took_over: false,
2487 resume_local: false,
2488 }),
2489 effects,
2490 );
2491 }
2492 _ => {}
2493 }
2494 }
2495 }
2496 self.cells.insert(id, cell);
2497 }
2498
2499 fn wake_hint(&mut self, id: CellId, now_ms: u64, effects: &mut Vec<Effect>) {
2500 if self.fenced {
2501 return;
2502 }
2503 if self.node_authoritative() {
2504 self.wake_hint_authorized(id, effects);
2505 return;
2506 }
2507 if let Some(spec) = self.lazy_node_lease_spec() {
2508 self.node_wake_waiters.insert(id);
2509 if matches!(self.node_authority, NodeAuthority::Lapsed(_)) {
2510 self.begin_node_lease_acquisition(now_ms, spec, effects);
2511 }
2512 }
2513 }
2514
2515 fn wake_hint_authorized(&mut self, id: CellId, effects: &mut Vec<Effect>) {
2516 let mut cell = self.cells.remove(&id).unwrap_or_default();
2517 cell.alarm_wake = true;
2518 match cell.phase {
2519 Phase::Inactive | Phase::Remote { .. } => {
2520 self.admit_or_queue_activation(&id, &mut cell, ColdStart::ReadOwner, effects);
2521 }
2522 Phase::Dormant { epoch } => self.admit_or_queue_activation(
2523 &id,
2524 &mut cell,
2525 ColdStart::Restore(RestoreSpec {
2526 epoch,
2527 fresh: false,
2528 took_over: false,
2529 resume_local: false,
2530 }),
2531 effects,
2532 ),
2533 _ => {}
2534 }
2535 self.cells.insert(id, cell);
2536 }
2537
2538 fn cancel(&mut self, request: RequestId) {
2539 self.capacity_requests.remove(&request);
2540 if self.node_lease_waiters.remove(&request).is_some() {
2541 return;
2542 }
2543 let Some(id) = self.request_cells.remove(&request) else {
2544 return;
2545 };
2546 let Some(cell) = self.cells.get_mut(&id) else {
2547 return;
2548 };
2549 cell.requests.remove(&request);
2550 if cell.requests.is_empty() && !cell.alarm_wake && cell.phase == Phase::WaitingActivation {
2551 let start = cell.waiting_activation.take();
2552 set_phase(
2553 &mut self.occupied,
2554 cell,
2555 match start {
2556 Some(ColdStart::Restore(spec)) => Phase::Dormant { epoch: spec.epoch },
2557 _ => Phase::Inactive,
2558 },
2559 );
2560 self.activation_waiters.retain(|queued| queued != &id);
2561 } else if cell.requests.is_empty()
2562 && !cell.alarm_wake
2563 && cell.phase == Phase::WaitingCapacity
2564 {
2565 let activation = cell.waiting_for.take();
2566 set_phase(
2567 &mut self.occupied,
2568 cell,
2569 match activation {
2570 Some(Activation::Restore(spec)) => Phase::Dormant { epoch: spec.epoch },
2571 _ => Phase::Inactive,
2572 },
2573 );
2574 self.capacity_waiters.retain(|queued| queued != &id);
2575 }
2576 }
2577
2578 /// Retire cold work that cannot contribute to a clean local reload.
2579 ///
2580 /// Published runtimes remain untouched. The shell drains their active
2581 /// turns before it snapshots the resident inventory. A restore has no
2582 /// runtime to preserve, and it can legitimately outlive every caller, so
2583 /// waiting for it would make one cold cell disable local reuse for the
2584 /// complete node. Retire those phases and fail their callers. A later
2585 /// completion is ignored because its operation is no longer current.
2586 fn begin_preserve(&mut self, effects: &mut Vec<Effect>) {
2587 self.activation_waiters.clear();
2588 self.capacity_waiters.clear();
2589 for (request, _) in std::mem::take(&mut self.node_lease_waiters) {
2590 effects.push(Effect::Complete {
2591 request,
2592 result: Err(RequestError::NodeFenced),
2593 });
2594 }
2595 self.node_wake_waiters.clear();
2596
2597 let ids: Vec<CellId> = self.cells.keys().cloned().collect();
2598 for id in ids {
2599 let mut cell = self.cells.remove(&id).expect("id came from map");
2600 let fallback = match &cell.phase {
2601 Phase::WaitingActivation => match cell.waiting_activation.as_ref() {
2602 Some(ColdStart::Restore(spec)) => Some(Phase::Dormant { epoch: spec.epoch }),
2603 _ => Some(Phase::Inactive),
2604 },
2605 Phase::ReadingOwner { .. }
2606 | Phase::ReadingNodeLease { .. }
2607 | Phase::ReadingCapacity { .. }
2608 | Phase::Acquiring { .. }
2609 | Phase::ReconcilingAcquire { .. } => Some(Phase::Inactive),
2610 Phase::WaitingCapacity => match cell.waiting_for.as_ref() {
2611 Some(Activation::Restore(spec)) => Some(Phase::Dormant { epoch: spec.epoch }),
2612 _ => Some(Phase::Inactive),
2613 },
2614 Phase::Restoring { spec, .. } => Some(Phase::Dormant { epoch: spec.epoch }),
2615 _ => None,
2616 };
2617 if let Some(fallback) = fallback {
2618 if let Some(stale) = phase_op(&cell.phase) {
2619 self.cell_ops.remove(&stale);
2620 }
2621 self.finish_requests(&id, &mut cell, Err(RequestError::NodeFenced), effects);
2622 set_phase(&mut self.occupied, &mut cell, fallback);
2623 cell.waiting_for = None;
2624 cell.waiting_activation = None;
2625 cell.alarm_wake = false;
2626 cell.resume_demand = false;
2627 self.resuming_cells.remove(&id);
2628 }
2629 self.cells.insert(id, cell);
2630 }
2631 if self.resuming_cells.is_empty() {
2632 self.resuming = false;
2633 }
2634 self.activation_permits.retain(|id| {
2635 self.cells
2636 .get(id)
2637 .is_some_and(|cell| phase_holds_activation(&cell.phase))
2638 });
2639 self.capacity_requests
2640 .retain(|request| self.request_cells.contains_key(request));
2641 }
2642
2643 fn begin_capacity_lookup(
2644 &mut self,
2645 id: &str,
2646 cell: &mut Cell,
2647 claim: Claim,
2648 effects: &mut Vec<Effect>,
2649 ) {
2650 let op = self.cell_op(id);
2651 set_phase(
2652 &mut self.occupied,
2653 cell,
2654 Phase::ReadingCapacity {
2655 op,
2656 claim: claim.clone(),
2657 },
2658 );
2659 effects.push(Effect::ReadCapacityPeers {
2660 op,
2661 cell: id.to_string(),
2662 });
2663 }
2664
2665 /// Place a genuinely unowned cell. Ordinary ingress may look for fleet
2666 /// capacity before waiting locally; a capacity handoff must either reserve
2667 /// a real local slot now or explicitly refuse so its caller can traverse.
2668 fn place_unowned(
2669 &mut self,
2670 id: &str,
2671 cell: &mut Cell,
2672 claim: Claim,
2673 effects: &mut Vec<Effect>,
2674 ) {
2675 if self.has_capacity() {
2676 self.activate_or_wait(id, cell, Activation::Claim(claim), effects);
2677 return;
2678 }
2679
2680 let handoffs: Vec<RequestId> = cell
2681 .requests
2682 .iter()
2683 .copied()
2684 .filter(|request| self.capacity_requests.contains(request))
2685 .collect();
2686 for request in handoffs {
2687 cell.requests.remove(&request);
2688 self.request_cells.remove(&request);
2689 self.complete_request(id, request, Err(RequestError::CapacityExhausted), effects);
2690 }
2691
2692 if cell.requests.is_empty() || !self.config.require_node_lease {
2693 // Alarm wakes cannot be proxied as an HTTP capacity handoff. They
2694 // retain the old local wait semantics until alarm dispatch itself
2695 // has a fleet transport effect. Lease-disabled mode likewise has
2696 // no authoritative fleet membership to enumerate.
2697 self.activate_or_wait(id, cell, Activation::Claim(claim), effects);
2698 } else {
2699 self.begin_capacity_lookup(id, cell, claim, effects);
2700 }
2701 }
2702
2703 fn owner_read(
2704 &mut self,
2705 op: OpId,
2706 now_ms: u64,
2707 result: Result<Option<OwnerRecord>, Failure>,
2708 effects: &mut Vec<Effect>,
2709 ) {
2710 let Some(id) = self.take_cell_op(op, |cell| {
2711 matches!(
2712 cell.phase,
2713 Phase::ReadingOwner { op: current }
2714 | Phase::ReconcilingAcquire { op: current, .. }
2715 if current == op
2716 )
2717 }) else {
2718 return;
2719 };
2720 let mut cell = self.cells.remove(&id).expect("cell found above");
2721 let reconciling_claim = match &cell.phase {
2722 Phase::ReconcilingAcquire { claim, .. } => Some(claim.clone()),
2723 _ => None,
2724 };
2725 // A reconcile re-reads and then acquires again: one attempt
2726 // continuing, not a new one. The count has to survive the round trip
2727 // or the bound below can never be reached.
2728 let reconciles = reconciling_claim
2729 .as_ref()
2730 .map_or(0, |claim| claim.reconciles);
2731 match result {
2732 Ok(Some(record))
2733 if reconciling_claim.as_ref().is_some_and(|claim| {
2734 record.node.as_deref() == Some(self.node.as_str())
2735 && record.epoch == claim.epoch
2736 }) =>
2737 {
2738 let spec = RestoreSpec {
2739 epoch: record.epoch,
2740 fresh: matches!(
2741 reconciling_claim.as_ref().map(|claim| &claim.guard),
2742 Some(CasGuard::Absent)
2743 ),
2744 took_over: reconciling_claim
2745 .as_ref()
2746 .is_some_and(|claim| claim.takeover),
2747 resume_local: false,
2748 };
2749 self.record_acquisition(&spec);
2750 self.activate_or_wait(&id, &mut cell, Activation::Restore(spec), effects);
2751 }
2752 Ok(Some(record)) if record.node.as_deref() == Some(self.node.as_str()) => {
2753 let epoch = record.epoch.saturating_add(1);
2754 self.activate_or_wait(
2755 &id,
2756 &mut cell,
2757 Activation::Claim(Claim {
2758 guard: CasGuard::Match(record.etag),
2759 epoch,
2760 takeover: false,
2761 reconciles,
2762 }),
2763 effects,
2764 );
2765 }
2766 Ok(Some(record)) if record.node.is_none() => {
2767 let epoch = record.epoch.saturating_add(1);
2768 self.place_unowned(
2769 &id,
2770 &mut cell,
2771 Claim {
2772 guard: CasGuard::Match(record.etag),
2773 epoch,
2774 takeover: true,
2775 reconciles,
2776 },
2777 effects,
2778 );
2779 }
2780 Ok(Some(record)) => {
2781 let owner = record.node.clone().expect("foreign owner checked above");
2782 let cached = self
2783 .node_lease_cache
2784 .get(&owner)
2785 .filter(|lease| lease.expires_ms > now_ms && !lease.addr.is_empty())
2786 .cloned();
2787 if let Some(lease) = cached {
2788 self.apply_node_lease_result(
2789 &id,
2790 &mut cell,
2791 record,
2792 now_ms,
2793 Ok(Some(lease)),
2794 effects,
2795 );
2796 } else {
2797 self.node_lease_cache.remove(&owner);
2798 let next = self.cell_op(&id);
2799 set_phase(
2800 &mut self.occupied,
2801 &mut cell,
2802 Phase::ReadingNodeLease {
2803 op: next,
2804 owner: record,
2805 },
2806 );
2807 effects.push(Effect::ReadNodeLease {
2808 op: next,
2809 cell: id.clone(),
2810 owner,
2811 });
2812 }
2813 }
2814 Ok(None) => {
2815 self.place_unowned(
2816 &id,
2817 &mut cell,
2818 Claim {
2819 guard: CasGuard::Absent,
2820 epoch: 1,
2821 takeover: false,
2822 reconciles,
2823 },
2824 effects,
2825 );
2826 }
2827 Err(_) => {
2828 set_phase(&mut self.occupied, &mut cell, Phase::Inactive);
2829 self.finish_requests(&id, &mut cell, Err(RequestError::ResolveFailed), effects);
2830 }
2831 }
2832 self.cells.insert(id, cell);
2833 if reconciling_claim.is_some() {
2834 self.pump_capacity(effects);
2835 }
2836 }
2837
2838 fn node_lease_read(
2839 &mut self,
2840 op: OpId,
2841 now_ms: u64,
2842 result: Result<Option<NodeLeaseRecord>, Failure>,
2843 effects: &mut Vec<Effect>,
2844 ) {
2845 let Some(id) = self.take_cell_op(op, |cell| {
2846 matches!(cell.phase, Phase::ReadingNodeLease { op: current, .. } if current == op)
2847 }) else {
2848 return;
2849 };
2850 let mut cell = self.cells.remove(&id).expect("cell found above");
2851 let Phase::ReadingNodeLease { owner: record, .. } = &cell.phase else {
2852 unreachable!()
2853 };
2854 let record = record.clone();
2855 if let Ok(Some(lease)) = &result {
2856 if record.node.as_deref() == Some(lease.node.as_str())
2857 && lease.expires_ms > now_ms
2858 && !lease.addr.is_empty()
2859 {
2860 self.node_lease_cache
2861 .insert(lease.node.clone(), lease.clone());
2862 }
2863 }
2864 self.apply_node_lease_result(&id, &mut cell, record, now_ms, result, effects);
2865 self.cells.insert(id, cell);
2866 }
2867
2868 fn capacity_peers_read(
2869 &mut self,
2870 op: OpId,
2871 now_ms: u64,
2872 result: Result<Vec<CapacityPeer>, Failure>,
2873 effects: &mut Vec<Effect>,
2874 ) {
2875 let Some(id) = self.take_cell_op(op, |cell| {
2876 matches!(cell.phase, Phase::ReadingCapacity { op: current, .. } if current == op)
2877 }) else {
2878 return;
2879 };
2880 let mut cell = self.cells.remove(&id).expect("cell found above");
2881 let Phase::ReadingCapacity { claim, .. } = &cell.phase else {
2882 unreachable!()
2883 };
2884 let claim = claim.clone();
2885 let peers = match result {
2886 Ok(peers) => peers,
2887 Err(_) => {
2888 self.activate_or_wait(&id, &mut cell, Activation::Claim(claim), effects);
2889 self.cells.insert(id, cell);
2890 return;
2891 }
2892 };
2893
2894 // A newer load sample supersedes both reservations made against and
2895 // refusals of the prior sample. Equal samples deliberately retain
2896 // both, which is what makes concurrent read completions compose.
2897 for peer in &peers {
2898 let prior = self.capacity_samples.get(&peer.node).copied().unwrap_or(0);
2899 if peer.sampled_ms > prior {
2900 self.capacity_samples
2901 .insert(peer.node.clone(), peer.sampled_ms);
2902 self.capacity_reservations.remove(&peer.node);
2903 self.capacity_rejections.remove(&peer.node);
2904 }
2905 }
2906
2907 let selected = peers
2908 .into_iter()
2909 .filter(|peer| {
2910 peer.node != self.node
2911 && peer.expires_ms > now_ms
2912 && !peer.addr.is_empty()
2913 && peer.peer_protocol == self.config.peer_protocol
2914 && peer.sampled_ms != 0
2915 && !peer.pressured
2916 && self
2917 .capacity_rejections
2918 .get(&peer.node)
2919 .is_none_or(|sample| peer.sampled_ms > *sample)
2920 })
2921 .map(|peer| {
2922 let projected = peer.resident_cells.saturating_add(
2923 self.capacity_reservations
2924 .get(&peer.node)
2925 .copied()
2926 .unwrap_or(0),
2927 );
2928 (peer, projected)
2929 })
2930 .min_by_key(|(peer, projected)| {
2931 // The third key is the memory the peer holds, which is what
2932 // the peer decides its own pressure on. A peer from before that
2933 // field existed reports nothing, and its resident set size is
2934 // the only number available -- which reads as more loaded than
2935 // it is, and is the conservative direction for a tiebreak.
2936 (
2937 *projected,
2938 peer.host_websockets,
2939 peer.in_use_bytes.unwrap_or(peer.rss_bytes),
2940 peer.node.clone(),
2941 )
2942 });
2943
2944 if let Some((peer, _)) = selected {
2945 *self
2946 .capacity_reservations
2947 .entry(peer.node.clone())
2948 .or_default() += 1;
2949 set_phase(
2950 &mut self.occupied,
2951 &mut cell,
2952 Phase::Remote {
2953 node: peer.node.clone(),
2954 addr: peer.addr.clone(),
2955 epoch: 0,
2956 peer_protocol: peer.peer_protocol,
2957 capacity_sampled_ms: Some(peer.sampled_ms),
2958 },
2959 );
2960 self.finish_requests(
2961 &id,
2962 &mut cell,
2963 Ok(Route::Remote {
2964 node: peer.node,
2965 addr: peer.addr,
2966 epoch: 0,
2967 peer_protocol: peer.peer_protocol,
2968 }),
2969 effects,
2970 );
2971 } else {
2972 self.activate_or_wait(&id, &mut cell, Activation::Claim(claim), effects);
2973 }
2974 self.cells.insert(id, cell);
2975 }
2976
2977 fn apply_node_lease_result(
2978 &mut self,
2979 id: &str,
2980 cell: &mut Cell,
2981 record: OwnerRecord,
2982 now_ms: u64,
2983 result: Result<Option<NodeLeaseRecord>, Failure>,
2984 effects: &mut Vec<Effect>,
2985 ) {
2986 match result {
2987 Ok(Some(lease))
2988 if lease.expires_ms > now_ms
2989 && !lease.addr.is_empty()
2990 && record.node.as_deref() == Some(lease.node.as_str())
2991 && lease.peer_protocol != self.config.peer_protocol =>
2992 {
2993 set_phase(&mut self.occupied, cell, Phase::Inactive);
2994 self.finish_requests(id, cell, Err(RequestError::PeerIncompatible), effects);
2995 }
2996 Ok(Some(lease))
2997 if lease.expires_ms > now_ms
2998 && !lease.addr.is_empty()
2999 && record.node.as_deref() == Some(lease.node.as_str())
3000 && lease.peer_protocol == self.config.peer_protocol =>
3001 {
3002 let node = lease.node;
3003 let addr = lease.addr;
3004 let epoch = record.epoch;
3005 set_phase(
3006 &mut self.occupied,
3007 cell,
3008 Phase::Remote {
3009 node: node.clone(),
3010 addr: addr.clone(),
3011 epoch,
3012 peer_protocol: lease.peer_protocol,
3013 capacity_sampled_ms: None,
3014 },
3015 );
3016 self.finish_requests(
3017 id,
3018 cell,
3019 Ok(Route::Remote {
3020 node,
3021 addr,
3022 epoch,
3023 peer_protocol: lease.peer_protocol,
3024 }),
3025 effects,
3026 );
3027 }
3028 Ok(_) => {
3029 let epoch = record.epoch.saturating_add(1);
3030 self.activate_or_wait(
3031 id,
3032 cell,
3033 Activation::Claim(Claim {
3034 guard: CasGuard::Match(record.etag),
3035 epoch,
3036 takeover: true,
3037 reconciles: 0,
3038 }),
3039 effects,
3040 );
3041 }
3042 Err(_) => {
3043 set_phase(&mut self.occupied, cell, Phase::Inactive);
3044 self.finish_requests(id, cell, Err(RequestError::ResolveFailed), effects);
3045 }
3046 }
3047 }
3048
3049 fn owner_cas_completed(
3050 &mut self,
3051 op: OpId,
3052 result: Result<CasOutcome, Failure>,
3053 effects: &mut Vec<Effect>,
3054 ) {
3055 let Some(id) = self.take_cell_op(
3056 op,
3057 |cell| matches!(cell.phase, Phase::Acquiring { op: current, .. } if current == op),
3058 ) else {
3059 return;
3060 };
3061 let mut cell = self.cells.remove(&id).expect("cell found above");
3062 let Phase::Acquiring { claim, .. } = &cell.phase else {
3063 unreachable!()
3064 };
3065 let claim = claim.clone();
3066 match result {
3067 Ok(CasOutcome::Applied) => {
3068 let next = self.cell_op(&id);
3069 let spec = RestoreSpec {
3070 epoch: claim.epoch,
3071 fresh: matches!(claim.guard, CasGuard::Absent),
3072 took_over: claim.takeover,
3073 resume_local: false,
3074 };
3075 self.record_acquisition(&spec);
3076 set_phase(
3077 &mut self.occupied,
3078 &mut cell,
3079 Phase::Restoring {
3080 op: next,
3081 spec: spec.clone(),
3082 },
3083 );
3084 effects.push(Effect::Restore {
3085 op: next,
3086 cell: id.clone(),
3087 spec,
3088 });
3089 }
3090 Ok(CasOutcome::Rejected) => {
3091 let next = self.cell_op(&id);
3092 set_phase(
3093 &mut self.occupied,
3094 &mut cell,
3095 Phase::ReadingOwner { op: next },
3096 );
3097 effects.push(Effect::ReadOwner {
3098 op: next,
3099 cell: id.clone(),
3100 });
3101 }
3102 Err(Failure::Ambiguous) if claim.reconciles < MAX_ACQUIRE_RECONCILES => {
3103 let next = self.cell_op(&id);
3104 let claim = Claim {
3105 reconciles: claim.reconciles + 1,
3106 ..claim
3107 };
3108 set_phase(
3109 &mut self.occupied,
3110 &mut cell,
3111 Phase::ReconcilingAcquire { op: next, claim },
3112 );
3113 effects.push(Effect::ReadOwner {
3114 op: next,
3115 cell: id.clone(),
3116 });
3117 }
3118 Err(Failure::Ambiguous) => {
3119 // Out of reconciles. The claim may or may not have applied, so
3120 // this cell is left dormant for a later request to resolve
3121 // from the record rather than guessed at here.
3122 set_phase(&mut self.occupied, &mut cell, Phase::Inactive);
3123 self.finish_requests(&id, &mut cell, Err(RequestError::AcquireFailed), effects);
3124 }
3125 Err(Failure::Definite) => {
3126 set_phase(&mut self.occupied, &mut cell, Phase::Inactive);
3127 self.finish_requests(&id, &mut cell, Err(RequestError::AcquireFailed), effects);
3128 }
3129 }
3130 self.cells.insert(id, cell);
3131 self.pump_capacity(effects);
3132 }
3133
3134 fn restore_completed(
3135 &mut self,
3136 op: OpId,
3137 result: Result<RestoreOutcome, Failure>,
3138 effects: &mut Vec<Effect>,
3139 ) {
3140 let Some(id) = self.take_cell_op(
3141 op,
3142 |cell| matches!(cell.phase, Phase::Restoring { op: current, .. } if current == op),
3143 ) else {
3144 return;
3145 };
3146 let mut cell = self.cells.remove(&id).expect("cell found above");
3147 let Phase::Restoring { spec, .. } = &cell.phase else {
3148 unreachable!()
3149 };
3150 let epoch = spec.epoch;
3151 let mut resume_failed = false;
3152 match result {
3153 Ok(outcome) => {
3154 if outcome.restored {
3155 self.activity.restored = self.activity.restored.saturating_add(1);
3156 }
3157 // Seed the mirror from the durable truth the restore loaded,
3158 // before the isolate opens the same database and long before
3159 // it would re-arm anything.
3160 if let Some(alarm) = outcome.alarm.filter(|alarm| alarm.at_ms >= 0) {
3161 let generation = self.next_timer_generation;
3162 self.next_timer_generation = self
3163 .next_timer_generation
3164 .checked_add(1)
3165 .expect("timer generation exhausted");
3166 let (now_ms, now_mono_ms) = (self.now_ms, self.now_mono_ms);
3167 self.schedule_alarm_timer(
3168 &id,
3169 generation,
3170 alarm.at_ms,
3171 now_ms,
3172 now_mono_ms,
3173 effects,
3174 );
3175 cell.alarm = Some(AlarmState::Armed {
3176 at_ms: alarm.at_ms,
3177 generation,
3178 covered: alarm.covered,
3179 });
3180 }
3181 let next = self.cell_op(&id);
3182 set_phase(
3183 &mut self.occupied,
3184 &mut cell,
3185 Phase::Starting { op: next, epoch },
3186 );
3187 effects.push(Effect::StartRuntime {
3188 op: next,
3189 cell: id.clone(),
3190 epoch,
3191 });
3192 }
3193 Err(_) => {
3194 set_phase(&mut self.occupied, &mut cell, Phase::Dormant { epoch });
3195 self.finish_requests(&id, &mut cell, Err(RequestError::RestoreFailed), effects);
3196 resume_failed = cell.resume_demand;
3197 }
3198 }
3199 self.cells.insert(id.clone(), cell);
3200 if resume_failed {
3201 self.settle_local_resume(&id);
3202 }
3203 self.pump_capacity(effects);
3204 }
3205
3206 fn runtime_started(
3207 &mut self,
3208 op: OpId,
3209 result: Result<(), Failure>,
3210 effects: &mut Vec<Effect>,
3211 ) {
3212 let Some(id) = self.take_cell_op(
3213 op,
3214 |cell| matches!(cell.phase, Phase::Starting { op: current, .. } if current == op),
3215 ) else {
3216 self.compensate_retired_runtime(op, result, effects);
3217 return;
3218 };
3219 let mut cell = self.cells.remove(&id).expect("cell found above");
3220 let Phase::Starting { epoch, .. } = cell.phase else {
3221 unreachable!()
3222 };
3223 let mut resume_failed = false;
3224 match result {
3225 Ok(()) => {
3226 let next = self.cell_op(&id);
3227 set_phase(
3228 &mut self.occupied,
3229 &mut cell,
3230 Phase::Publishing { op: next, epoch },
3231 );
3232 effects.push(Effect::Publish {
3233 op: next,
3234 cell: id.clone(),
3235 epoch,
3236 });
3237 }
3238 Err(_) => {
3239 set_phase(&mut self.occupied, &mut cell, Phase::Dormant { epoch });
3240 self.finish_requests(&id, &mut cell, Err(RequestError::RuntimeFailed), effects);
3241 resume_failed = cell.resume_demand;
3242 }
3243 }
3244 self.cells.insert(id.clone(), cell);
3245 if resume_failed {
3246 self.settle_local_resume(&id);
3247 }
3248 self.pump_capacity(effects);
3249 }
3250
3251 fn published(&mut self, op: OpId, result: Result<(), Failure>, effects: &mut Vec<Effect>) {
3252 let Some(id) = self.take_cell_op(
3253 op,
3254 |cell| matches!(cell.phase, Phase::Publishing { op: current, .. } if current == op),
3255 ) else {
3256 self.compensate_retired_runtime(op, result, effects);
3257 return;
3258 };
3259 let mut cell = self.cells.remove(&id).expect("cell found above");
3260 let Phase::Publishing { epoch, .. } = cell.phase else {
3261 unreachable!()
3262 };
3263 let completing_resume = cell.resume_demand;
3264 match result {
3265 Ok(()) => {
3266 set_phase(&mut self.occupied, &mut cell, Phase::Resident { epoch });
3267 self.finish_requests(&id, &mut cell, Ok(Route::Local), effects);
3268 }
3269 Err(_) => {
3270 let next = self.cell_op(&id);
3271 set_phase(
3272 &mut self.occupied,
3273 &mut cell,
3274 Phase::Cleaning {
3275 op: next,
3276 epoch,
3277 cause: StopCause::Cleanup,
3278 },
3279 );
3280 effects.push(Effect::StopRuntime {
3281 op: next,
3282 cell: id.clone(),
3283 epoch,
3284 cause: StopCause::Cleanup,
3285 });
3286 }
3287 }
3288 self.cells.insert(id.clone(), cell);
3289 if completing_resume {
3290 self.settle_local_resume(&id);
3291 }
3292 }
3293
3294 /// A release either published the cell as unowned or did not. Ownership
3295 /// is the bucket's answer, not this node's, so a rejected or failed write
3296 /// simply leaves the record naming this node -- correct, if less useful,
3297 /// and the next eviction gets another chance.
3298 fn owner_released(&mut self, op: OpId, result: Result<CasOutcome, Failure>) {
3299 let Some(id) = self.take_cell_op(op, |cell| cell.releasing == Some(op)) else {
3300 return;
3301 };
3302 let cell = self.cells.get_mut(&id).expect("cell found above");
3303 cell.releasing = None;
3304 // Only a cell still sitting where the eviction left it may be
3305 // forgotten. Anything else means it was wanted again while the write
3306 // was in flight, and that claim outranks a release decided earlier.
3307 // On a draining node a rejection settles the cell too: the record no
3308 // longer names this node at this epoch, so nothing here blocks a
3309 // successor, and the pump must not re-read a record it can never
3310 // blank. An indefinite failure stays `Dormant`, which is what makes
3311 // the pump retry it while the drain window is open.
3312 let settled = matches!(result, Ok(CasOutcome::Applied))
3313 || (self.draining && matches!(result, Ok(CasOutcome::Rejected)));
3314 if settled && matches!(cell.phase, Phase::Dormant { .. }) {
3315 set_phase(&mut self.occupied, cell, Phase::Inactive);
3316 }
3317 }
3318
3319 fn runtime_stopped(&mut self, op: OpId, effects: &mut Vec<Effect>) {
3320 let Some(id) = self.take_cell_op(
3321 op,
3322 |cell| matches!(cell.phase, Phase::Cleaning { op: current, .. } if current == op),
3323 ) else {
3324 return;
3325 };
3326 let mut cell = self.cells.remove(&id).expect("cell found above");
3327 let Phase::Cleaning { epoch, cause, .. } = cell.phase else {
3328 unreachable!()
3329 };
3330 match cause {
3331 StopCause::Cleanup => {
3332 set_phase(&mut self.occupied, &mut cell, Phase::Dormant { epoch });
3333 self.finish_requests(&id, &mut cell, Err(RequestError::PublishFailed), effects);
3334 }
3335 // `Inactive`, not `Dormant`: the next request re-reads the
3336 // ownership record. A proof that could not be completed is exactly
3337 // the moment to stop assuming this node still holds the cell, and
3338 // the re-read costs one GET on a path that was already failing.
3339 StopCause::Reset => {
3340 set_phase(&mut self.occupied, &mut cell, Phase::Inactive);
3341 if let Some(AlarmState::Firing { op, .. }) = cell.alarm {
3342 self.cell_ops.remove(&op);
3343 }
3344 cell.alarm = None;
3345 cell.alarm_wake = false;
3346 cell.websockets.clear();
3347 self.finish_requests(
3348 &id,
3349 &mut cell,
3350 Err(RequestError::DurabilityUnproven),
3351 effects,
3352 );
3353 }
3354 StopCause::Evict { rebalance } if cell.requests.is_empty() => {
3355 set_phase(&mut self.occupied, &mut cell, Phase::Dormant { epoch });
3356 self.eviction_permits.remove(&id);
3357 // The record still names this node, which is the whole cost of
3358 // stopping here: every later request for the cell routes to a
3359 // node that has already decided it has no room. Publishing it
3360 // as unowned is what turns an eviction into shed load.
3361 if rebalance {
3362 let op = self.cell_op(&id);
3363 cell.releasing = Some(op);
3364 effects.push(Effect::ReleaseOwner {
3365 op,
3366 cell: id.clone(),
3367 epoch,
3368 });
3369 }
3370 }
3371 StopCause::Evict { .. } => {
3372 // A request arrived mid-eviction, so the cell turns straight
3373 // back around. The eviction is over either way.
3374 self.eviction_permits.remove(&id);
3375 self.admit_or_queue_activation(
3376 &id,
3377 &mut cell,
3378 ColdStart::Restore(RestoreSpec {
3379 epoch,
3380 fresh: false,
3381 took_over: false,
3382 resume_local: false,
3383 }),
3384 effects,
3385 );
3386 }
3387 StopCause::Fence => unreachable!("fenced cells do not wait for runtime shutdown"),
3388 }
3389 self.cells.insert(id, cell);
3390 self.pump_capacity(effects);
3391 self.shed_toward_floor(effects);
3392 }
3393
3394 fn durability_checked(
3395 &mut self,
3396 op: OpId,
3397 result: Result<(), Failure>,
3398 effects: &mut Vec<Effect>,
3399 ) {
3400 let now = self.now_mono_ms;
3401 let Some(id) = self.take_cell_op(op, |cell| {
3402 matches!(cell.phase, Phase::EnsuringDurability { op: current, .. } if current == op)
3403 }) else {
3404 return;
3405 };
3406 let cell = self.cells.get_mut(&id).expect("cell found above");
3407 let Phase::EnsuringDurability { epoch, .. } = cell.phase else {
3408 unreachable!()
3409 };
3410 match result {
3411 Ok(()) => {
3412 // Minted inline: `cell` still borrows the map, and field
3413 // accesses split where a method call cannot.
3414 let stop = self.next_op;
3415 self.next_op = self.next_op.checked_add(1).expect("operation id exhausted");
3416 self.cell_ops.insert(stop, id.clone());
3417 let rebalance = cell.evict_rebalance;
3418 set_phase(
3419 &mut self.occupied,
3420 cell,
3421 Phase::Cleaning {
3422 op: stop,
3423 epoch,
3424 cause: StopCause::Evict { rebalance },
3425 },
3426 );
3427 effects.push(Effect::StopRuntime {
3428 op: stop,
3429 cell: id,
3430 epoch,
3431 cause: StopCause::Evict { rebalance },
3432 });
3433 }
3434 Err(_) => {
3435 set_phase(&mut self.occupied, cell, Phase::Resident { epoch });
3436 cell.eviction_refused_mono_ms = Some(now);
3437 self.eviction_permits.remove(&id);
3438 }
3439 }
3440 }
3441
3442 /// Evict on demand. Local, like an idle eviction: the caller asked
3443 /// this node to drop the cell, not to give it away.
3444 fn evict(&mut self, id: &str, effects: &mut Vec<Effect>) {
3445 self.begin_eviction(id, false, effects);
3446 }
3447
3448 /// Shutdown handoff: give every resident cell away by releasing its
3449 /// owner record, so peers take over at once instead of waiting out the
3450 /// node lease. `rebalance` is forced true, so this releases even when
3451 /// `ownership_on_evict` keeps ownership on an ordinary evict.
3452 ///
3453 /// Only marks the node draining; `pump_release` does the work, at most
3454 /// `max_releases` at a time. An unbounded walk here would start a
3455 /// durability proof per resident cell at once -- a node holding
3456 /// thousands turns its own shutdown into the restore storm the eviction
3457 /// bound exists to prevent, and trips the `validate` ceiling besides.
3458 fn release_all(&mut self, effects: &mut Vec<Effect>) {
3459 self.draining = true;
3460 self.pump_release(effects);
3461 }
3462
3463 /// The drain pump, run after every event once draining: keep
3464 /// `max_releases` handoffs in flight while any owned cell remains.
3465 /// A cell that refuses eviction now -- active, or holding an uncovered
3466 /// alarm -- is skipped and retried on a later pump, so an active cell
3467 /// is handed off the moment its activity finishes. Releases in flight
3468 /// count against the same ceiling as the proofs: the bound exists to
3469 /// keep shutdown from flooding the store, and a release is one more
3470 /// write in that flood.
3471 fn pump_release(&mut self, effects: &mut Vec<Effect>) {
3472 if !self.draining {
3473 return;
3474 }
3475 let mut in_flight = self.eviction_permits.len() + self.releasing();
3476 for id in self.residents() {
3477 if in_flight >= self.config.max_releases {
3478 return;
3479 }
3480 if self.begin_eviction(&id, true, effects) {
3481 in_flight += 1;
3482 }
3483 }
3484 // A cell evicted before the drain kept its record on this node --
3485 // a sticky eviction, hibernation, or a release whose write failed
3486 // -- so a later request could resume locally. On a leaving node
3487 // that record only makes a successor wait out the node lease. The
3488 // runtime is already stopped, so the drain releases the record
3489 // directly.
3490 let dormant: Vec<(CellId, Epoch)> = self
3491 .cells
3492 .iter()
3493 .filter_map(|(id, cell)| match cell.phase {
3494 Phase::Dormant { epoch }
3495 if cell.releasing.is_none() && cell.requests.is_empty() =>
3496 {
3497 Some((id.clone(), epoch))
3498 }
3499 _ => None,
3500 })
3501 .collect();
3502 for (id, epoch) in dormant {
3503 if in_flight >= self.config.max_releases {
3504 return;
3505 }
3506 let op = self.cell_op(&id);
3507 let cell = self.cells.get_mut(&id).expect("dormant cell listed above");
3508 cell.releasing = Some(op);
3509 effects.push(Effect::ReleaseOwner {
3510 op,
3511 cell: id,
3512 epoch,
3513 });
3514 in_flight += 1;
3515 }
3516 }
3517
3518 /// Does an eviction made for room hand the cell away?
3519 fn rebalances(&self) -> bool {
3520 self.config.ownership_on_evict == OwnershipOnEvict::Release
3521 }
3522
3523 fn begin_eviction(&mut self, id: &str, rebalance: bool, effects: &mut Vec<Effect>) -> bool {
3524 // An alarm about to fire is not worth an eviction: the wake costs
3525 // more than the residency it would save, so the cell is held even
3526 // though its entry is perfectly durable. Coverage says the alarm can
3527 // survive the eviction; this says it is not worth surviving it.
3528 let alarm_is_imminent = self.cells.get(id).is_some_and(|cell| match cell.alarm {
3529 Some(AlarmState::Armed { at_ms, .. }) | Some(AlarmState::Firing { at_ms, .. }) => {
3530 at_ms >= 0
3531 && (at_ms as u64).saturating_sub(self.now_ms) <= self.config.alarm_resident_ms
3532 }
3533 None => false,
3534 });
3535 // Only while there is room to spare. Holding a cell to save a wake is
3536 // worth it on an idle node and indefensible on a full one: the window
3537 // defaults to an hour, so on an alarm-driven workload this would hold
3538 // most of the node and pin it at its ceiling -- trading a real
3539 // admission failure for a saved activation. Under pressure the node
3540 // takes the wake.
3541 if alarm_is_imminent && !self.shedding && !self.draining {
3542 return false;
3543 }
3544 let alarm_is_safe = self.cells.get(id).is_some_and(|cell| {
3545 cell.alarm
3546 .as_ref()
3547 .is_none_or(|alarm| matches!(alarm, AlarmState::Armed { covered: true, .. }))
3548 });
3549 if !self.is_hibernatable(id) || !alarm_is_safe {
3550 return false;
3551 }
3552 let Some(Phase::Resident { epoch }) = self.cells.get(id).map(|cell| &cell.phase) else {
3553 return false;
3554 };
3555 let epoch = *epoch;
3556 let op = self.cell_op(id);
3557 let Some(cell) = self.cells.get_mut(id) else {
3558 return false;
3559 };
3560 cell.evict_rebalance = rebalance;
3561 set_phase(
3562 &mut self.occupied,
3563 cell,
3564 Phase::EnsuringDurability { op, epoch },
3565 );
3566 self.eviction_permits.insert(id.to_string());
3567 effects.push(Effect::EnsureDurable {
3568 op,
3569 cell: id.to_string(),
3570 epoch,
3571 });
3572 true
3573 }
3574
3575 fn shed_one(&mut self, effects: &mut Vec<Effect>) {
3576 // Only when the blocker is headroom. A latched node is already walking
3577 // down on its own schedule, and admission stays closed until it
3578 // reaches the low watermark -- so shedding to make room for a waiter
3579 // that cannot be admitted has no stopping condition, and every
3580 // completed eviction re-enters here through `pump_capacity` and starts
3581 // another. That empties the node.
3582 //
3583 // Count the evictions already in flight against the waiters: this is
3584 // reachable from every activity finish and websocket close, and a
3585 // waiter whose eviction is already under way must not turn each of
3586 // those triggers into another victim. Spend the cut on commit, never
3587 // on nomination.
3588 if self.shedding
3589 || self.capacity_waiters.len() <= self.eviction_permits.len()
3590 || self.eviction_permits.len() >= self.config.max_evictions
3591 {
3592 return;
3593 }
3594 if let Some(victim) = self.shed_candidate() {
3595 self.begin_eviction(&victim, self.rebalances(), effects);
3596 }
3597 }
3598
3599 /// The cell to shed right now: resident, idle, not holding an alarm the
3600 /// node still owes, and the least recently used of those. Demand shedding
3601 /// and pressure shedding both come through here, so they cannot disagree
3602 /// about what is safe to take or which one to take first.
3603 fn shed_candidate(&self) -> Option<CellId> {
3604 self.cells
3605 .iter()
3606 .filter(|(id, cell)| {
3607 self.is_hibernatable(id)
3608 && cell.alarm.as_ref().is_none_or(|alarm| {
3609 matches!(alarm, AlarmState::Armed { covered: true, .. })
3610 })
3611 })
3612 // Cells that have never been refused first, then by how long ago
3613 // the refusal was, then least recently used, with the id as a
3614 // tiebreak so the choice stays a function of the state and not of
3615 // map iteration order. A refused cell is still reachable -- it
3616 // just stops being the answer every time.
3617 .min_by_key(|(id, cell)| {
3618 (
3619 cell.eviction_refused_mono_ms,
3620 cell.last_used_mono_ms,
3621 (*id).clone(),
3622 )
3623 })
3624 .map(|(id, _)| id.clone())
3625 }
3626
3627 /// Release one cell that has gone cold, with nothing asking for the room.
3628 ///
3629 /// Shedding answers "this node is in trouble"; this answers the ordinary
3630 /// question of a cell nobody has touched in a long time. Without it a node
3631 /// only ever gives a cell back under pressure or when another cell wants
3632 /// the slot, so a quiet node holds every cell it ever served until it
3633 /// reaches a watermark -- paying to keep runtimes alive for traffic that
3634 /// stopped hours ago.
3635 fn evict_idle(&mut self, now_mono_ms: u64, effects: &mut Vec<Effect>) {
3636 let Some(idle_ms) = self.config.idle_evict_ms else {
3637 return;
3638 };
3639 let Some(candidate) = self.shed_candidate() else {
3640 return;
3641 };
3642 let cold = self
3643 .cells
3644 .get(&candidate)
3645 .is_some_and(|cell| now_mono_ms.saturating_sub(cell.last_used_mono_ms) >= idle_ms);
3646 if cold {
3647 // Idle eviction is a local residency decision, not a handoff.
3648 self.begin_eviction(&candidate, false, effects);
3649 }
3650 }
3651
3652 /// Fold a resource sample into the shedding latch, then act on it.
3653 ///
3654 /// The latch is the whole point. Shedding on the instantaneous crossing
3655 /// alone flaps: the eviction relieves the pressure, admission resumes, the
3656 /// ceiling is crossed again. `PressureConfig` holds the node in shedding
3657 /// until every configured low watermark clears, so the node walks down to
3658 /// its target instead of oscillating around its ceiling.
3659 fn load_sampled(&mut self, load: pressure::Load, now_mono_ms: u64, effects: &mut Vec<Effect>) {
3660 // Both latches are folded, and the reason names the more serious of the
3661 // two. The latches are state of their own: derived from the reason
3662 // instead, one crossing holds the node against the other's watermark.
3663 let (latches, reason) = self.config.pressure.classify(load, self.latches);
3664 self.latches = latches;
3665 self.shed_reason = reason;
3666 self.shedding = reason.is_some();
3667 if !self.shedding {
3668 // Relieved. Whatever was queued for capacity may proceed.
3669 self.shed_cut = None;
3670 self.pump_capacity(effects);
3671 self.evict_idle(now_mono_ms, effects);
3672 return;
3673 }
3674 // Evicting only helps if it returns memory. When the last cut has
3675 // fully landed and this sample's in-use bytes sit within 5% of what
3676 // that cut measured, another cut is futile: the latch holds -- the node
3677 // genuinely is over its ceiling, so admission stays closed -- but the
3678 // walk down stops spending the working set. Without this stopping
3679 // condition an unsatisfiable ceiling (one below the process's memory
3680 // floor) evicts a proportion of whatever remains on every sample and
3681 // walks the node to zero -- a latched walk down with no stopping
3682 // condition, the same shape as demand shedding for a waiter that can
3683 // never be admitted. A
3684 // sample that moves either way re-arms the walk down.
3685 //
3686 // The comparison reads whichever measurement the walk down works
3687 // against. The ordinary ceiling wins whenever it is latched, even if
3688 // the cap is latched too: eviction relieves the ordinary ceiling and
3689 // may do nothing at all for the cap, so reading the cap's number while
3690 // the node is genuinely over its ordinary ceiling stops the walk down
3691 // exactly when it is needed. Under the cap alone the in-use figure is
3692 // small and moves freely, so reading it there would find every sample
3693 // "not flat" and drain the working set against a condition eviction
3694 // cannot relieve.
3695 //
3696 // A change of measurement discards the baseline. The two numbers are
3697 // not comparable, and on this fleet they sit within 2% of each other,
3698 // so comparing across them finds them flat by coincidence and
3699 // suppresses every further cut.
3700 let metric = pressure::PressureConfig::walk_metric(latches);
3701 let sample_bytes = match metric {
3702 pressure::Metric::InUse => load.in_use_bytes,
3703 pressure::Metric::Rss => load.rss_bytes,
3704 };
3705 if self
3706 .shed_cut
3707 .is_some_and(|(previous, _, _)| previous != metric)
3708 {
3709 self.shed_cut = None;
3710 }
3711 if let Some((_, cut_bytes, cut_cells)) = self.shed_cut {
3712 let cut_landed = self.occupied() <= self.shed_floor && self.eviction_permits.is_empty();
3713 // Did the last cut return anything? It is only evidence if it
3714 // actually vacated cells: a walk down that has already stopped
3715 // vacates nothing, and reading that as "no progress" would make the
3716 // stop hold because it held.
3717 let removed = cut_cells.saturating_sub(self.occupied());
3718 // A tolerance, not a threshold. It absorbs the jitter of a live
3719 // sample; it does not decide how much a cut must achieve. The old
3720 // condition used 5% of the sample as a threshold, and that is the
3721 // fault: a cut can help and still move a large sample by less.
3722 let tolerance = cut_bytes / 100;
3723 let fell = sample_bytes.saturating_add(tolerance) < cut_bytes;
3724 let rose = sample_bytes > cut_bytes.saturating_add(tolerance);
3725 if cut_landed && removed > 0 && !fell && !rose {
3726 return;
3727 }
3728 }
3729 // How far this resource sample asks the node to come down: a proportion
3730 // of what was just measured, because the effect of an eviction on the
3731 // sample is not visible until the next one.
3732 self.shed_floor = pressure::PressureConfig::release_target(load.resident_cells);
3733 self.shed_cut = Some((metric, sample_bytes, load.resident_cells));
3734 self.shed_toward_floor(effects);
3735 }
3736
3737 // The walk down's stopping condition lives in `load_sampled` above: a cut
3738 // that vacated cells and did not lower the sample is futile, and the node
3739 // holds what it has rather than spending the working set on a ceiling that
3740 // eviction cannot satisfy.
3741 //
3742 // It asks whether the last cut *helped*, not whether it helped by some
3743 // percentage. The cut is a proportion of the cells and the sample includes
3744 // memory the cells do not own, so a cut that helps can still move the
3745 // sample by very little -- and stopping there leaves the node above its own
3746 // resume line with idle cells in hand, refusing every request for a cell.
3747 // That is issue #50, measured on a fleet as nine hours of exactly that, and
3748 // on one node as a walk down that stopped 14 MB short of its line.
3749
3750 /// Continue a latched walk down as each eviction lands.
3751 ///
3752 /// `shed_one` stands down while the latch is hot, because its stopping
3753 /// condition -- the waiter got in -- cannot be met until the node is
3754 /// relieved. This is the other half: a stopping condition that can be met,
3755 /// so the node reaches its floor at the speed evictions complete rather
3756 /// than one per sampling period. Serialized like every other eviction
3757 /// path, so a walk down never puts the whole working set in flight.
3758 fn shed_toward_floor(&mut self, effects: &mut Vec<Effect>) {
3759 if !self.shedding || self.occupied() <= self.shed_floor {
3760 return;
3761 }
3762 // Fill the permits rather than starting one and waiting for it. Each
3763 // proof is a round trip, so a serialized drain costs the number of
3764 // cells times that latency; running the bound's worth at once is the
3765 // difference between a walk down measured in seconds and one measured
3766 // in minutes.
3767 // Count what is already leaving against the target. `occupied` still
3768 // includes a cell whose proof is in flight, so comparing it directly
3769 // nominates cells the evictions already under way will account for,
3770 // and the node settles below its floor by up to the whole bound --
3771 // the mistake celld's eviction budget documents: spend the cut on
3772 // commit, never on nomination.
3773 while self.eviction_permits.len() < self.config.max_evictions
3774 && self.occupied().saturating_sub(self.eviction_permits.len()) > self.shed_floor
3775 {
3776 let Some(victim) = self.shed_candidate() else {
3777 return;
3778 };
3779 if !self.begin_eviction(&victim, self.rebalances(), effects) {
3780 return;
3781 }
3782 }
3783 }
3784
3785 fn activity_finished(&mut self, request: RequestId, effects: &mut Vec<Effect>) {
3786 // A write still on the output gate keeps its request pinned, so the
3787 // cell cannot be evicted before the write is proven durable. The unpin
3788 // moves to whichever path drains the last gate for this request.
3789 if self
3790 .gated_writes
3791 .values()
3792 .any(|gate| gate.request == request)
3793 {
3794 self.gate_pinned.insert(request);
3795 return;
3796 }
3797 if let Some(id) = self.deactivate_request(request) {
3798 let now = self.now_mono_ms;
3799 if let Some(cell) = self.cells.get_mut(&id) {
3800 cell.last_used_mono_ms = now;
3801 }
3802 }
3803 self.shed_one(effects);
3804 }
3805
3806 /// Open the output gate for a local write: hold its response until the
3807 /// cell's committed `position` is proven replicated. The request must still
3808 /// be a live local activity on its cell, resident at the epoch that
3809 /// committed the write; otherwise durability cannot be proven for it and
3810 /// the response fails rather than falsely acknowledging the write.
3811 fn wrote(&mut self, request: RequestId, position: u64, effects: &mut Vec<Effect>) {
3812 let held = self.active_requests.get(&request).and_then(|id| {
3813 match self.cells.get(id).map(|cell| &cell.phase) {
3814 Some(Phase::Resident { epoch }) => Some((id.clone(), *epoch)),
3815 _ => None,
3816 }
3817 });
3818 let Some((cell, epoch)) = held else {
3819 effects.push(Effect::ReleaseResponse {
3820 request,
3821 result: Err(RequestError::DurabilityUnproven),
3822 });
3823 return;
3824 };
3825 let op = self.op();
3826 self.gated_writes.insert(
3827 op,
3828 GatedWrite {
3829 request,
3830 cell: cell.clone(),
3831 epoch,
3832 position,
3833 },
3834 );
3835 effects.push(Effect::AwaitDurable {
3836 op,
3837 cell,
3838 epoch,
3839 position,
3840 });
3841 }
3842
3843 /// A gated write's durability proof completed. Acknowledge the write only
3844 /// when the replica proved a position that *covers* it — a shorter proof
3845 /// (a lagging or lying replicator) fails it rather than acknowledging a
3846 /// write the node cannot actually restore. Any error fails it. A completion
3847 /// for a gate already drained (fence or deadline) is ignored — the
3848 /// versioned-op discipline used throughout the core.
3849 fn durable_reached(
3850 &mut self,
3851 op: OpId,
3852 result: Result<u64, Failure>,
3853 effects: &mut Vec<Effect>,
3854 ) {
3855 let Some(gate) = self.gated_writes.remove(&op) else {
3856 return;
3857 };
3858 let proven = matches!(result, Ok(durable) if durable >= gate.position);
3859 let result = if proven {
3860 Ok(())
3861 } else {
3862 Err(RequestError::DurabilityUnproven)
3863 };
3864 // Unpin before releasing: the cleanup this ends -- shedding, eviction --
3865 // is queued ahead of the response, so a caller that sees its write
3866 // acknowledged sees the residency it released too. `activity_finished`
3867 // re-checks the gate map, so a request holding a second gated write
3868 // simply re-pins itself here.
3869 if self.gate_pinned.remove(&gate.request) {
3870 self.activity_finished(gate.request, effects);
3871 }
3872 effects.push(Effect::ReleaseResponse {
3873 request: gate.request,
3874 result,
3875 });
3876 if !proven {
3877 let (id, epoch) = (gate.cell.clone(), gate.epoch);
3878 self.reset_cell(&id, epoch, effects);
3879 }
3880 }
3881
3882 /// Discard a runtime whose durability could not be proved.
3883 ///
3884 /// The caller has been told its write failed. If the cell stays resident,
3885 /// the very next read is served from the same unreplicated memory and
3886 /// returns that write anyway -- the node disagreeing with what it just
3887 /// told a client. Stopping with [`StopCause::Reset`] keeps no local
3888 /// snapshot, so the next activation restores from the bucket.
3889 ///
3890 /// Note this is a stop, not a truncation. The restored database is not
3891 /// invalidated by a failed proof; only this node's unreplicated additions
3892 /// to it are in doubt, and re-reading durable state is how they are
3893 /// discarded.
3894 fn reset_cell(&mut self, id: &str, epoch: Epoch, effects: &mut Vec<Effect>) {
3895 if !matches!(
3896 self.cells.get(id).map(|cell| &cell.phase),
3897 Some(Phase::Resident { epoch: current }) if *current == epoch
3898 ) {
3899 return;
3900 }
3901 // Every other write still on the gate for this cell loses its runtime
3902 // here, so none of them may be acknowledged either.
3903 let doomed: Vec<OpId> = self
3904 .gated_writes
3905 .iter()
3906 .filter(|(_, gate)| gate.cell == id && gate.epoch == epoch)
3907 .map(|(op, _)| *op)
3908 .collect();
3909 for op in doomed {
3910 let Some(gate) = self.gated_writes.remove(&op) else {
3911 continue;
3912 };
3913 self.gate_pinned.remove(&gate.request);
3914 effects.push(Effect::ReleaseResponse {
3915 request: gate.request,
3916 result: Err(RequestError::DurabilityUnproven),
3917 });
3918 }
3919 // Requests already running against this runtime lose it here, exactly
3920 // as a fence does. Leaving them in `active_requests` would leave the
3921 // core believing a stopped cell is still serving, which its own
3922 // invariant catches.
3923 let running: Vec<RequestId> = self
3924 .active_requests
3925 .iter()
3926 .filter(|(_, cell)| cell.as_str() == id)
3927 .map(|(request, _)| *request)
3928 .collect();
3929 for request in running {
3930 self.deactivate_request(request);
3931 self.gate_pinned.remove(&request);
3932 }
3933 let op = self.cell_op(id);
3934 if let Some(cell) = self.cells.get_mut(id) {
3935 // The phase being replaced may hold an op that will now never
3936 // complete against it; its index entry must not outlive it.
3937 if let Some(stale) = phase_op(&cell.phase) {
3938 self.cell_ops.remove(&stale);
3939 }
3940 set_phase(
3941 &mut self.occupied,
3942 cell,
3943 Phase::Cleaning {
3944 op,
3945 epoch,
3946 cause: StopCause::Reset,
3947 },
3948 );
3949 }
3950 effects.push(Effect::StopRuntime {
3951 op,
3952 cell: id.to_string(),
3953 epoch,
3954 cause: StopCause::Reset,
3955 });
3956 }
3957
3958 /// How many cells are currently held resident by a non-hibernatable
3959 /// transport.
3960 fn outbound_pinned(&self) -> usize {
3961 self.cells
3962 .values()
3963 .filter(|cell| {
3964 cell.websockets
3965 .values()
3966 .any(|kind| *kind == WebSocketKind::Outbound)
3967 })
3968 .count()
3969 }
3970
3971 fn websocket_opened(
3972 &mut self,
3973 id: &str,
3974 websocket: WebSocketId,
3975 kind: WebSocketKind,
3976 effects: &mut Vec<Effect>,
3977 ) {
3978 if self.fenced {
3979 return;
3980 }
3981 // A non-hibernatable transport holds its cell resident for as long as
3982 // it is open, so every one of them is a cell the node can never shed.
3983 // Pin the whole ceiling and there is nothing left to nominate:
3984 // residency cannot fall, admission waits on capacity that will never
3985 // be freed, and the node is wedged by its own applications. Cells that
3986 // already hold one are not counted again -- the budget is on how much
3987 // of the node is held, not on how many sockets exist.
3988 let already_pinned = self.cells.get(id).is_some_and(|cell| {
3989 cell.websockets
3990 .values()
3991 .any(|kind| *kind == WebSocketKind::Outbound)
3992 });
3993 let cell_outbound = self.cells.get(id).map_or(0, |cell| {
3994 cell.websockets
3995 .values()
3996 .filter(|kind| **kind == WebSocketKind::Outbound)
3997 .count()
3998 });
3999 if kind == WebSocketKind::Outbound
4000 && (cell_outbound >= self.config.max_outbound_websockets
4001 || (!already_pinned
4002 && !pressure::may_pin_outbound(
4003 self.outbound_pinned(),
4004 Some(self.config.max_resident),
4005 )))
4006 {
4007 effects.push(Effect::CloseWebSocket {
4008 cell: id.to_string(),
4009 websocket,
4010 });
4011 return;
4012 }
4013 let Some(cell) = self.cells.get_mut(id) else {
4014 return;
4015 };
4016 cell.websockets.insert(websocket, kind);
4017 }
4018
4019 fn websocket_closed(&mut self, id: &str, websocket: WebSocketId, effects: &mut Vec<Effect>) {
4020 if let Some(cell) = self.cells.get_mut(id) {
4021 cell.websockets.remove(&websocket);
4022 }
4023 self.shed_one(effects);
4024 }
4025
4026 fn invalidate_remote(&mut self, id: &str, node: &str, epoch: Epoch) {
4027 self.node_lease_cache.remove(node);
4028 let rejected_sample = self.cells.get(id).and_then(|cell| match &cell.phase {
4029 Phase::Remote {
4030 node: current,
4031 epoch: current_epoch,
4032 capacity_sampled_ms,
4033 ..
4034 } if current == node && *current_epoch == epoch => *capacity_sampled_ms,
4035 _ => None,
4036 });
4037 if let Some(sample) = rejected_sample {
4038 self.capacity_rejections.insert(node.to_string(), sample);
4039 self.capacity_reservations.remove(node);
4040 }
4041 let Some(cell) = self.cells.get_mut(id) else {
4042 return;
4043 };
4044 if matches!(
4045 &cell.phase,
4046 Phase::Remote {
4047 node: current,
4048 epoch: current_epoch,
4049 ..
4050 } if current == node && *current_epoch == epoch
4051 ) {
4052 set_phase(&mut self.occupied, cell, Phase::Inactive);
4053 }
4054 }
4055
4056 fn fence(&mut self, effects: &mut Vec<Effect>) {
4057 if self.fenced {
4058 return;
4059 }
4060 self.fenced = true;
4061 self.activation_waiters.clear();
4062 self.activation_permits.clear();
4063 self.capacity_waiters.clear();
4064 self.active_requests.clear();
4065 self.active_cells.clear();
4066 // Any write still waiting on the output gate loses its cell here, so it
4067 // must fail rather than be acknowledged — the fence and the fail are
4068 // atomic. A late DurableReached for a drained op is ignored.
4069 self.gate_pinned.clear();
4070 for (_, gate) in std::mem::take(&mut self.gated_writes) {
4071 effects.push(Effect::ReleaseResponse {
4072 request: gate.request,
4073 result: Err(RequestError::NodeFenced),
4074 });
4075 }
4076 for (request, _) in std::mem::take(&mut self.node_lease_waiters) {
4077 effects.push(Effect::Complete {
4078 request,
4079 result: Err(RequestError::NodeFenced),
4080 });
4081 }
4082 self.node_wake_waiters.clear();
4083 let ids: Vec<CellId> = self.cells.keys().cloned().collect();
4084 for id in ids {
4085 let mut cell = self.cells.remove(&id).expect("id came from map");
4086 match &cell.phase {
4087 Phase::Starting { op, epoch } | Phase::Publishing { op, epoch } => {
4088 self.retired_runtime_ops.insert(*op, (id.clone(), *epoch));
4089 }
4090 _ => {}
4091 }
4092 if let Some(epoch) = runtime_epoch(&cell.phase) {
4093 let op = self.op();
4094 effects.push(Effect::StopRuntime {
4095 op,
4096 cell: id.clone(),
4097 epoch,
4098 cause: StopCause::Fence,
4099 });
4100 }
4101 self.finish_requests(&id, &mut cell, Err(RequestError::NodeFenced), effects);
4102 // The phase and alarm die here without completing; their ops can
4103 // never match a lookup again. The release op survives on purpose:
4104 // `owner_released` still consumes it after a fence, as it did
4105 // when resolution was a scan.
4106 if let Some(stale) = phase_op(&cell.phase) {
4107 self.cell_ops.remove(&stale);
4108 }
4109 if let Some(AlarmState::Firing { op, .. }) = cell.alarm {
4110 self.cell_ops.remove(&op);
4111 }
4112 set_phase(&mut self.occupied, &mut cell, Phase::Fenced);
4113 cell.waiting_for = None;
4114 cell.waiting_activation = None;
4115 cell.alarm = None;
4116 cell.alarm_wake = false;
4117 cell.websockets.clear();
4118 self.cells.insert(id, cell);
4119 }
4120 }
4121
4122 fn compensate_retired_runtime(
4123 &mut self,
4124 op: OpId,
4125 result: Result<(), Failure>,
4126 effects: &mut Vec<Effect>,
4127 ) {
4128 let Some((cell, epoch)) = self.retired_runtime_ops.remove(&op) else {
4129 return;
4130 };
4131 // Definite failure created nothing. Success or ambiguity may have
4132 // created/published a runtime after authority was revoked, so cleanup
4133 // is mandatory and idempotent.
4134 if result != Err(Failure::Definite) {
4135 let cleanup = self.op();
4136 effects.push(Effect::StopRuntime {
4137 op: cleanup,
4138 cell,
4139 epoch,
4140 cause: StopCause::Cleanup,
4141 });
4142 }
4143 }
4144}
4145
4146/// The sole state transition entry point.
4147/// The monotonic instant an event carries, if it carries one. Events without
4148/// a timestamp leave the remembered instant alone rather than resetting it.
4149/// The wall-clock reading an event carried, if it carried one.
4150fn event_now_ms(event: &Event) -> Option<u64> {
4151 match event {
4152 Event::StartNodeLease { now_ms, .. }
4153 | Event::SelfNodeLeaseRead { now_ms, .. }
4154 | Event::OwnerRead { now_ms, .. }
4155 | Event::NodeLeaseRead { now_ms, .. }
4156 | Event::TimerFired { now_ms, .. }
4157 | Event::AlarmObserved { now_ms, .. }
4158 | Event::AlarmFinished { now_ms, .. } => Some(*now_ms),
4159 _ => None,
4160 }
4161}
4162
4163fn event_mono_ms(event: &Event) -> Option<u64> {
4164 match event {
4165 Event::SelfNodeLeaseRead { now_mono_ms, .. }
4166 | Event::NodeLeaseCasCompleted { now_mono_ms, .. }
4167 | Event::RequestAt { now_mono_ms, .. }
4168 | Event::CapacityRequestAt { now_mono_ms, .. }
4169 | Event::WakeHintAt { now_mono_ms, .. }
4170 | Event::TimerFired { now_mono_ms, .. }
4171 | Event::AlarmObserved { now_mono_ms, .. }
4172 | Event::AlarmFinished { now_mono_ms, .. }
4173 | Event::LoadSampled { now_mono_ms, .. } => Some(*now_mono_ms),
4174 _ => None,
4175 }
4176}
4177
4178pub fn on_event(state: &mut State, event: Event) -> Vec<Effect> {
4179 let mut effects = Vec::new();
4180 if let Some(now_mono_ms) = event_mono_ms(&event) {
4181 state.now_mono_ms = state.now_mono_ms.max(now_mono_ms);
4182 }
4183 if let Some(now_ms) = event_now_ms(&event) {
4184 state.now_ms = state.now_ms.max(now_ms);
4185 }
4186 match event {
4187 Event::StartNodeLease { now_ms, spec } => {
4188 state.start_node_lease(now_ms, spec, &mut effects)
4189 }
4190 Event::SelfNodeLeaseRead {
4191 op,
4192 now_ms,
4193 now_mono_ms,
4194 result,
4195 } => state.read_self_node_lease(op, now_ms, now_mono_ms, result, &mut effects),
4196 Event::NodeLeaseCasCompleted {
4197 op,
4198 now_mono_ms,
4199 result,
4200 } => state.node_lease_cas_completed(op, now_mono_ms, result, &mut effects),
4201 Event::LocalCellsRead { result } => state.local_cells_read(result, &mut effects),
4202 Event::TimerFired {
4203 timer,
4204 now_ms,
4205 now_mono_ms,
4206 } => state.timer_fired(timer, now_ms, now_mono_ms, &mut effects),
4207 Event::Request { request, cell } => state.request(request, cell, 0, false, &mut effects),
4208 Event::RequestAt {
4209 request,
4210 cell,
4211 now_ms,
4212 ..
4213 } => state.request(request, cell, now_ms, false, &mut effects),
4214 Event::CapacityRequestAt {
4215 request,
4216 cell,
4217 now_ms,
4218 ..
4219 } => state.request(request, cell, now_ms, true, &mut effects),
4220 Event::WorkerRequest { request } => state.worker_request(request, &mut effects),
4221 Event::BeginPreserve => state.begin_preserve(&mut effects),
4222 Event::Cancel { request } => state.cancel(request),
4223 Event::ActivityFinished { request } => state.activity_finished(request, &mut effects),
4224 Event::Wrote { request, position } => state.wrote(request, position, &mut effects),
4225 Event::DurableReached { op, result } => state.durable_reached(op, result, &mut effects),
4226 Event::WebSocketOpened {
4227 cell,
4228 websocket,
4229 kind,
4230 } => state.websocket_opened(&cell, websocket, kind, &mut effects),
4231 Event::WebSocketClosed { cell, websocket } => {
4232 state.websocket_closed(&cell, websocket, &mut effects)
4233 }
4234 Event::AlarmObserved {
4235 cell,
4236 at_ms,
4237 covered,
4238 now_ms,
4239 now_mono_ms,
4240 } => state.alarm_observed(&cell, at_ms, covered, now_ms, now_mono_ms, &mut effects),
4241 Event::AlarmFinished {
4242 op,
4243 now_ms,
4244 now_mono_ms,
4245 result,
4246 } => state.alarm_finished(op, now_ms, now_mono_ms, result, &mut effects),
4247 Event::WakeHint { cell } => state.wake_hint(cell, 0, &mut effects),
4248 Event::WakeHintAt { cell, now_ms, .. } => state.wake_hint(cell, now_ms, &mut effects),
4249 Event::OwnerRead { op, now_ms, result } => {
4250 state.owner_read(op, now_ms, result, &mut effects)
4251 }
4252 Event::NodeLeaseRead { op, now_ms, result } => {
4253 state.node_lease_read(op, now_ms, result, &mut effects)
4254 }
4255 Event::CapacityPeersRead { op, now_ms, result } => {
4256 state.capacity_peers_read(op, now_ms, result, &mut effects)
4257 }
4258 Event::OwnerCasCompleted { op, result } => {
4259 state.owner_cas_completed(op, result, &mut effects)
4260 }
4261 Event::OwnerReleased { op, result } => state.owner_released(op, result),
4262 Event::RestoreCompleted { op, result } => state.restore_completed(op, result, &mut effects),
4263 Event::RuntimeStarted { op, result } => state.runtime_started(op, result, &mut effects),
4264 Event::Published { op, result } => state.published(op, result, &mut effects),
4265 Event::DurabilityChecked { op, result } => {
4266 state.durability_checked(op, result, &mut effects)
4267 }
4268 Event::RuntimeStopped { op } => state.runtime_stopped(op, &mut effects),
4269 Event::Evict { cell } => state.evict(&cell, &mut effects),
4270 Event::LoadSampled { load, now_mono_ms } => {
4271 state.load_sampled(load, now_mono_ms, &mut effects)
4272 }
4273 Event::InvalidateRemote { cell, node, epoch } => {
4274 state.invalidate_remote(&cell, &node, epoch)
4275 }
4276 Event::NodeFenced => state.fence_node(&mut effects),
4277 Event::ReleaseAll => state.release_all(&mut effects),
4278 }
4279 state.pump_activations(&mut effects);
4280 state.pump_release(&mut effects);
4281 state.update_node_lease_dependencies(state.now_mono_ms);
4282 if cfg!(debug_assertions) {
4283 state.validate().expect("state invariant");
4284 }
4285 state.arm_operation_deadlines(&mut effects);
4286 effects
4287}
4288
4289fn same_node_lease(left: &NodeLeaseRecord, right: &NodeLeaseRecord) -> bool {
4290 left.node == right.node
4291 && left.addr == right.addr
4292 && left.expires_ms == right.expires_ms
4293 && left.peer_protocol == right.peer_protocol
4294 && left.generation == right.generation
4295}
4296
4297fn phase_occupies_capacity(phase: &Phase) -> bool {
4298 matches!(
4299 phase,
4300 Phase::Acquiring { .. }
4301 | Phase::ReconcilingAcquire { .. }
4302 | Phase::Restoring { .. }
4303 | Phase::Starting { .. }
4304 | Phase::Publishing { .. }
4305 | Phase::EnsuringDurability { .. }
4306 | Phase::Cleaning { .. }
4307 | Phase::Resident { .. }
4308 )
4309}
4310
4311fn phase_holds_activation(phase: &Phase) -> bool {
4312 matches!(
4313 phase,
4314 Phase::ReadingOwner { .. }
4315 | Phase::ReadingNodeLease { .. }
4316 | Phase::ReadingCapacity { .. }
4317 | Phase::WaitingCapacity
4318 | Phase::Acquiring { .. }
4319 | Phase::ReconcilingAcquire { .. }
4320 | Phase::Restoring { .. }
4321 | Phase::Starting { .. }
4322 | Phase::Publishing { .. }
4323 | Phase::Cleaning { .. }
4324 )
4325}
4326
4327fn phase_depends_on_node_lease(phase: &Phase) -> bool {
4328 matches!(
4329 phase,
4330 Phase::WaitingActivation
4331 | Phase::ReadingOwner { .. }
4332 | Phase::ReadingNodeLease { .. }
4333 | Phase::ReadingCapacity { .. }
4334 | Phase::WaitingCapacity
4335 | Phase::Acquiring { .. }
4336 | Phase::ReconcilingAcquire { .. }
4337 | Phase::Restoring { .. }
4338 | Phase::Starting { .. }
4339 | Phase::Publishing { .. }
4340 | Phase::EnsuringDurability { .. }
4341 | Phase::Cleaning { .. }
4342 | Phase::Resident { .. }
4343 )
4344}
4345
4346/// The one gate every phase change passes through: it keeps `occupied`
4347/// equal to the number of cells in a capacity-occupying phase, so nothing
4348/// ever has to count them. `validate` asserts the equality by walking.
4349fn set_phase(occupied: &mut usize, cell: &mut Cell, phase: Phase) {
4350 match (
4351 phase_occupies_capacity(&cell.phase),
4352 phase_occupies_capacity(&phase),
4353 ) {
4354 (false, true) => *occupied += 1,
4355 (true, false) => *occupied -= 1,
4356 _ => {}
4357 }
4358 cell.phase = phase;
4359}
4360
4361/// The in-flight operation a phase is waiting on, if it is waiting on one.
4362fn phase_op(phase: &Phase) -> Option<OpId> {
4363 match phase {
4364 Phase::ReadingOwner { op }
4365 | Phase::ReadingNodeLease { op, .. }
4366 | Phase::ReadingCapacity { op, .. }
4367 | Phase::Acquiring { op, .. }
4368 | Phase::ReconcilingAcquire { op, .. }
4369 | Phase::Restoring { op, .. }
4370 | Phase::Starting { op, .. }
4371 | Phase::Publishing { op, .. }
4372 | Phase::EnsuringDurability { op, .. }
4373 | Phase::Cleaning { op, .. } => Some(*op),
4374 _ => None,
4375 }
4376}
4377
4378fn runtime_epoch(phase: &Phase) -> Option<Epoch> {
4379 match phase {
4380 Phase::Publishing { epoch, .. }
4381 | Phase::EnsuringDurability { epoch, .. }
4382 | Phase::Cleaning { epoch, .. }
4383 | Phase::Resident { epoch } => Some(*epoch),
4384 _ => None,
4385 }
4386}