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