aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-expert-residency / src / manager.rs
| 1 | //! The residency state machine. |
| 2 | //! |
| 3 | //! ## Lifecycle |
| 4 | //! |
| 5 | //! ```text |
| 6 | //! Absent --acquire (miss)--> Fetching --mark_verified--> Verified |
| 7 | //! --mark_copying--> Copying --publish--> Ready |
| 8 | //! Ready --pin--> InUse --last release--> Evictable --evict--> Absent |
| 9 | //! Fetching | Verified | Copying --fail--> Failed (held until the last pin |
| 10 | //! is released) --> Absent |
| 11 | //! ``` |
| 12 | //! |
| 13 | //! `publish` must be called only after the transfer completed, the digest |
| 14 | //! matched and the GPU visibility fence signalled (aienix#4 invariant 3). |
| 15 | //! |
| 16 | //! ## Pins |
| 17 | //! |
| 18 | //! [`ResidencyManager::acquire`] always returns a [`Pin`], also on a miss: a |
| 19 | //! request pins its experts from the moment the router selects them until |
| 20 | //! its GPU read fence has passed, then releases each pin. An entry with any |
| 21 | //! pin, or with a fetch in flight, is never evicted. A [`Pin`] is not |
| 22 | //! `Clone`, so it can be released only once. |
| 23 | //! |
| 24 | //! ## Generations (ABA) |
| 25 | //! |
| 26 | //! Every admission gets a fresh generation from one counter that never |
| 27 | //! repeats. Pins and tickets carry `(slot, generation)`; after a slot is |
| 28 | //! reused, an old pin or ticket is refused as stale instead of acting on the |
| 29 | //! new occupant. |
| 30 | //! |
| 31 | //! ## Eviction order |
| 32 | //! |
| 33 | //! Least recently used, by a logical clock that advances on every acquire |
| 34 | //! and release. Ticks are unique, so the order is total and deterministic for |
| 35 | //! a given sequence of calls. Free slots are reused lowest index first. |
| 36 | |
| 37 | use std::collections::{BTreeMap, BTreeSet}; |
| 38 | use std::fmt::Debug; |
| 39 | |
| 40 | use crate::budget::{Ledger, MemoryBudget}; |
| 41 | use crate::error::{BudgetError, FailureCause, Refusal}; |
| 42 | |
| 43 | /// Index of a fixed logical expert slot. |
| 44 | pub type SlotId = u32; |
| 45 | |
| 46 | /// Which part of an expert's MLP an identity names. `GateUp` is for |
| 47 | /// checkpoints that store gate and up fused. |
| 48 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 49 | pub enum ExpertPart { |
| 50 | Gate, |
| 51 | Up, |
| 52 | GateUp, |
| 53 | Down, |
| 54 | } |
| 55 | |
| 56 | /// A stable expert identity: checkpoint digest, layer, expert, part. The |
| 57 | /// manager is generic over the key, so the sc#629 store key (which also |
| 58 | /// carries the quantization format) can be used directly instead. |
| 59 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 60 | pub struct ExpertIdentity { |
| 61 | pub checkpoint_digest: [u8; 32], |
| 62 | pub layer: u32, |
| 63 | pub expert: u32, |
| 64 | pub part: ExpertPart, |
| 65 | } |
| 66 | |
| 67 | /// Internal phase of an admitted entry. |
| 68 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 69 | pub enum Phase { |
| 70 | Fetching, |
| 71 | Verified, |
| 72 | Copying, |
| 73 | Ready, |
| 74 | /// The fetch failed; the slot is held only until its pins are released. |
| 75 | Failed(FailureCause), |
| 76 | } |
| 77 | |
| 78 | /// Externally visible state of an expert identity. |
| 79 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 80 | pub enum ExpertState { |
| 81 | Absent, |
| 82 | Fetching, |
| 83 | Verified, |
| 84 | Copying, |
| 85 | /// Published and not pinned, not yet used since publish. |
| 86 | Ready, |
| 87 | /// Published and pinned by at least one request. |
| 88 | InUse, |
| 89 | /// Published, not pinned, used at least once. |
| 90 | Evictable, |
| 91 | } |
| 92 | |
| 93 | /// What a pin holder sees when it polls. |
| 94 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 95 | pub enum PinStatus { |
| 96 | /// The expert is resident and published in this slot generation. |
| 97 | Ready, |
| 98 | /// Still in flight; the holder must wait (never substitute). |
| 99 | Waiting(Phase), |
| 100 | } |
| 101 | |
| 102 | /// A request's hold on one expert. Not `Clone`: release it exactly once. |
| 103 | #[derive(Debug, PartialEq, Eq)] |
| 104 | #[must_use = "a pin must be released, or the slot stays pinned"] |
| 105 | pub struct Pin { |
| 106 | slot: SlotId, |
| 107 | generation: u64, |
| 108 | } |
| 109 | |
| 110 | impl Pin { |
| 111 | pub fn slot(&self) -> SlotId { |
| 112 | self.slot |
| 113 | } |
| 114 | pub fn generation(&self) -> u64 { |
| 115 | self.generation |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | /// The right to drive one fetch through its steps. Handed to exactly one |
| 120 | /// caller, the one whose acquire missed. |
| 121 | #[derive(Debug, PartialEq, Eq)] |
| 122 | #[must_use = "a fetch ticket must be published or failed"] |
| 123 | pub struct FetchTicket { |
| 124 | slot: SlotId, |
| 125 | generation: u64, |
| 126 | bytes: u64, |
| 127 | } |
| 128 | |
| 129 | impl FetchTicket { |
| 130 | pub fn slot(&self) -> SlotId { |
| 131 | self.slot |
| 132 | } |
| 133 | pub fn generation(&self) -> u64 { |
| 134 | self.generation |
| 135 | } |
| 136 | pub fn bytes(&self) -> u64 { |
| 137 | self.bytes |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | /// Result of a successful acquire. |
| 142 | #[derive(Debug, PartialEq, Eq)] |
| 143 | pub enum Acquired { |
| 144 | /// Hit: resident and published. |
| 145 | Ready(Pin), |
| 146 | /// Miss: a slot was assigned; the caller must fetch into it. |
| 147 | Fetch(Pin, FetchTicket), |
| 148 | /// Another caller's fetch for the same key is in flight; wait for it. |
| 149 | Pending(Pin), |
| 150 | } |
| 151 | |
| 152 | impl Acquired { |
| 153 | pub fn pin(&self) -> &Pin { |
| 154 | match self { |
| 155 | Self::Ready(p) | Self::Fetch(p, _) | Self::Pending(p) => p, |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | /// Configuration of one manager. |
| 161 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 162 | pub struct ResidencyConfig { |
| 163 | pub budget: MemoryBudget, |
| 164 | /// Size of one fixed expert slot. Every admitted object must fit. |
| 165 | pub slot_bytes: u64, |
| 166 | /// Optional cap on the number of slots below what the budget allows. |
| 167 | pub max_slots: Option<u32>, |
| 168 | /// Maximum fetches in flight (queue depth). |
| 169 | pub max_in_flight: u32, |
| 170 | /// Maximum bytes in flight. Must fit the staging reservation and hold at |
| 171 | /// least one full slot. |
| 172 | pub max_in_flight_bytes: u64, |
| 173 | } |
| 174 | |
| 175 | /// Counters. All monotonic except the `current_*` gauges. |
| 176 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 177 | pub struct Stats { |
| 178 | pub hits: u64, |
| 179 | /// Acquires that joined a fetch already in flight. |
| 180 | pub joined: u64, |
| 181 | pub misses: u64, |
| 182 | pub published: u64, |
| 183 | pub evictions: u64, |
| 184 | pub failures: u64, |
| 185 | /// Fresh fetches rolled back by [`ResidencyManager::acquire_all`]. |
| 186 | pub rolled_back: u64, |
| 187 | pub refusals: u64, |
| 188 | pub current_in_flight: u32, |
| 189 | pub current_in_flight_bytes: u64, |
| 190 | pub peak_in_flight_bytes: u64, |
| 191 | pub current_resident_bytes: u64, |
| 192 | pub peak_resident_bytes: u64, |
| 193 | pub current_pins: u64, |
| 194 | /// Sum and maximum of admit-to-publish time, from caller timestamps. |
| 195 | pub fetch_wait_ns_total: u64, |
| 196 | pub fetch_wait_ns_max: u64, |
| 197 | } |
| 198 | |
| 199 | #[derive(Debug, Clone)] |
| 200 | struct Entry<K> { |
| 201 | key: K, |
| 202 | generation: u64, |
| 203 | phase: Phase, |
| 204 | pins: u32, |
| 205 | bytes: u64, |
| 206 | last_use: u64, |
| 207 | used: bool, |
| 208 | admitted_ns: u64, |
| 209 | } |
| 210 | |
| 211 | impl<K> Entry<K> { |
| 212 | fn in_flight(&self) -> bool { |
| 213 | matches!( |
| 214 | self.phase, |
| 215 | Phase::Fetching | Phase::Verified | Phase::Copying |
| 216 | ) |
| 217 | } |
| 218 | fn evictable(&self) -> bool { |
| 219 | self.phase == Phase::Ready && self.pins == 0 |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | /// The bounded residency manager. |
| 224 | #[derive(Debug)] |
| 225 | pub struct ResidencyManager<K> { |
| 226 | ledger: Ledger, |
| 227 | max_in_flight: u32, |
| 228 | max_in_flight_bytes: u64, |
| 229 | slots: Vec<Option<Entry<K>>>, |
| 230 | index: BTreeMap<K, SlotId>, |
| 231 | free: BTreeSet<SlotId>, |
| 232 | clock: u64, |
| 233 | next_generation: u64, |
| 234 | stats: Stats, |
| 235 | } |
| 236 | |
| 237 | impl<K: Ord + Clone + Debug> ResidencyManager<K> { |
| 238 | /// Plan the ledger and create an empty manager. Fails closed on any |
| 239 | /// oversubscription or inconsistent limit. |
| 240 | pub fn new(config: ResidencyConfig) -> Result<Self, BudgetError> { |
| 241 | let ledger = Ledger::plan(&config.budget, config.slot_bytes, config.max_slots)?; |
| 242 | if config.max_in_flight == 0 { |
| 243 | return Err(BudgetError::ZeroInFlight); |
| 244 | } |
| 245 | if config.max_in_flight_bytes > ledger.staging_bytes { |
| 246 | return Err(BudgetError::InFlightBytesExceedStaging { |
| 247 | max_in_flight_bytes: config.max_in_flight_bytes, |
| 248 | staging_bytes: ledger.staging_bytes, |
| 249 | }); |
| 250 | } |
| 251 | if config.max_in_flight_bytes < config.slot_bytes { |
| 252 | return Err(BudgetError::InFlightBytesBelowSlot { |
| 253 | max_in_flight_bytes: config.max_in_flight_bytes, |
| 254 | slot_bytes: config.slot_bytes, |
| 255 | }); |
| 256 | } |
| 257 | let n = ledger.slot_count; |
| 258 | Ok(Self { |
| 259 | ledger, |
| 260 | max_in_flight: config.max_in_flight, |
| 261 | max_in_flight_bytes: config.max_in_flight_bytes, |
| 262 | slots: (0..n).map(|_| None).collect(), |
| 263 | index: BTreeMap::new(), |
| 264 | free: (0..n).collect(), |
| 265 | clock: 0, |
| 266 | next_generation: 1, |
| 267 | stats: Stats::default(), |
| 268 | }) |
| 269 | } |
| 270 | |
| 271 | pub fn ledger(&self) -> &Ledger { |
| 272 | &self.ledger |
| 273 | } |
| 274 | |
| 275 | pub fn stats(&self) -> Stats { |
| 276 | self.stats |
| 277 | } |
| 278 | |
| 279 | pub fn slot_count(&self) -> u32 { |
| 280 | self.ledger.slot_count |
| 281 | } |
| 282 | |
| 283 | /// The state of one identity. |
| 284 | pub fn state(&self, key: &K) -> ExpertState { |
| 285 | let Some(&slot) = self.index.get(key) else { |
| 286 | return ExpertState::Absent; |
| 287 | }; |
| 288 | let e = self.entry(slot); |
| 289 | match e.phase { |
| 290 | Phase::Fetching => ExpertState::Fetching, |
| 291 | Phase::Verified => ExpertState::Verified, |
| 292 | Phase::Copying => ExpertState::Copying, |
| 293 | Phase::Ready if e.pins > 0 => ExpertState::InUse, |
| 294 | Phase::Ready if e.used => ExpertState::Evictable, |
| 295 | Phase::Ready => ExpertState::Ready, |
| 296 | // Failed entries are removed from the index. |
| 297 | Phase::Failed(_) => ExpertState::Absent, |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | /// The slot and generation currently holding `key`, if admitted. |
| 302 | pub fn slot_of(&self, key: &K) -> Option<(SlotId, u64)> { |
| 303 | self.index.get(key).map(|&s| (s, self.entry(s).generation)) |
| 304 | } |
| 305 | |
| 306 | /// Pin `key` of `bytes` bytes. On a hit the pin is ready; on a miss a |
| 307 | /// slot is assigned (evicting the least recently used unpinned resident |
| 308 | /// entry if no slot is free) and the caller gets the fetch ticket. |
| 309 | /// `now_ns` is the caller's monotonic clock, used only for wait counters. |
| 310 | pub fn acquire(&mut self, key: K, bytes: u64, now_ns: u64) -> Result<Acquired, Refusal> { |
| 311 | let r = self.acquire_inner(key, bytes, now_ns); |
| 312 | if r.is_err() { |
| 313 | self.stats.refusals += 1; |
| 314 | } |
| 315 | r |
| 316 | } |
| 317 | |
| 318 | fn acquire_inner(&mut self, key: K, bytes: u64, now_ns: u64) -> Result<Acquired, Refusal> { |
| 319 | if let Some(&slot) = self.index.get(&key) { |
| 320 | let e = self.entry(slot); |
| 321 | if e.bytes != bytes { |
| 322 | return Err(Refusal::SizeMismatch { |
| 323 | admitted: e.bytes, |
| 324 | requested: bytes, |
| 325 | }); |
| 326 | } |
| 327 | let pins = e.pins.checked_add(1).ok_or(Refusal::PinOverflow { slot })?; |
| 328 | let tick = self.tick(); |
| 329 | let e = self.slots[slot as usize].as_mut().expect("indexed slot"); |
| 330 | e.pins = pins; |
| 331 | e.last_use = tick; |
| 332 | let pin = Pin { |
| 333 | slot, |
| 334 | generation: e.generation, |
| 335 | }; |
| 336 | let ready = e.phase == Phase::Ready; |
| 337 | self.stats.current_pins += 1; |
| 338 | return Ok(if ready { |
| 339 | self.stats.hits += 1; |
| 340 | Acquired::Ready(pin) |
| 341 | } else { |
| 342 | self.stats.joined += 1; |
| 343 | Acquired::Pending(pin) |
| 344 | }); |
| 345 | } |
| 346 | |
| 347 | // Miss: validate everything before evicting anything. |
| 348 | if bytes == 0 { |
| 349 | return Err(Refusal::ZeroSizedObject); |
| 350 | } |
| 351 | if bytes > self.ledger.slot_bytes { |
| 352 | return Err(Refusal::ObjectTooLarge { |
| 353 | bytes, |
| 354 | slot_bytes: self.ledger.slot_bytes, |
| 355 | }); |
| 356 | } |
| 357 | if self.stats.current_in_flight >= self.max_in_flight { |
| 358 | return Err(Refusal::InFlightLimit { |
| 359 | limit: self.max_in_flight, |
| 360 | }); |
| 361 | } |
| 362 | let in_flight_bytes = self.stats.current_in_flight_bytes; |
| 363 | if in_flight_bytes + bytes > self.max_in_flight_bytes { |
| 364 | return Err(Refusal::InFlightBytesLimit { |
| 365 | in_flight_bytes, |
| 366 | requested: bytes, |
| 367 | limit: self.max_in_flight_bytes, |
| 368 | }); |
| 369 | } |
| 370 | let slot = match self.free.first().copied() { |
| 371 | Some(s) => { |
| 372 | self.free.remove(&s); |
| 373 | s |
| 374 | } |
| 375 | None => { |
| 376 | let victim = self.lru_victim().ok_or_else(|| self.exhaustion())?; |
| 377 | self.evict(victim); |
| 378 | victim |
| 379 | } |
| 380 | }; |
| 381 | |
| 382 | let tick = self.tick(); |
| 383 | let generation = self.next_generation; |
| 384 | self.next_generation += 1; |
| 385 | self.slots[slot as usize] = Some(Entry { |
| 386 | key: key.clone(), |
| 387 | generation, |
| 388 | phase: Phase::Fetching, |
| 389 | pins: 1, |
| 390 | bytes, |
| 391 | last_use: tick, |
| 392 | used: false, |
| 393 | admitted_ns: now_ns, |
| 394 | }); |
| 395 | self.index.insert(key, slot); |
| 396 | self.stats.misses += 1; |
| 397 | self.stats.current_pins += 1; |
| 398 | self.stats.current_in_flight += 1; |
| 399 | self.stats.current_in_flight_bytes += bytes; |
| 400 | self.stats.peak_in_flight_bytes = self |
| 401 | .stats |
| 402 | .peak_in_flight_bytes |
| 403 | .max(self.stats.current_in_flight_bytes); |
| 404 | Ok(Acquired::Fetch( |
| 405 | Pin { slot, generation }, |
| 406 | FetchTicket { |
| 407 | slot, |
| 408 | generation, |
| 409 | bytes, |
| 410 | }, |
| 411 | )) |
| 412 | } |
| 413 | |
| 414 | /// Acquire every key of one request, or none. Keys may repeat (each |
| 415 | /// occurrence takes its own pin). On a refusal every pin taken by this |
| 416 | /// call is released and every fetch it started is rolled back, then the |
| 417 | /// refusal is returned. Entries evicted to make room stay evicted. |
| 418 | pub fn acquire_all( |
| 419 | &mut self, |
| 420 | keys: &[(K, u64)], |
| 421 | now_ns: u64, |
| 422 | ) -> Result<Vec<Acquired>, Refusal> { |
| 423 | let mut taken: Vec<Acquired> = Vec::with_capacity(keys.len()); |
| 424 | for (key, bytes) in keys { |
| 425 | match self.acquire(key.clone(), *bytes, now_ns) { |
| 426 | Ok(a) => taken.push(a), |
| 427 | Err(refusal) => { |
| 428 | // Release in reverse so fresh fetches lose their last |
| 429 | // pin before being rolled back. |
| 430 | while let Some(a) = taken.pop() { |
| 431 | self.rollback(a); |
| 432 | } |
| 433 | return Err(refusal); |
| 434 | } |
| 435 | } |
| 436 | } |
| 437 | Ok(taken) |
| 438 | } |
| 439 | |
| 440 | fn rollback(&mut self, a: Acquired) { |
| 441 | match a { |
| 442 | Acquired::Ready(pin) | Acquired::Pending(pin) => { |
| 443 | self.release(pin).expect("pin taken by this call"); |
| 444 | } |
| 445 | Acquired::Fetch(pin, ticket) => { |
| 446 | self.release(pin).expect("pin taken by this call"); |
| 447 | let slot = ticket.slot; |
| 448 | let e = self.entry(slot); |
| 449 | debug_assert!(e.generation == ticket.generation && e.phase == Phase::Fetching); |
| 450 | // Pins are released newest first, so every later duplicate of |
| 451 | // this key (which joined this fetch) is already released. |
| 452 | assert_eq!(e.pins, 0, "fresh fetch still pinned during rollback"); |
| 453 | self.finish_in_flight(slot); |
| 454 | let e = self.slots[slot as usize].take().expect("slot"); |
| 455 | self.index.remove(&e.key); |
| 456 | self.free.insert(slot); |
| 457 | self.stats.rolled_back += 1; |
| 458 | } |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | /// Fetching -> Verified: the bytes are in staging and the digest matched. |
| 463 | pub fn mark_verified(&mut self, ticket: &FetchTicket) -> Result<(), Refusal> { |
| 464 | self.step(ticket, Phase::Fetching, Phase::Verified) |
| 465 | } |
| 466 | |
| 467 | /// Verified -> Copying: the staging-to-slot copy has started. |
| 468 | pub fn mark_copying(&mut self, ticket: &FetchTicket) -> Result<(), Refusal> { |
| 469 | self.step(ticket, Phase::Verified, Phase::Copying) |
| 470 | } |
| 471 | |
| 472 | /// Copying -> Ready. Call only after the copy completed and the GPU |
| 473 | /// visibility fence signalled. |
| 474 | pub fn publish(&mut self, ticket: &FetchTicket, now_ns: u64) -> Result<(), Refusal> { |
| 475 | self.step(ticket, Phase::Copying, Phase::Ready)?; |
| 476 | let slot = ticket.slot; |
| 477 | let (bytes, admitted_ns) = { |
| 478 | let e = self.entry(slot); |
| 479 | (e.bytes, e.admitted_ns) |
| 480 | }; |
| 481 | self.finish_in_flight(slot); |
| 482 | let wait = now_ns.saturating_sub(admitted_ns); |
| 483 | let s = &mut self.stats; |
| 484 | s.published += 1; |
| 485 | s.current_resident_bytes += bytes; |
| 486 | s.peak_resident_bytes = s.peak_resident_bytes.max(s.current_resident_bytes); |
| 487 | s.fetch_wait_ns_total = s.fetch_wait_ns_total.saturating_add(wait); |
| 488 | s.fetch_wait_ns_max = s.fetch_wait_ns_max.max(wait); |
| 489 | Ok(()) |
| 490 | } |
| 491 | |
| 492 | /// Any in-flight phase -> Failed. The key is unmapped at once, so the |
| 493 | /// next acquire starts a clean fetch; pin holders see |
| 494 | /// [`Refusal::FetchFailed`] when they poll and must release. |
| 495 | pub fn fail(&mut self, ticket: &FetchTicket, cause: FailureCause) -> Result<(), Refusal> { |
| 496 | let slot = self.check_ticket(ticket)?; |
| 497 | let e = self.entry(slot); |
| 498 | if !e.in_flight() { |
| 499 | return Err(Refusal::WrongPhase { |
| 500 | slot, |
| 501 | expected: Phase::Fetching, |
| 502 | found: e.phase, |
| 503 | }); |
| 504 | } |
| 505 | self.finish_in_flight(slot); |
| 506 | self.stats.failures += 1; |
| 507 | let e = self.slots[slot as usize].as_mut().expect("slot"); |
| 508 | e.phase = Phase::Failed(cause); |
| 509 | let key = e.key.clone(); |
| 510 | let pins = e.pins; |
| 511 | self.index.remove(&key); |
| 512 | if pins == 0 { |
| 513 | self.slots[slot as usize] = None; |
| 514 | self.free.insert(slot); |
| 515 | } |
| 516 | Ok(()) |
| 517 | } |
| 518 | |
| 519 | /// The current phase of the fetch behind `ticket`. A ticket whose slot |
| 520 | /// generation is gone (failed and freed, or evicted after publish) is |
| 521 | /// refused as stale. |
| 522 | pub fn ticket_phase(&self, ticket: &FetchTicket) -> Result<Phase, Refusal> { |
| 523 | let slot = self.check_ticket(ticket)?; |
| 524 | Ok(self.entry(slot).phase) |
| 525 | } |
| 526 | |
| 527 | /// Where the pinned expert stands. |
| 528 | pub fn poll(&self, pin: &Pin) -> Result<PinStatus, Refusal> { |
| 529 | let e = self.pinned_entry(pin)?; |
| 530 | match e.phase { |
| 531 | Phase::Ready => Ok(PinStatus::Ready), |
| 532 | Phase::Failed(cause) => Err(Refusal::FetchFailed { |
| 533 | slot: pin.slot, |
| 534 | generation: pin.generation, |
| 535 | cause, |
| 536 | }), |
| 537 | p => Ok(PinStatus::Waiting(p)), |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | /// Drop one pin. Call after the GPU read fence of the request has |
| 542 | /// passed. The slot becomes evictable when its last pin goes. |
| 543 | pub fn release(&mut self, pin: Pin) -> Result<(), Refusal> { |
| 544 | self.pinned_entry(&pin)?; |
| 545 | let tick = self.tick(); |
| 546 | let slot = pin.slot; |
| 547 | let e = self.slots[slot as usize].as_mut().expect("slot"); |
| 548 | e.pins -= 1; |
| 549 | e.last_use = tick; |
| 550 | if e.phase == Phase::Ready { |
| 551 | e.used = true; |
| 552 | } |
| 553 | let free_failed = matches!(e.phase, Phase::Failed(_)) && e.pins == 0; |
| 554 | self.stats.current_pins -= 1; |
| 555 | if free_failed { |
| 556 | self.slots[slot as usize] = None; |
| 557 | self.free.insert(slot); |
| 558 | } |
| 559 | Ok(()) |
| 560 | } |
| 561 | |
| 562 | /// The slot that the next miss would evict, if no slot is free. |
| 563 | pub fn next_victim(&self) -> Option<SlotId> { |
| 564 | if self.free.is_empty() { |
| 565 | self.lru_victim() |
| 566 | } else { |
| 567 | None |
| 568 | } |
| 569 | } |
| 570 | |
| 571 | /// Check every internal invariant. For tests and debug assertions. |
| 572 | pub fn check_invariants(&self) -> Result<(), String> { |
| 573 | let mut pins = 0u64; |
| 574 | let mut in_flight = 0u32; |
| 575 | let mut in_flight_bytes = 0u64; |
| 576 | let mut resident = 0u64; |
| 577 | let mut generations = BTreeSet::new(); |
| 578 | for (i, s) in self.slots.iter().enumerate() { |
| 579 | let slot = i as SlotId; |
| 580 | match s { |
| 581 | None => { |
| 582 | if !self.free.contains(&slot) { |
| 583 | return Err(format!("empty slot {slot} not on free list")); |
| 584 | } |
| 585 | } |
| 586 | Some(e) => { |
| 587 | if self.free.contains(&slot) { |
| 588 | return Err(format!("occupied slot {slot} on free list")); |
| 589 | } |
| 590 | if !generations.insert(e.generation) || e.generation >= self.next_generation { |
| 591 | return Err(format!("slot {slot} bad generation {}", e.generation)); |
| 592 | } |
| 593 | if e.bytes == 0 || e.bytes > self.ledger.slot_bytes { |
| 594 | return Err(format!("slot {slot} bad size {}", e.bytes)); |
| 595 | } |
| 596 | pins += u64::from(e.pins); |
| 597 | match e.phase { |
| 598 | Phase::Failed(_) => { |
| 599 | if e.pins == 0 { |
| 600 | return Err(format!("failed slot {slot} held with no pins")); |
| 601 | } |
| 602 | if self.index.get(&e.key) == Some(&slot) { |
| 603 | return Err(format!("failed slot {slot} still indexed")); |
| 604 | } |
| 605 | } |
| 606 | _ => { |
| 607 | if self.index.get(&e.key) != Some(&slot) { |
| 608 | return Err(format!("slot {slot} not indexed by its key")); |
| 609 | } |
| 610 | } |
| 611 | } |
| 612 | if e.in_flight() { |
| 613 | in_flight += 1; |
| 614 | in_flight_bytes += e.bytes; |
| 615 | } |
| 616 | if e.phase == Phase::Ready { |
| 617 | resident += e.bytes; |
| 618 | } |
| 619 | } |
| 620 | } |
| 621 | } |
| 622 | for (k, &slot) in &self.index { |
| 623 | match self.slots.get(slot as usize).and_then(Option::as_ref) { |
| 624 | Some(e) if &e.key == k => {} |
| 625 | _ => return Err(format!("index entry {k:?} -> {slot} dangling")), |
| 626 | } |
| 627 | } |
| 628 | let s = &self.stats; |
| 629 | if pins != s.current_pins { |
| 630 | return Err(format!("pins {pins} != counter {}", s.current_pins)); |
| 631 | } |
| 632 | if in_flight != s.current_in_flight || in_flight_bytes != s.current_in_flight_bytes { |
| 633 | return Err("in-flight counters drifted".into()); |
| 634 | } |
| 635 | if in_flight > self.max_in_flight || in_flight_bytes > self.max_in_flight_bytes { |
| 636 | return Err("in-flight limits exceeded".into()); |
| 637 | } |
| 638 | if resident != s.current_resident_bytes || resident > self.ledger.expert_pool_bytes { |
| 639 | return Err(format!("resident bytes {resident} inconsistent")); |
| 640 | } |
| 641 | if s.peak_in_flight_bytes > self.ledger.staging_bytes |
| 642 | || s.peak_resident_bytes > self.ledger.expert_pool_bytes |
| 643 | { |
| 644 | return Err("high-water mark above reservation".into()); |
| 645 | } |
| 646 | Ok(()) |
| 647 | } |
| 648 | |
| 649 | // ---- internals ---- |
| 650 | |
| 651 | fn tick(&mut self) -> u64 { |
| 652 | self.clock += 1; |
| 653 | self.clock |
| 654 | } |
| 655 | |
| 656 | fn entry(&self, slot: SlotId) -> &Entry<K> { |
| 657 | self.slots[slot as usize].as_ref().expect("occupied slot") |
| 658 | } |
| 659 | |
| 660 | fn lru_victim(&self) -> Option<SlotId> { |
| 661 | self.slots |
| 662 | .iter() |
| 663 | .enumerate() |
| 664 | .filter_map(|(i, s)| { |
| 665 | s.as_ref() |
| 666 | .filter(|e| e.evictable()) |
| 667 | .map(|e| (e.last_use, i)) |
| 668 | }) |
| 669 | .min() |
| 670 | .map(|(_, i)| i as SlotId) |
| 671 | } |
| 672 | |
| 673 | fn exhaustion(&self) -> Refusal { |
| 674 | let pinned = self.slots.iter().flatten().filter(|e| e.pins > 0).count() as u32; |
| 675 | Refusal::PinnedExhaustion { |
| 676 | slots: self.ledger.slot_count, |
| 677 | pinned, |
| 678 | in_flight: self.stats.current_in_flight, |
| 679 | } |
| 680 | } |
| 681 | |
| 682 | fn evict(&mut self, slot: SlotId) { |
| 683 | let e = self.slots[slot as usize].take().expect("victim"); |
| 684 | debug_assert!(e.evictable()); |
| 685 | self.index.remove(&e.key); |
| 686 | self.stats.current_resident_bytes -= e.bytes; |
| 687 | self.stats.evictions += 1; |
| 688 | } |
| 689 | |
| 690 | fn finish_in_flight(&mut self, slot: SlotId) { |
| 691 | let bytes = self.entry(slot).bytes; |
| 692 | self.stats.current_in_flight -= 1; |
| 693 | self.stats.current_in_flight_bytes -= bytes; |
| 694 | } |
| 695 | |
| 696 | fn check_ticket(&self, t: &FetchTicket) -> Result<SlotId, Refusal> { |
| 697 | match self.slots.get(t.slot as usize).and_then(Option::as_ref) { |
| 698 | Some(e) if e.generation == t.generation => Ok(t.slot), |
| 699 | _ => Err(Refusal::StaleTicket { |
| 700 | slot: t.slot, |
| 701 | generation: t.generation, |
| 702 | }), |
| 703 | } |
| 704 | } |
| 705 | |
| 706 | fn pinned_entry(&self, pin: &Pin) -> Result<&Entry<K>, Refusal> { |
| 707 | match self.slots.get(pin.slot as usize).and_then(Option::as_ref) { |
| 708 | Some(e) if e.generation == pin.generation && e.pins > 0 => Ok(e), |
| 709 | _ => Err(Refusal::StalePin { |
| 710 | slot: pin.slot, |
| 711 | generation: pin.generation, |
| 712 | }), |
| 713 | } |
| 714 | } |
| 715 | |
| 716 | fn step(&mut self, ticket: &FetchTicket, from: Phase, to: Phase) -> Result<(), Refusal> { |
| 717 | let slot = self.check_ticket(ticket)?; |
| 718 | let e = self.slots[slot as usize].as_mut().expect("slot"); |
| 719 | if e.phase != from { |
| 720 | return Err(Refusal::WrongPhase { |
| 721 | slot, |
| 722 | expected: from, |
| 723 | found: e.phase, |
| 724 | }); |
| 725 | } |
| 726 | e.phase = to; |
| 727 | Ok(()) |
| 728 | } |
| 729 | } |