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