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