Diffinery

homeflare/celldpublic

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