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