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-runtime / src / kv_residency.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Persistent KV in the runtime (cut C6, ADR 0003 sections 5, 6, 7.3 and 8): |
| 17 | //! park at the scheduler's finish transaction, restore at submit, and the |
| 18 | //! per-sequence residency states that keep both honest. |
| 19 | //! |
| 20 | //! Who runs what (ADR 5.4 and 8): |
| 21 | //! |
| 22 | //! * **S1 finish-fork** runs in [`ParkHook::on_finish`], inside the scheduler's |
| 23 | //! finish transaction under the KV write guard it already holds, before the |
| 24 | //! sequence's own `free_sequence`. It only forks one holder per chunk |
| 25 | //! (`fork_range`) and pushes a [`ParkIntent`] to an outbox. No store call |
| 26 | //! except the O(keys) index `lookup`, no I/O. |
| 27 | //! * The spine drains the outbox right after the scheduler step returns and |
| 28 | //! calls `submit_store` for each intent with no lock held. |
| 29 | //! * **S2 restore-alloc** runs on the spine thread in `submit_*`: one holder |
| 30 | //! per chunk, refused when the pool would fall below the scheduler's |
| 31 | //! watermark. |
| 32 | //! * **S3 restore-commit** runs on the spine thread at the start of `step`, |
| 33 | //! after `poll`, never on the storage worker: verify the incarnation and that |
| 34 | //! every job of the transaction is `Completed`, `assemble_table`, the |
| 35 | //! backend's `restore_sequence`, then the scheduler's |
| 36 | //! `admit_restored_prefix`. |
| 37 | //! * **S4 holder-release** is the release callback of each holder guard. It |
| 38 | //! takes the KV write lock, so a guard is never dropped while this thread |
| 39 | //! holds that lock (every drop below happens after the guard was released). |
| 40 | //! |
| 41 | //! States (ADR 5.1). `Resident` is the absence of an entry. A park does not |
| 42 | //! need a per-sequence state: the sequence is freed after the fork, and the |
| 43 | //! park jobs are tracked by job id until their terminals. |
| 44 | //! |
| 45 | //! ```text |
| 46 | //! submit: chain hit --S2--> Restoring{txn} |
| 47 | //! Restoring --every job Completed + S3--> Prefilling --suffix prefilled--> Resident |
| 48 | //! Restoring --any job fails / cancelled--> Draining{txn} --every job terminal--> Failed |
| 49 | //! Failed --plain prefill started--> Resident |
| 50 | //! ``` |
| 51 | //! |
| 52 | //! A completion is committed only if its incarnation `(seq_id, epoch)` equals |
| 53 | //! the transaction's and the scheduler still knows the sequence; anything else |
| 54 | //! is counted in `store_stale_completions_total` and only drops its holder copy. |
| 55 | |
| 56 | use std::collections::HashMap; |
| 57 | use std::sync::Arc; |
| 58 | use std::time::{SystemTime, UNIX_EPOCH}; |
| 59 | |
| 60 | use aien_abi_core::AienInferenceBackend; |
| 61 | use aien_kv_cache::{holder_id, AienKvManager, KvLayout, SharedKvManager, SuffixPolicy}; |
| 62 | use aien_kv_store::holder::HolderGenerations; |
| 63 | use aien_kv_store::worker::{LoadTicket, StorageWorker}; |
| 64 | use aien_kv_store::{ |
| 65 | chunk_chain, ChunkHeader, ChunkKey, Completion, HolderGuard, Incarnation, JobId, KvError, |
| 66 | KvStore, LandingHolder, LayoutStrides, NamespaceFields, NamespaceId, PinToken, PinnedDest, |
| 67 | PinnedSource, PublishOutcome, Terminal, |
| 68 | }; |
| 69 | use aien_platform::PlatformError; |
| 70 | use aien_scheduler::{AienScheduler, FinishContext, FinishHook, SequenceId, SequencePhase}; |
| 71 | use parking_lot::Mutex; |
| 72 | |
| 73 | /// Completions drained per `poll` call; the loop repeats until the queue is empty. |
| 74 | const POLL_BATCH: usize = 256; |
| 75 | |
| 76 | /// Chain heads remembered by the retry window at once. Past it a new failure |
| 77 | /// is not recorded (that head keeps being looked up), so memory stays bounded |
| 78 | /// whatever the request mix (DOCS SILENT on a bound; C7 choice). |
| 79 | const RETRY_HEADS_MAX: usize = 4096; |
| 80 | |
| 81 | /// A monotonic millisecond clock. The daemon uses [`monotonic_ms_clock`]; |
| 82 | /// tests inject their own so no assertion depends on wall-clock sleeps. |
| 83 | pub type Clock = Arc<dyn Fn() -> u64 + Send + Sync>; |
| 84 | |
| 85 | /// Milliseconds since the clock was made, from `std::time::Instant`. |
| 86 | pub fn monotonic_ms_clock() -> Clock { |
| 87 | let t0 = std::time::Instant::now(); |
| 88 | Arc::new(move || t0.elapsed().as_millis() as u64) |
| 89 | } |
| 90 | |
| 91 | /// What the daemon needs at shutdown: the storage worker and the configured |
| 92 | /// intake deadline. [`KvDrainHandle::drain`] blocks for at most about the |
| 93 | /// deadline (ADR 7.5); run it off the async runtime's worker threads. |
| 94 | pub struct KvDrainHandle { |
| 95 | store: Arc<StorageWorker>, |
| 96 | deadline_ms: u64, |
| 97 | } |
| 98 | |
| 99 | impl KvDrainHandle { |
| 100 | /// Stops intake, cancels what has not started, lets jobs past the file |
| 101 | /// sync finish, and returns at the deadline with every unfinished job |
| 102 | /// named. Nothing is freed to meet the deadline: the worker keeps each |
| 103 | /// job's buffers until its terminal completion. |
| 104 | pub fn drain(&self) -> aien_kv_store::DrainReport { |
| 105 | self.store.shutdown(self.deadline_ms) |
| 106 | } |
| 107 | |
| 108 | pub fn deadline_ms(&self) -> u64 { |
| 109 | self.deadline_ms |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | /// The byte strides of the pool layout as the namespace records them (ADR 1.2 |
| 114 | /// field 10). |
| 115 | pub fn layout_strides(layout: &KvLayout) -> LayoutStrides { |
| 116 | LayoutStrides { |
| 117 | head_stride: layout.head_stride_bytes as u64, |
| 118 | token_stride: layout.token_stride_bytes as u64, |
| 119 | kv_plane_stride: layout.kv_plane_stride_bytes as u64, |
| 120 | layer_stride: layout.layer_stride_bytes as u64, |
| 121 | block_stride: layout.block_stride_bytes as u64, |
| 122 | element_bytes: layout.element_bytes as u64, |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | /// Settings of the residency layer (METRICS_AND_SETTINGS). |
| 127 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 128 | pub struct KvResidencyConfig { |
| 129 | /// `AIEN_KV_CHUNK_BLOCKS`: chunk size in pool blocks. |
| 130 | pub chunk_blocks: u32, |
| 131 | /// `AIEN_KV_CONTEXT_TOKENS`: the restorable prefix never exceeds it. |
| 132 | pub context_cap: Option<usize>, |
| 133 | /// `AIEN_KV_RESTORE_MAX_BLOCKS`: holder blocks of restores in flight at once. |
| 134 | pub restore_max_blocks: usize, |
| 135 | /// `AIEN_KV_PARK`. |
| 136 | pub park: bool, |
| 137 | /// `AIEN_KV_RESTORE`. |
| 138 | pub restore: bool, |
| 139 | /// `AIEN_KV_RESTORE_RETRY_WINDOW_MS`: after two failed restores of one |
| 140 | /// chain head within this many milliseconds, that head is prefilled |
| 141 | /// without a lookup until the older failure leaves the window. |
| 142 | pub restore_retry_window_ms: u64, |
| 143 | /// `AIEN_KV_STORE_DRAIN_MS` (parsed by `WorkerConfig`): the shutdown intake |
| 144 | /// deadline handed to the store (ADR 7.5). |
| 145 | pub drain_ms: u64, |
| 146 | } |
| 147 | |
| 148 | /// The namespace inputs with owned strings, so the residency layer can live as |
| 149 | /// long as the runtime. [`KvIdentity::fields`] lends them back as the |
| 150 | /// borrowed [`NamespaceFields`] the codec takes. |
| 151 | #[derive(Debug, Clone)] |
| 152 | pub struct KvIdentity { |
| 153 | template: NamespaceFields<'static>, |
| 154 | model_digest_kind: String, |
| 155 | model_id: String, |
| 156 | sharing_namespace: String, |
| 157 | namespace: NamespaceId, |
| 158 | } |
| 159 | |
| 160 | impl KvIdentity { |
| 161 | /// Copies `fields` and computes the namespace id (refused as the codec |
| 162 | /// refuses it). |
| 163 | pub fn new(fields: &NamespaceFields<'_>) -> Result<Self, KvError> { |
| 164 | let namespace = fields.namespace_id()?; |
| 165 | Ok(Self { |
| 166 | template: NamespaceFields { |
| 167 | model_digest_kind: "", |
| 168 | model_id: "", |
| 169 | sharing_namespace: "", |
| 170 | ..*fields |
| 171 | }, |
| 172 | model_digest_kind: fields.model_digest_kind.to_string(), |
| 173 | model_id: fields.model_id.to_string(), |
| 174 | sharing_namespace: fields.sharing_namespace.to_string(), |
| 175 | namespace, |
| 176 | }) |
| 177 | } |
| 178 | |
| 179 | pub fn fields(&self) -> NamespaceFields<'_> { |
| 180 | NamespaceFields { |
| 181 | model_digest_kind: &self.model_digest_kind, |
| 182 | model_id: &self.model_id, |
| 183 | sharing_namespace: &self.sharing_namespace, |
| 184 | ..self.template |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | pub fn namespace(&self) -> NamespaceId { |
| 189 | self.namespace |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | /// Counters (METRICS_AND_SETTINGS names without the `kv_` prefix). |
| 194 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 195 | pub struct KvResidencyStats { |
| 196 | /// Chunks forked into holders at a finish transaction (S1). |
| 197 | pub park_intents_total: u64, |
| 198 | /// Finish transactions with nothing to park (no computed prefix, table not |
| 199 | /// computed, no pool, or parking off). |
| 200 | pub park_skipped_total: u64, |
| 201 | /// Chunks not parked because the store already has them, or a store of the |
| 202 | /// same key was already in flight. |
| 203 | pub park_dedup_total: u64, |
| 204 | /// Park jobs accepted by the store. |
| 205 | pub park_jobs_total: u64, |
| 206 | pub park_bytes_total: u64, |
| 207 | /// Park jobs whose terminal reported publication. |
| 208 | pub park_published_total: u64, |
| 209 | /// Refused at submit, or ended failed or cancelled. |
| 210 | pub park_failed_total: u64, |
| 211 | /// Finish hooks that failed (the sequence was freed anyway). |
| 212 | pub park_hook_failed_total: u64, |
| 213 | /// Restore loads this runtime started or attached to. |
| 214 | pub restore_jobs_total: u64, |
| 215 | pub restore_bytes_total: u64, |
| 216 | /// Loads that attached to an in-flight load of the same key (ADR 7.3). |
| 217 | pub restore_coalesced_total: u64, |
| 218 | /// Transactions that ended without a restore after a job failed. |
| 219 | pub restore_failed_total: u64, |
| 220 | /// Requests that got a plain prefill instead of a restore (miss, refusal or failure). |
| 221 | pub restore_fallback_prefill_total: u64, |
| 222 | /// S2 refusals because the pool would fall below the watermark. |
| 223 | pub restore_refused_watermark_total: u64, |
| 224 | /// Transactions committed (S3 and the scheduler admission succeeded). |
| 225 | pub restore_committed_total: u64, |
| 226 | pub restore_tokens_total: u64, |
| 227 | /// Restore transactions abandoned because their request left the scheduler. |
| 228 | pub restore_abandoned_total: u64, |
| 229 | /// Park publications reported `Indeterminate` (served, durability unknown; |
| 230 | /// ADR 2.4), whatever the terminal says (the adapters report it on a |
| 231 | /// failed terminal after the rename). |
| 232 | pub park_indeterminate_total: u64, |
| 233 | /// Requests prefilled without a lookup because their chain head failed |
| 234 | /// twice within the retry window. Also counted as fallbacks. |
| 235 | pub restore_retry_suppressed_total: u64, |
| 236 | pub store_stale_completions_total: u64, |
| 237 | pub store_cancelled_total: u64, |
| 238 | pub store_queue_full_total: u64, |
| 239 | } |
| 240 | |
| 241 | /// One sequence's residency (ADR 5.1). `Resident` means "no entry". |
| 242 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 243 | pub enum ResidencyState { |
| 244 | Resident, |
| 245 | Restoring, |
| 246 | Draining, |
| 247 | Failed, |
| 248 | Prefilling, |
| 249 | } |
| 250 | |
| 251 | /// A point-in-time view for status lines and tests. |
| 252 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 253 | pub struct KvResidencyStatus { |
| 254 | pub stats: KvResidencyStats, |
| 255 | pub restoring: usize, |
| 256 | pub draining: usize, |
| 257 | pub failed: usize, |
| 258 | pub prefilling: usize, |
| 259 | /// Park jobs between submit and their terminal. |
| 260 | pub parking_jobs: usize, |
| 261 | /// `kv_pool_holder_blocks`. |
| 262 | pub holder_blocks: usize, |
| 263 | /// `kv_restore_inflight_blocks`: holder blocks of restores not yet adopted |
| 264 | /// or drained. |
| 265 | pub restore_inflight_blocks: usize, |
| 266 | /// Waiters of this runtime still expecting a terminal from an in-flight |
| 267 | /// restore load: the opener plus every attached waiter, summed over the |
| 268 | /// landings. Zero once every restore is terminal; anything else after that |
| 269 | /// is a leak of the attached-waiter count. |
| 270 | pub landing_waiters: usize, |
| 271 | } |
| 272 | |
| 273 | /// What S1 hands the spine: one chunk's holder and header. |
| 274 | #[derive(Debug)] |
| 275 | pub struct ParkIntent { |
| 276 | holder: u64, |
| 277 | generation: u32, |
| 278 | blocks: Vec<usize>, |
| 279 | tail_valid: u32, |
| 280 | header: ChunkHeader, |
| 281 | inc: Incarnation, |
| 282 | } |
| 283 | |
| 284 | /// The part shared by the finish hook (scheduler side) and the spine. |
| 285 | struct Shared { |
| 286 | kv: SharedKvManager, |
| 287 | store: Arc<StorageWorker>, |
| 288 | identity: KvIdentity, |
| 289 | chunk_tokens: usize, |
| 290 | block_size: usize, |
| 291 | park: bool, |
| 292 | /// Leaf lock; taken under the KV lock (S1, S2) or with no lock held (S4). |
| 293 | gens: Arc<Mutex<HolderGenerations>>, |
| 294 | /// Leaf lock held for one push or one take (ADR 8 rule 4). |
| 295 | outbox: Mutex<Vec<ParkIntent>>, |
| 296 | hook_counts: Mutex<HookCounts>, |
| 297 | } |
| 298 | |
| 299 | #[derive(Default)] |
| 300 | struct HookCounts { |
| 301 | intents: u64, |
| 302 | skipped: u64, |
| 303 | dedup: u64, |
| 304 | failed: u64, |
| 305 | } |
| 306 | |
| 307 | fn now_unix_ns() -> u64 { |
| 308 | SystemTime::now() |
| 309 | .duration_since(UNIX_EPOCH) |
| 310 | .map(|d| d.as_nanos() as u64) |
| 311 | .unwrap_or(0) |
| 312 | } |
| 313 | |
| 314 | /// The guard of one holder: dropping it frees the holder's table (S4) and then |
| 315 | /// its generation. Never dropped while the dropping thread holds the KV lock. |
| 316 | fn holder_guard( |
| 317 | kv: &SharedKvManager, |
| 318 | gens: &Arc<Mutex<HolderGenerations>>, |
| 319 | holder: u64, |
| 320 | generation: u32, |
| 321 | ) -> HolderGuard { |
| 322 | let kv = kv.clone(); |
| 323 | let gens = gens.clone(); |
| 324 | HolderGuard::new(move || { |
| 325 | let _ = kv.write().free_sequence(holder); |
| 326 | gens.lock().release(generation); |
| 327 | }) |
| 328 | } |
| 329 | |
| 330 | /// Allocates a holder generation and id. The generation is released on refusal. |
| 331 | fn alloc_holder(gens: &Mutex<HolderGenerations>) -> Result<(u64, u32), String> { |
| 332 | let generation = gens |
| 333 | .lock() |
| 334 | .alloc() |
| 335 | .map_err(|e| format!("holder generations: {e:?}"))?; |
| 336 | match holder_id(u64::from(generation)) { |
| 337 | Ok(id) => Ok((id, generation)), |
| 338 | Err(e) => { |
| 339 | gens.lock().release(generation); |
| 340 | Err(e) |
| 341 | } |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | /// S1 (ADR 6.1): installed as the scheduler's finish hook. |
| 346 | pub struct ParkHook { |
| 347 | shared: Arc<Shared>, |
| 348 | } |
| 349 | |
| 350 | impl ParkHook { |
| 351 | fn skip(&self) -> Result<(), String> { |
| 352 | self.shared.hook_counts.lock().skipped += 1; |
| 353 | Ok(()) |
| 354 | } |
| 355 | |
| 356 | /// Frees holders forked so far in this transaction (we hold the KV guard, |
| 357 | /// so this is a direct free, not a guard drop). |
| 358 | fn undo(&self, kv: &mut AienKvManager, made: Vec<ParkIntent>) { |
| 359 | for it in made { |
| 360 | let _ = kv.free_sequence(it.holder); |
| 361 | self.shared.gens.lock().release(it.generation); |
| 362 | } |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | impl FinishHook for ParkHook { |
| 367 | fn on_finish(&self, kv: &mut AienKvManager, ctx: &FinishContext<'_>) -> Result<(), String> { |
| 368 | let sh = &self.shared; |
| 369 | if !sh.park { |
| 370 | return self.skip(); |
| 371 | } |
| 372 | let Some(prefix) = ctx.computed_prefix.as_deref() else { |
| 373 | return self.skip(); |
| 374 | }; |
| 375 | if prefix.is_empty() || kv.pool().is_none() { |
| 376 | return self.skip(); |
| 377 | } |
| 378 | match kv.get_block_table(ctx.request_id) { |
| 379 | Some(t) |
| 380 | if t.prefill_state.is_ready() |
| 381 | && t.total_tokens >= prefix.len() |
| 382 | && t.block_ids.len() * sh.block_size >= prefix.len() => {} |
| 383 | _ => return self.skip(), |
| 384 | } |
| 385 | let fields = sh.identity.fields(); |
| 386 | let ns = sh.identity.namespace(); |
| 387 | let keys = chunk_chain(&ns, sh.chunk_tokens as u32, prefix).map_err(|e| { |
| 388 | sh.hook_counts.lock().failed += 1; |
| 389 | format!("park: key chain: {e}") |
| 390 | })?; |
| 391 | // Index-only lookup (ADR 8 rule 3; lock order KV -> store index). |
| 392 | let found = sh.store.lookup(&keys); |
| 393 | let inc = Incarnation::seq(ctx.request_id); |
| 394 | let written = now_unix_ns(); |
| 395 | let mut made: Vec<ParkIntent> = Vec::new(); |
| 396 | let mut dedup = 0u64; |
| 397 | for (i, key) in keys.iter().enumerate() { |
| 398 | if found.get(i).copied().flatten().is_some() { |
| 399 | dedup += 1; |
| 400 | continue; |
| 401 | } |
| 402 | let first = i * sh.chunk_tokens; |
| 403 | let tokens = (prefix.len() - first).min(sh.chunk_tokens); |
| 404 | let first_block = first / sh.block_size; |
| 405 | let n_blocks = tokens.div_ceil(sh.block_size); |
| 406 | let tail_valid = (tokens - (n_blocks - 1) * sh.block_size) as u32; |
| 407 | let header = match fields.chunk_header( |
| 408 | &ns, |
| 409 | *key, |
| 410 | i.checked_sub(1).map(|p| &keys[p]), |
| 411 | first as u32, |
| 412 | tokens as u32, |
| 413 | written, |
| 414 | ) { |
| 415 | Ok(h) => h, |
| 416 | Err(e) => { |
| 417 | self.undo(kv, made); |
| 418 | sh.hook_counts.lock().failed += 1; |
| 419 | return Err(format!("park: header: {e}")); |
| 420 | } |
| 421 | }; |
| 422 | let (holder, generation) = match alloc_holder(&sh.gens) { |
| 423 | Ok(v) => v, |
| 424 | Err(e) => { |
| 425 | self.undo(kv, made); |
| 426 | sh.hook_counts.lock().failed += 1; |
| 427 | return Err(format!("park: {e}")); |
| 428 | } |
| 429 | }; |
| 430 | match kv.fork_range(ctx.request_id, first_block, n_blocks, holder) { |
| 431 | Ok(blocks) => made.push(ParkIntent { |
| 432 | holder, |
| 433 | generation, |
| 434 | blocks, |
| 435 | tail_valid, |
| 436 | header, |
| 437 | inc, |
| 438 | }), |
| 439 | Err(e) => { |
| 440 | sh.gens.lock().release(generation); |
| 441 | self.undo(kv, made); |
| 442 | sh.hook_counts.lock().failed += 1; |
| 443 | return Err(format!("park: fork_range: {e}")); |
| 444 | } |
| 445 | } |
| 446 | } |
| 447 | { |
| 448 | let mut c = sh.hook_counts.lock(); |
| 449 | c.intents += made.len() as u64; |
| 450 | c.dedup += dedup; |
| 451 | } |
| 452 | sh.outbox.lock().extend(made); |
| 453 | Ok(()) |
| 454 | } |
| 455 | } |
| 456 | |
| 457 | #[derive(Debug)] |
| 458 | enum SlotState { |
| 459 | Pending, |
| 460 | /// Completed and validated; the landing holder copy is kept until S3 |
| 461 | /// adopted its blocks (or the transaction drained). |
| 462 | Completed(Option<LandingHolder>), |
| 463 | /// Failed or cancelled terminal received. |
| 464 | Ended, |
| 465 | } |
| 466 | |
| 467 | #[derive(Debug)] |
| 468 | struct ChunkSlot { |
| 469 | job: JobId, |
| 470 | holder: u64, |
| 471 | state: SlotState, |
| 472 | } |
| 473 | |
| 474 | #[derive(Debug)] |
| 475 | struct RestoreTxn { |
| 476 | inc: Incarnation, |
| 477 | /// The first chunk key of the prompt chain (retry-window bookkeeping). |
| 478 | head: ChunkKey, |
| 479 | restored: usize, |
| 480 | blocks: usize, |
| 481 | chunks: Vec<ChunkSlot>, |
| 482 | pin: Option<PinToken>, |
| 483 | } |
| 484 | |
| 485 | impl RestoreTxn { |
| 486 | fn pending(&self) -> usize { |
| 487 | self.chunks |
| 488 | .iter() |
| 489 | .filter(|c| matches!(c.state, SlotState::Pending)) |
| 490 | .count() |
| 491 | } |
| 492 | |
| 493 | fn completed(&self) -> usize { |
| 494 | self.chunks |
| 495 | .iter() |
| 496 | .filter(|c| matches!(c.state, SlotState::Completed(_))) |
| 497 | .count() |
| 498 | } |
| 499 | |
| 500 | /// Takes every landing holder copy out of the transaction (the caller drops |
| 501 | /// them with no lock held). |
| 502 | fn take_landings(&mut self) -> Vec<LandingHolder> { |
| 503 | self.chunks |
| 504 | .iter_mut() |
| 505 | .filter_map(|c| match &mut c.state { |
| 506 | SlotState::Completed(h) => h.take(), |
| 507 | _ => None, |
| 508 | }) |
| 509 | .collect() |
| 510 | } |
| 511 | } |
| 512 | |
| 513 | #[derive(Debug)] |
| 514 | struct Entry { |
| 515 | seq: SequenceId, |
| 516 | state: ResidencyState, |
| 517 | epoch: u32, |
| 518 | txn: Option<RestoreTxn>, |
| 519 | } |
| 520 | |
| 521 | impl Entry { |
| 522 | fn transition(&mut self, state: ResidencyState) { |
| 523 | self.state = state; |
| 524 | self.epoch = self.epoch.wrapping_add(1); |
| 525 | } |
| 526 | } |
| 527 | |
| 528 | /// S2 output: (holder id, generation, blocks) per chunk, the pool base and |
| 529 | /// the block size. |
| 530 | type Allocated = (Vec<(u64, u32, Vec<usize>)>, *mut u8, usize); |
| 531 | |
| 532 | /// A restore load another transaction of this runtime may attach to: which |
| 533 | /// holder the bytes land in, and how many of our waiters still expect a |
| 534 | /// terminal. |
| 535 | #[derive(Debug)] |
| 536 | struct Landing { |
| 537 | holder: u64, |
| 538 | waiters: u32, |
| 539 | } |
| 540 | |
| 541 | /// The spine-owned residency map and the park/restore machinery. |
| 542 | pub struct KvResidency { |
| 543 | shared: Arc<Shared>, |
| 544 | config: KvResidencyConfig, |
| 545 | watermark_blocks: usize, |
| 546 | entries: HashMap<u64, Entry>, |
| 547 | /// Park jobs in flight: job -> payload bytes. |
| 548 | parks: HashMap<JobId, u64>, |
| 549 | landings: HashMap<JobId, Landing>, |
| 550 | restore_inflight_blocks: usize, |
| 551 | stats: KvResidencyStats, |
| 552 | /// Milliseconds on a monotonic clock (injected by tests). |
| 553 | clock: Clock, |
| 554 | /// Chain head -> times (ms) of its failed restores still inside the window. |
| 555 | retry_failures: HashMap<ChunkKey, Vec<u64>>, |
| 556 | } |
| 557 | |
| 558 | impl KvResidency { |
| 559 | /// `store` must serve `identity`'s namespace; `kv` must be the pooled |
| 560 | /// manager the scheduler and the backend share. Chunks are whole blocks |
| 561 | /// (`chunk_blocks * block_size` tokens), which is what the identity's |
| 562 | /// `chunk_tokens` must say. |
| 563 | pub fn new( |
| 564 | config: KvResidencyConfig, |
| 565 | identity: KvIdentity, |
| 566 | store: Arc<StorageWorker>, |
| 567 | kv: SharedKvManager, |
| 568 | ) -> Result<Self, String> { |
| 569 | let fields = identity.fields(); |
| 570 | let block_size = kv.read().block_size(); |
| 571 | if config.chunk_blocks == 0 || block_size == 0 { |
| 572 | return Err("kv residency: chunk_blocks and block_size must be nonzero".into()); |
| 573 | } |
| 574 | let chunk_tokens = config.chunk_blocks as usize * block_size; |
| 575 | if fields.block_size as usize != block_size || fields.chunk_tokens as usize != chunk_tokens |
| 576 | { |
| 577 | return Err(format!( |
| 578 | "kv residency: identity says block {} chunk {}, pool says block {block_size} chunk {chunk_tokens}", |
| 579 | fields.block_size, fields.chunk_tokens |
| 580 | )); |
| 581 | } |
| 582 | if store.namespace() != identity.namespace() { |
| 583 | return Err("kv residency: store namespace differs from the identity".into()); |
| 584 | } |
| 585 | { |
| 586 | let guard = kv.read(); |
| 587 | let pool = guard |
| 588 | .pool() |
| 589 | .ok_or("kv residency: the KV manager has no tensor pool")?; |
| 590 | if pool.block_bytes() as u64 != fields.layout.block_stride { |
| 591 | return Err("kv residency: pool block bytes differ from the layout".into()); |
| 592 | } |
| 593 | } |
| 594 | let park = config.park; |
| 595 | Ok(Self { |
| 596 | shared: Arc::new(Shared { |
| 597 | kv, |
| 598 | store, |
| 599 | identity, |
| 600 | chunk_tokens, |
| 601 | block_size, |
| 602 | park, |
| 603 | gens: Arc::new(Mutex::new(HolderGenerations::new())), |
| 604 | outbox: Mutex::new(Vec::new()), |
| 605 | hook_counts: Mutex::new(HookCounts::default()), |
| 606 | }), |
| 607 | config, |
| 608 | watermark_blocks: 0, |
| 609 | entries: HashMap::new(), |
| 610 | parks: HashMap::new(), |
| 611 | landings: HashMap::new(), |
| 612 | restore_inflight_blocks: 0, |
| 613 | stats: KvResidencyStats::default(), |
| 614 | clock: monotonic_ms_clock(), |
| 615 | retry_failures: HashMap::new(), |
| 616 | }) |
| 617 | } |
| 618 | |
| 619 | /// The scheduler hook (S1). The spine installs it. |
| 620 | pub fn finish_hook(&self) -> Arc<dyn FinishHook> { |
| 621 | Arc::new(ParkHook { |
| 622 | shared: self.shared.clone(), |
| 623 | }) |
| 624 | } |
| 625 | |
| 626 | /// Replaces the retry-window clock (tests). |
| 627 | pub fn set_clock(&mut self, clock: Clock) { |
| 628 | self.clock = clock; |
| 629 | } |
| 630 | |
| 631 | /// The store's admission state and accounting (`kv_store_*` status fields). |
| 632 | pub fn store_capacity(&self) -> aien_kv_store::Capacity { |
| 633 | self.shared.store.capacity() |
| 634 | } |
| 635 | |
| 636 | /// The `status` reply fields (METRICS_AND_SETTINGS names). |
| 637 | pub fn persist_report(&self) -> crate::control::KvPersistReport { |
| 638 | use aien_kv_store::StoreState; |
| 639 | let s = self.status(); |
| 640 | let c = self.store_capacity(); |
| 641 | let st = &s.stats; |
| 642 | crate::control::KvPersistReport { |
| 643 | kv_store_state: match c.state { |
| 644 | StoreState::Recovering => "recovering", |
| 645 | StoreState::Open => "open", |
| 646 | StoreState::Degraded => "degraded", |
| 647 | StoreState::Failed => "failed", |
| 648 | } |
| 649 | .to_string(), |
| 650 | kv_store_persisted_bytes: c.used_bytes, |
| 651 | kv_store_persisted_objects: c.objects + c.unindexed_objects, |
| 652 | kv_store_quota_bytes: c.quota_bytes, |
| 653 | kv_store_max_objects: c.max_objects, |
| 654 | kv_store_over_cap: c.unindexed_objects > 0 || c.used_bytes > c.quota_bytes, |
| 655 | kv_store_reserved_bytes: c.reserved_bytes, |
| 656 | kv_store_unindexed_bytes: c.unindexed_bytes, |
| 657 | kv_store_unindexed_objects: c.unindexed_objects, |
| 658 | kv_store_inflight_ops: u64::from(c.restore_ops) + u64::from(c.park_ops), |
| 659 | kv_store_inflight_bytes: c.inflight_bytes, |
| 660 | kv_store_restore_ops: u64::from(c.restore_ops), |
| 661 | kv_store_park_ops: u64::from(c.park_ops), |
| 662 | kv_restore_inflight_blocks: s.restore_inflight_blocks as u64, |
| 663 | kv_park_jobs_total: st.park_jobs_total, |
| 664 | kv_park_bytes_total: st.park_bytes_total, |
| 665 | kv_park_failed_total: st.park_failed_total, |
| 666 | kv_park_dedup_total: st.park_dedup_total, |
| 667 | kv_park_indeterminate_total: st.park_indeterminate_total, |
| 668 | kv_restore_jobs_total: st.restore_jobs_total, |
| 669 | kv_restore_bytes_total: st.restore_bytes_total, |
| 670 | kv_restore_failed_total: st.restore_failed_total, |
| 671 | kv_restore_coalesced_total: st.restore_coalesced_total, |
| 672 | kv_restore_fallback_prefill_total: st.restore_fallback_prefill_total, |
| 673 | kv_restore_retry_suppressed_total: st.restore_retry_suppressed_total, |
| 674 | kv_restore_tokens_total: st.restore_tokens_total, |
| 675 | kv_store_stale_completions_total: st.store_stale_completions_total, |
| 676 | kv_store_cancelled_total: st.store_cancelled_total, |
| 677 | kv_store_queue_full_total: st.store_queue_full_total, |
| 678 | kv_store_refused_reason: String::new(), |
| 679 | kv_store_key_refused_total: aien_kv_store::seal::key_refusals_total(), |
| 680 | kv_store_seal_rejected_total: aien_kv_store::seal::open_rejected_total(), |
| 681 | } |
| 682 | } |
| 683 | |
| 684 | /// The shutdown drain (ADR 7.5) with the configured deadline. |
| 685 | pub fn drain_handle(&self) -> KvDrainHandle { |
| 686 | KvDrainHandle { |
| 687 | store: self.shared.store.clone(), |
| 688 | deadline_ms: self.config.drain_ms, |
| 689 | } |
| 690 | } |
| 691 | |
| 692 | /// Failures of `head` still inside the window at `now`. |
| 693 | fn recent_failures(&self, head: &ChunkKey, now: u64) -> usize { |
| 694 | let window = self.config.restore_retry_window_ms; |
| 695 | self.retry_failures.get(head).map_or(0, |ts| { |
| 696 | ts.iter() |
| 697 | .filter(|&&t| now.saturating_sub(t) < window) |
| 698 | .count() |
| 699 | }) |
| 700 | } |
| 701 | |
| 702 | /// Records a failed restore of the chain starting at `head`. Only the two |
| 703 | /// newest failures matter; entries whose failures all left the window are |
| 704 | /// dropped first. |
| 705 | fn record_restore_failure(&mut self, head: ChunkKey) { |
| 706 | let now = (self.clock)(); |
| 707 | let window = self.config.restore_retry_window_ms; |
| 708 | self.retry_failures |
| 709 | .retain(|_, ts| ts.iter().any(|&t| now.saturating_sub(t) < window)); |
| 710 | if !self.retry_failures.contains_key(&head) && self.retry_failures.len() >= RETRY_HEADS_MAX |
| 711 | { |
| 712 | return; |
| 713 | } |
| 714 | let ts = self.retry_failures.entry(head).or_default(); |
| 715 | ts.push(now); |
| 716 | if ts.len() > 2 { |
| 717 | ts.remove(0); |
| 718 | } |
| 719 | } |
| 720 | |
| 721 | /// The scheduler's watermark, used by S2 (ADR 7.1). |
| 722 | pub fn set_watermark_blocks(&mut self, blocks: usize) { |
| 723 | self.watermark_blocks = blocks; |
| 724 | } |
| 725 | |
| 726 | pub fn namespace(&self) -> NamespaceId { |
| 727 | self.shared.identity.namespace() |
| 728 | } |
| 729 | |
| 730 | pub fn chunk_tokens(&self) -> usize { |
| 731 | self.shared.chunk_tokens |
| 732 | } |
| 733 | |
| 734 | pub fn residency_of(&self, seq: u64) -> ResidencyState { |
| 735 | self.entries |
| 736 | .get(&seq) |
| 737 | .map_or(ResidencyState::Resident, |e| e.state) |
| 738 | } |
| 739 | |
| 740 | /// Store job ids of `seq`'s restore transaction, in chunk order. |
| 741 | pub fn restore_jobs_of(&self, seq: u64) -> Vec<JobId> { |
| 742 | self.entries |
| 743 | .get(&seq) |
| 744 | .and_then(|e| e.txn.as_ref()) |
| 745 | .map(|t| t.chunks.iter().map(|c| c.job).collect()) |
| 746 | .unwrap_or_default() |
| 747 | } |
| 748 | |
| 749 | /// `(completed chunks, total chunks)` of `seq`'s restore transaction. |
| 750 | pub fn restore_progress(&self, seq: u64) -> Option<(usize, usize)> { |
| 751 | let t = self.entries.get(&seq)?.txn.as_ref()?; |
| 752 | Some((t.completed(), t.chunks.len())) |
| 753 | } |
| 754 | |
| 755 | pub fn status(&self) -> KvResidencyStatus { |
| 756 | let mut stats = self.stats.clone(); |
| 757 | { |
| 758 | let c = self.shared.hook_counts.lock(); |
| 759 | stats.park_intents_total = c.intents; |
| 760 | stats.park_skipped_total = c.skipped; |
| 761 | stats.park_dedup_total += c.dedup; |
| 762 | stats.park_hook_failed_total = c.failed; |
| 763 | } |
| 764 | let count = |s: ResidencyState| self.entries.values().filter(|e| e.state == s).count(); |
| 765 | KvResidencyStatus { |
| 766 | stats, |
| 767 | restoring: count(ResidencyState::Restoring), |
| 768 | draining: count(ResidencyState::Draining), |
| 769 | failed: count(ResidencyState::Failed), |
| 770 | prefilling: count(ResidencyState::Prefilling), |
| 771 | parking_jobs: self.parks.len() + self.shared.outbox.lock().len(), |
| 772 | holder_blocks: self.shared.kv.read().holder_block_count(), |
| 773 | restore_inflight_blocks: self.restore_inflight_blocks, |
| 774 | landing_waiters: self.landings.values().map(|l| l.waiters as usize).sum(), |
| 775 | } |
| 776 | } |
| 777 | |
| 778 | // ----------------------------------------------------------------------- |
| 779 | // Park: submit what S1 forked |
| 780 | // ----------------------------------------------------------------------- |
| 781 | |
| 782 | /// Submits every queued park intent (called by the spine right after the |
| 783 | /// scheduler step, with no lock held). A refused submit drops the source, |
| 784 | /// which frees its holder (S4). |
| 785 | pub fn drain_outbox(&mut self) { |
| 786 | let intents = std::mem::take(&mut *self.shared.outbox.lock()); |
| 787 | if intents.is_empty() { |
| 788 | return; |
| 789 | } |
| 790 | let base = match self.shared.kv.read().pool() { |
| 791 | Some(p) => p.base_ptr(), |
| 792 | None => return, |
| 793 | }; |
| 794 | let block_bytes = self.shared.kv.read().pool().map_or(0, |p| p.block_bytes()); |
| 795 | for it in intents { |
| 796 | let guard = holder_guard(&self.shared.kv, &self.shared.gens, it.holder, it.generation); |
| 797 | // SAFETY: the blocks belong to the pool behind `base` and are |
| 798 | // referenced by the holder table `it.holder` (fork_range in S1), so |
| 799 | // they are neither freed nor reused until the guard runs its |
| 800 | // release. Nobody writes them meanwhile: the finished sequence that |
| 801 | // wrote them is freed, and a later sharer copies on write. |
| 802 | let src = |
| 803 | unsafe { PinnedSource::new(base, block_bytes, it.blocks, it.tail_valid, guard) }; |
| 804 | let bytes = it.header.payload_len; |
| 805 | match self.shared.store.submit_store(it.header, src, it.inc) { |
| 806 | Ok(job) if self.parks.contains_key(&job) => self.stats.park_dedup_total += 1, |
| 807 | Ok(job) => { |
| 808 | self.parks.insert(job, bytes); |
| 809 | self.stats.park_jobs_total += 1; |
| 810 | self.stats.park_bytes_total += bytes; |
| 811 | } |
| 812 | Err(e) => { |
| 813 | if matches!(e, PlatformError::QueueFull) { |
| 814 | self.stats.store_queue_full_total += 1; |
| 815 | } |
| 816 | self.stats.park_failed_total += 1; |
| 817 | } |
| 818 | } |
| 819 | } |
| 820 | } |
| 821 | |
| 822 | // ----------------------------------------------------------------------- |
| 823 | // Restore at submit (S2) |
| 824 | // ----------------------------------------------------------------------- |
| 825 | |
| 826 | fn fallback(&mut self) { |
| 827 | self.stats.restore_fallback_prefill_total += 1; |
| 828 | } |
| 829 | |
| 830 | /// Looks the prompt of `seq` up in the store and, on a hit, starts its |
| 831 | /// restore: S2 allocates the destination holders, the loads are submitted |
| 832 | /// under one transaction and the request is held (`AwaitingRestore`). |
| 833 | /// Every miss or refusal leaves the request a plain waiting request. |
| 834 | pub fn try_restore(&mut self, sched: &mut AienScheduler, seq: SequenceId) { |
| 835 | if !self.config.restore { |
| 836 | return; |
| 837 | } |
| 838 | let Some(prompt) = sched.arena().get(seq).map(|r| r.prompt.clone()) else { |
| 839 | return; |
| 840 | }; |
| 841 | let ct = self.shared.chunk_tokens; |
| 842 | let bs = self.shared.block_size; |
| 843 | let mut cap = prompt.len().saturating_sub(1); |
| 844 | if let Some(c) = self.config.context_cap { |
| 845 | cap = cap.min(c); |
| 846 | } |
| 847 | if cap == 0 { |
| 848 | return self.fallback(); |
| 849 | } |
| 850 | let ns = self.shared.identity.namespace(); |
| 851 | let Ok(keys) = chunk_chain(&ns, ct as u32, &prompt[..cap]) else { |
| 852 | return self.fallback(); |
| 853 | }; |
| 854 | // Retry window: a chain head whose restore failed twice within the |
| 855 | // window is prefilled without a lookup. |
| 856 | if let Some(head) = keys.first() { |
| 857 | if self.recent_failures(head, (self.clock)()) >= 2 { |
| 858 | self.stats.restore_retry_suppressed_total += 1; |
| 859 | return self.fallback(); |
| 860 | } |
| 861 | } |
| 862 | // Walk to the first miss. The chain's last key is a partial tail only |
| 863 | // when `cap` is not a chunk multiple, and it was keyed with exactly the |
| 864 | // tokens up to the cap, so a hit there is a tail of exactly that length. |
| 865 | let hits = self.shared.store.lookup(&keys); |
| 866 | let n = hits.iter().take_while(|h| h.is_some()).count(); |
| 867 | if n == 0 { |
| 868 | return self.fallback(); |
| 869 | } |
| 870 | let spans: Vec<(usize, usize)> = (0..n) |
| 871 | .map(|i| { |
| 872 | let first = i * ct; |
| 873 | (first, (cap - first).min(ct)) |
| 874 | }) |
| 875 | .collect(); |
| 876 | let needed: usize = spans.iter().map(|&(_, t)| t.div_ceil(bs)).sum(); |
| 877 | if self.restore_inflight_blocks + needed > self.config.restore_max_blocks { |
| 878 | return self.fallback(); |
| 879 | } |
| 880 | let pin = match self.shared.store.pin(&keys[..n]) { |
| 881 | Ok(p) => p, |
| 882 | Err(e) => { |
| 883 | if matches!(e, PlatformError::QueueFull) { |
| 884 | self.stats.store_queue_full_total += 1; |
| 885 | } |
| 886 | return self.fallback(); |
| 887 | } |
| 888 | }; |
| 889 | |
| 890 | // S2 under one KV write guard; guards are built after it is released. |
| 891 | let allocated: Result<Allocated, bool> = { |
| 892 | let mut kv = self.shared.kv.write(); |
| 893 | if kv.free_block_count() < self.watermark_blocks + needed { |
| 894 | Err(true) |
| 895 | } else { |
| 896 | let mut made: Vec<(u64, u32, Vec<usize>)> = Vec::with_capacity(n); |
| 897 | let mut ok = true; |
| 898 | for &(first, tokens) in &spans { |
| 899 | let Ok((holder, generation)) = alloc_holder(&self.shared.gens) else { |
| 900 | ok = false; |
| 901 | break; |
| 902 | }; |
| 903 | match kv.allocate_sequence(holder, &prompt[first..first + tokens]) { |
| 904 | Ok(blocks) => made.push((holder, generation, blocks)), |
| 905 | Err(_) => { |
| 906 | self.shared.gens.lock().release(generation); |
| 907 | ok = false; |
| 908 | break; |
| 909 | } |
| 910 | } |
| 911 | } |
| 912 | let pool = kv.pool_mut().map(|p| (p.base_mut_ptr(), p.block_bytes())); |
| 913 | match (ok, pool) { |
| 914 | (true, Some((base, block_bytes))) => Ok((made, base, block_bytes)), |
| 915 | _ => { |
| 916 | for (holder, generation, _) in made { |
| 917 | let _ = kv.free_sequence(holder); |
| 918 | self.shared.gens.lock().release(generation); |
| 919 | } |
| 920 | Err(false) |
| 921 | } |
| 922 | } |
| 923 | } |
| 924 | }; |
| 925 | let (made, base, block_bytes) = match allocated { |
| 926 | Ok(v) => v, |
| 927 | Err(watermark) => { |
| 928 | if watermark { |
| 929 | self.stats.restore_refused_watermark_total += 1; |
| 930 | } |
| 931 | self.shared.store.unpin(pin); |
| 932 | return self.fallback(); |
| 933 | } |
| 934 | }; |
| 935 | |
| 936 | let inc = Incarnation::new(seq.to_u64(), 1); |
| 937 | let fields = self.shared.identity.fields(); |
| 938 | let mut chunks: Vec<ChunkSlot> = Vec::with_capacity(n); |
| 939 | let mut restored = 0usize; |
| 940 | let mut blocks_used = 0usize; |
| 941 | for (i, (holder, generation, blocks)) in made.into_iter().enumerate() { |
| 942 | let (first, tokens) = spans[i]; |
| 943 | let n_blocks = blocks.len(); |
| 944 | let guard = holder_guard(&self.shared.kv, &self.shared.gens, holder, generation); |
| 945 | // Once a chunk could not be submitted, later chunks are not either |
| 946 | // (the restored prefix must be contiguous); their guards free them. |
| 947 | if chunks.len() != i { |
| 948 | drop(guard); |
| 949 | continue; |
| 950 | } |
| 951 | let Ok(header) = fields.chunk_header( |
| 952 | &ns, |
| 953 | keys[i], |
| 954 | i.checked_sub(1).map(|p| &keys[p]), |
| 955 | first as u32, |
| 956 | tokens as u32, |
| 957 | 0, |
| 958 | ) else { |
| 959 | drop(guard); |
| 960 | continue; |
| 961 | }; |
| 962 | // SAFETY: the blocks were just allocated to the holder table |
| 963 | // `holder` (S2) and are invisible to the scheduler until S3 |
| 964 | // assembles them; the guard keeps them until the last landing copy |
| 965 | // is dropped. |
| 966 | let dst = unsafe { PinnedDest::new(base, block_bytes, blocks, guard) }; |
| 967 | match self |
| 968 | .shared |
| 969 | .store |
| 970 | .submit_load_coalesced(keys[i], &header, move || dst, inc) |
| 971 | { |
| 972 | Ok(LoadTicket::Started(job)) => { |
| 973 | self.landings.insert(job, Landing { holder, waiters: 1 }); |
| 974 | chunks.push(ChunkSlot { |
| 975 | job, |
| 976 | holder, |
| 977 | state: SlotState::Pending, |
| 978 | }); |
| 979 | } |
| 980 | Ok(LoadTicket::Attached(job)) => match self.landings.get_mut(&job) { |
| 981 | Some(l) => { |
| 982 | l.waiters += 1; |
| 983 | self.stats.restore_coalesced_total += 1; |
| 984 | chunks.push(ChunkSlot { |
| 985 | job, |
| 986 | holder: l.holder, |
| 987 | state: SlotState::Pending, |
| 988 | }); |
| 989 | } |
| 990 | None => { |
| 991 | // A load this runtime did not start: its landing holder |
| 992 | // is unknown here, so it cannot be assembled. Withdraw; |
| 993 | // its terminal arrives later and is counted stale. |
| 994 | let _ = self.shared.store.cancel_waiter(job, inc); |
| 995 | continue; |
| 996 | } |
| 997 | }, |
| 998 | Err(e) => { |
| 999 | if matches!(e, PlatformError::QueueFull) { |
| 1000 | self.stats.store_queue_full_total += 1; |
| 1001 | } |
| 1002 | continue; |
| 1003 | } |
| 1004 | } |
| 1005 | self.stats.restore_jobs_total += 1; |
| 1006 | self.stats.restore_bytes_total += header.payload_len; |
| 1007 | restored += tokens; |
| 1008 | blocks_used += n_blocks; |
| 1009 | } |
| 1010 | if chunks.is_empty() { |
| 1011 | self.shared.store.unpin(pin); |
| 1012 | return self.fallback(); |
| 1013 | } |
| 1014 | let mut entry = Entry { |
| 1015 | seq, |
| 1016 | state: ResidencyState::Restoring, |
| 1017 | epoch: inc.epoch, |
| 1018 | txn: Some(RestoreTxn { |
| 1019 | inc, |
| 1020 | head: keys[0], |
| 1021 | restored, |
| 1022 | blocks: blocks_used, |
| 1023 | chunks, |
| 1024 | pin: Some(pin), |
| 1025 | }), |
| 1026 | }; |
| 1027 | self.restore_inflight_blocks += blocks_used; |
| 1028 | if sched.hold_for_restore(seq).is_err() { |
| 1029 | // Not a plain waiting request after all: drain what was submitted. |
| 1030 | self.begin_drain(&mut entry); |
| 1031 | } |
| 1032 | self.entries.insert(seq.to_u64(), entry); |
| 1033 | } |
| 1034 | |
| 1035 | // ----------------------------------------------------------------------- |
| 1036 | // Completions, S3, draining |
| 1037 | // ----------------------------------------------------------------------- |
| 1038 | |
| 1039 | /// Moves a restoring entry to `Draining` and withdraws its pending loads. |
| 1040 | fn begin_drain(&mut self, entry: &mut Entry) { |
| 1041 | if entry.state == ResidencyState::Draining { |
| 1042 | return; |
| 1043 | } |
| 1044 | entry.transition(ResidencyState::Draining); |
| 1045 | if let Some(txn) = &entry.txn { |
| 1046 | for c in &txn.chunks { |
| 1047 | if matches!(c.state, SlotState::Pending) { |
| 1048 | let _ = self.shared.store.cancel_waiter(c.job, txn.inc); |
| 1049 | } |
| 1050 | } |
| 1051 | } |
| 1052 | } |
| 1053 | |
| 1054 | fn landing_terminal(&mut self, job: JobId) { |
| 1055 | if let Some(l) = self.landings.get_mut(&job) { |
| 1056 | l.waiters = l.waiters.saturating_sub(1); |
| 1057 | if l.waiters == 0 { |
| 1058 | self.landings.remove(&job); |
| 1059 | } |
| 1060 | } |
| 1061 | } |
| 1062 | |
| 1063 | fn on_park_completion(&mut self, c: Completion) { |
| 1064 | let Some(t) = &c.terminal else { |
| 1065 | return; |
| 1066 | }; |
| 1067 | self.parks.remove(&c.job); |
| 1068 | // ADR 2.4: published and served, durability unknown. Adapters report it |
| 1069 | // on a failed terminal (the directory sync failed after the rename); |
| 1070 | // counted whatever the terminal says. |
| 1071 | if c.publish == PublishOutcome::Indeterminate { |
| 1072 | self.stats.park_indeterminate_total += 1; |
| 1073 | } |
| 1074 | match t { |
| 1075 | Terminal::Done(_) => self.stats.park_published_total += 1, |
| 1076 | Terminal::Failed(_) => self.stats.park_failed_total += 1, |
| 1077 | Terminal::Cancelled => { |
| 1078 | self.stats.store_cancelled_total += 1; |
| 1079 | self.stats.park_failed_total += 1; |
| 1080 | } |
| 1081 | } |
| 1082 | } |
| 1083 | |
| 1084 | /// Routes one restore completion. Returns the holder copy that must be |
| 1085 | /// dropped by the caller (stale or failed), if any. |
| 1086 | fn on_restore_completion(&mut self, mut c: Completion) -> Option<LandingHolder> { |
| 1087 | let terminal = c.terminal.clone()?; |
| 1088 | self.landing_terminal(c.job); |
| 1089 | let key = c.incarnation.seq_id; |
| 1090 | let Some(mut entry) = self.entries.remove(&key) else { |
| 1091 | self.stats.store_stale_completions_total += 1; |
| 1092 | return c.holder.take(); |
| 1093 | }; |
| 1094 | let live = entry.txn.as_ref().is_some_and(|t| t.inc == c.incarnation) |
| 1095 | && matches!( |
| 1096 | entry.state, |
| 1097 | ResidencyState::Restoring | ResidencyState::Draining |
| 1098 | ); |
| 1099 | let slot = live |
| 1100 | .then(|| { |
| 1101 | entry.txn.as_mut().and_then(|t| { |
| 1102 | t.chunks |
| 1103 | .iter_mut() |
| 1104 | .find(|s| s.job == c.job && matches!(s.state, SlotState::Pending)) |
| 1105 | }) |
| 1106 | }) |
| 1107 | .flatten(); |
| 1108 | let Some(slot) = slot else { |
| 1109 | self.stats.store_stale_completions_total += 1; |
| 1110 | self.entries.insert(key, entry); |
| 1111 | return c.holder.take(); |
| 1112 | }; |
| 1113 | let mut drop_me = None; |
| 1114 | let failed = match terminal { |
| 1115 | Terminal::Done(_) => { |
| 1116 | slot.state = SlotState::Completed(c.holder.take()); |
| 1117 | false |
| 1118 | } |
| 1119 | Terminal::Failed(_) => { |
| 1120 | slot.state = SlotState::Ended; |
| 1121 | drop_me = c.holder.take(); |
| 1122 | true |
| 1123 | } |
| 1124 | Terminal::Cancelled => { |
| 1125 | slot.state = SlotState::Ended; |
| 1126 | self.stats.store_cancelled_total += 1; |
| 1127 | drop_me = c.holder.take(); |
| 1128 | true |
| 1129 | } |
| 1130 | }; |
| 1131 | if failed && entry.state == ResidencyState::Restoring { |
| 1132 | self.begin_drain(&mut entry); |
| 1133 | } |
| 1134 | self.entries.insert(key, entry); |
| 1135 | drop_me |
| 1136 | } |
| 1137 | |
| 1138 | /// Ends a transaction that will not be committed: releases its accounting |
| 1139 | /// and pin and returns its landing copies for the caller to drop. |
| 1140 | fn close_txn(&mut self, txn: &mut RestoreTxn) -> Vec<LandingHolder> { |
| 1141 | self.restore_inflight_blocks = self.restore_inflight_blocks.saturating_sub(txn.blocks); |
| 1142 | txn.blocks = 0; |
| 1143 | if let Some(pin) = txn.pin.take() { |
| 1144 | self.shared.store.unpin(pin); |
| 1145 | } |
| 1146 | txn.take_landings() |
| 1147 | } |
| 1148 | |
| 1149 | /// S3 for one fully completed transaction. On any refusal the request |
| 1150 | /// falls back to a plain prefill and nothing the scheduler can see changed. |
| 1151 | fn commit<B: AienInferenceBackend + ?Sized>( |
| 1152 | &mut self, |
| 1153 | sched: &mut AienScheduler, |
| 1154 | backend: &mut B, |
| 1155 | entry: &mut Entry, |
| 1156 | garbage: &mut Vec<LandingHolder>, |
| 1157 | ) { |
| 1158 | let Some(mut txn) = entry.txn.take() else { |
| 1159 | return; |
| 1160 | }; |
| 1161 | let seq = entry.seq; |
| 1162 | let seq_u64 = seq.to_u64(); |
| 1163 | let holders: Vec<u64> = txn.chunks.iter().map(|c| c.holder).collect(); |
| 1164 | // The incarnation matched; the sequence must also still exist (ADR 5.3). |
| 1165 | let prompt = sched.arena().get(seq).map(|r| r.prompt.clone()); |
| 1166 | let assembled = if prompt.is_none() { |
| 1167 | Err("sequence left the scheduler".to_string()) |
| 1168 | } else { |
| 1169 | let mut kv = self.shared.kv.write(); |
| 1170 | let mut res = Ok(()); |
| 1171 | for &h in &holders { |
| 1172 | // The load verified every segment into the holder's blocks: |
| 1173 | // that is the holder's completion fence (DOCS SILENT, see C6 |
| 1174 | // report). Idempotent for a holder another waiter completed. |
| 1175 | if let Err(e) = kv |
| 1176 | .mark_prefill_pending(h) |
| 1177 | .and_then(|_| kv.complete_prefill(h)) |
| 1178 | { |
| 1179 | res = Err(format!("{e}")); |
| 1180 | break; |
| 1181 | } |
| 1182 | } |
| 1183 | res.and_then(|_| { |
| 1184 | kv.assemble_table(seq_u64, &holders, SuffixPolicy::AllowPartialTail) |
| 1185 | .map(|_| ()) |
| 1186 | }) |
| 1187 | }; |
| 1188 | garbage.extend(self.close_txn(&mut txn)); |
| 1189 | let restored = txn.restored; |
| 1190 | let ok = assembled.is_ok() |
| 1191 | && prompt.as_ref().is_some_and(|p| restored < p.len()) |
| 1192 | && match prompt |
| 1193 | .as_ref() |
| 1194 | .map(|p| backend.restore_sequence(seq_u64, &p[..restored])) |
| 1195 | { |
| 1196 | Some(Ok(())) => match sched.admit_restored_prefix(seq, restored) { |
| 1197 | Ok(()) => true, |
| 1198 | Err(_) => { |
| 1199 | let _ = backend.release_sequence(seq_u64); |
| 1200 | false |
| 1201 | } |
| 1202 | }, |
| 1203 | _ => false, |
| 1204 | }; |
| 1205 | if ok { |
| 1206 | entry.transition(ResidencyState::Prefilling); |
| 1207 | self.stats.restore_committed_total += 1; |
| 1208 | self.stats.restore_tokens_total += restored as u64; |
| 1209 | } else { |
| 1210 | if assembled.is_ok() { |
| 1211 | let _ = self.shared.kv.write().free_sequence(seq_u64); |
| 1212 | } |
| 1213 | let _ = sched.release_restore(seq); |
| 1214 | entry.transition(ResidencyState::Failed); |
| 1215 | self.stats.restore_failed_total += 1; |
| 1216 | self.record_restore_failure(txn.head); |
| 1217 | self.fallback(); |
| 1218 | } |
| 1219 | } |
| 1220 | |
| 1221 | /// The spine calls this at the start of every `step`: abandon restores |
| 1222 | /// whose request left the scheduler, route completions, commit or drain |
| 1223 | /// finished transactions, and retire settled entries. Never blocks. |
| 1224 | pub fn poll<B: AienInferenceBackend + ?Sized>( |
| 1225 | &mut self, |
| 1226 | sched: &mut AienScheduler, |
| 1227 | backend: &mut B, |
| 1228 | ) { |
| 1229 | let mut garbage: Vec<LandingHolder> = Vec::new(); |
| 1230 | |
| 1231 | // 1. Requests that left the scheduler (cancelled, client gone): their |
| 1232 | // waiters are withdrawn and the entry dropped, so every later |
| 1233 | // completion for them is stale. Their holders stay with the worker |
| 1234 | // until each job's terminal (ADR 5.5). |
| 1235 | let gone: Vec<u64> = self |
| 1236 | .entries |
| 1237 | .iter() |
| 1238 | .filter(|(_, e)| sched.arena().is_stale(e.seq)) |
| 1239 | .map(|(&k, _)| k) |
| 1240 | .collect(); |
| 1241 | for k in gone { |
| 1242 | if let Some(mut e) = self.entries.remove(&k) { |
| 1243 | if let Some(mut txn) = e.txn.take() { |
| 1244 | for c in &txn.chunks { |
| 1245 | if matches!(c.state, SlotState::Pending) { |
| 1246 | let _ = self.shared.store.cancel_waiter(c.job, txn.inc); |
| 1247 | } |
| 1248 | } |
| 1249 | garbage.extend(self.close_txn(&mut txn)); |
| 1250 | self.stats.restore_abandoned_total += 1; |
| 1251 | } |
| 1252 | } |
| 1253 | } |
| 1254 | |
| 1255 | // 2. Completions. |
| 1256 | loop { |
| 1257 | let batch = self.shared.store.poll(POLL_BATCH); |
| 1258 | if batch.is_empty() { |
| 1259 | break; |
| 1260 | } |
| 1261 | for c in batch { |
| 1262 | if self.parks.contains_key(&c.job) { |
| 1263 | self.on_park_completion(c); |
| 1264 | } else if let Some(h) = self.on_restore_completion(c) { |
| 1265 | garbage.push(h); |
| 1266 | } |
| 1267 | } |
| 1268 | } |
| 1269 | |
| 1270 | // 3. Commit or finish draining. |
| 1271 | let keys: Vec<u64> = self.entries.keys().copied().collect(); |
| 1272 | for k in keys { |
| 1273 | let Some(mut e) = self.entries.remove(&k) else { |
| 1274 | continue; |
| 1275 | }; |
| 1276 | match e.state { |
| 1277 | ResidencyState::Restoring if e.txn.as_ref().is_some_and(|t| t.pending() == 0) => { |
| 1278 | self.commit(sched, backend, &mut e, &mut garbage); |
| 1279 | } |
| 1280 | ResidencyState::Draining if e.txn.as_ref().is_none_or(|t| t.pending() == 0) => { |
| 1281 | if let Some(mut txn) = e.txn.take() { |
| 1282 | garbage.extend(self.close_txn(&mut txn)); |
| 1283 | self.record_restore_failure(txn.head); |
| 1284 | } |
| 1285 | let _ = sched.release_restore(e.seq); |
| 1286 | e.transition(ResidencyState::Failed); |
| 1287 | self.stats.restore_failed_total += 1; |
| 1288 | self.fallback(); |
| 1289 | } |
| 1290 | _ => {} |
| 1291 | } |
| 1292 | // 4. Retire settled entries: a restored request once its suffix is |
| 1293 | // prefilled, a failed one once its plain prefill started. |
| 1294 | let settled = match sched.arena().get(e.seq) { |
| 1295 | // A restoring or draining entry of a request that left is |
| 1296 | // closed by step 1 (next poll), never dropped here. |
| 1297 | None => matches!(e.state, ResidencyState::Prefilling | ResidencyState::Failed), |
| 1298 | Some(rec) => match e.state { |
| 1299 | ResidencyState::Prefilling => rec.is_prefilled, |
| 1300 | ResidencyState::Failed => !matches!( |
| 1301 | rec.phase, |
| 1302 | SequencePhase::Waiting | SequencePhase::AwaitingRestore |
| 1303 | ), |
| 1304 | _ => false, |
| 1305 | }, |
| 1306 | }; |
| 1307 | if !settled { |
| 1308 | self.entries.insert(k, e); |
| 1309 | } |
| 1310 | } |
| 1311 | |
| 1312 | // Landing copies are dropped here, with no lock held (S4 takes the KV lock). |
| 1313 | drop(garbage); |
| 1314 | } |
| 1315 | } |