Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-serve-http/src/kv_persist.rs # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-serve-http / src / kv_persist.rs` 1701 lines ยท 65808 bytes Raw Blame History 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 park and restore on the omega door (sc#505, ADR 0003), opt in with 17 //! `AIEN_KV_STORE_DIR`. 18 //! 19 //! With the directory unset nothing in this module runs: [`settings_from_lookup`] reads that one 20 //! variable and returns `None`, the door keeps [`PersistState::Off`], and generation, logs and 21 //! `/health` are what they were before persistence existed. 22 //! 23 //! With it set the door opens the sealed host store (`aien-kv-store`, the #511/#512 rules: a 24 //! private directory under a trusted parent, `AIEN_KV_STORE_KEY` required) and: 25 //! 26 //! - **park**: after a generation, under the GPU lock, the K/V of every chunk of the stored 27 //! history that the store does not hold yet is exported (`Qwen3MoeOmegaEngine::export_kv`, the 28 //! `HostPagedPoolV1` bytes of `kvio`); the lock is released and the chunks are submitted to the 29 //! storage worker, which seals and writes them on its own thread. 30 //! - **restore**: before a generation, without the GPU lock, the longest stored prefix of the 31 //! prompt (capped at `len - 1`, ADR 6.5: the last prompt token is always stepped) is looked up 32 //! and loaded; only when it is longer than what the engine still holds in RAM is it imported 33 //! (under the GPU lock, `restore_kv`), all or nothing. 34 //! 35 //! Every problem (store refused at start, missing or malformed key, unknown omega switch, a 36 //! miss, a failed or corrupt load, a timeout, an import error) ends in a plain prefill. Nothing 37 //! is ever partly restored: `restore_kv` resets the engine on error. 38 //! 39 //! The namespace binds the checkpoint digest, the model shape, the bf16 pool layout, the chunk 40 //! size, the sharing namespace and the engine identity of ADR 1.2.2 built by 41 //! [`OmegaKvIdentity::new`]: weight format as loaded, the build (omega commit, linked 42 //! `libomega_gpu.a` sha256, this crate's commit), a rounding class, and an engine config digest 43 //! over the MoE shape and every run switch that can move a K/V byte. 44 //! 45 //! Exactness limit (ADR 6.3 deviation): a stored tail chunk is found only when the prompt 46 //! continues the parked history; a prompt that diverges inside a chunk restores up to the last 47 //! whole chunk before the divergence, and may then restore less than the in-RAM rule would reuse 48 //! in an uninterrupted run (correct, only slower). 49 50 use std::collections::{BTreeMap, HashMap}; 51 use std::path::{Path, PathBuf}; 52 use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; 53 use std::sync::{Arc, Mutex}; 54 use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; 55 56 use aien_inference_abi::qwen3_moe_omega::kvio::{self, PoolBlockGeometry}; 57 use aien_inference_abi::qwen3_moe_omega::{ 58 OmegaKvSwitches, Qwen3MoeConfig, Qwen3MoeOmegaEngine, WeightFormat, KV_BLOCK_SIZE, 59 }; 60 use aien_kv_store::host_fs::{Boundary, FaultAction, FaultHook, HostFsConfig, HostFsStore}; 61 use aien_kv_store::worker::StorageWorker; 62 use aien_kv_store::{ 63 chunk_chain, chunk_key, BackendFormat, ChunkHeader, ChunkKey, ComputeConfig, EngineConfig, 64 EngineIdentity, HiddenAct, HolderGuard, Incarnation, JobId, KvDtype, KvStore, LayoutStrides, 65 NamespaceFields, NamespaceId, PinnedDest, PinnedSource, RecoveryProgress, StoreState, Terminal, 66 HEADER_REGION_LEN, 67 }; 68 use aien_runtime::shared_kv::{KvPersistSettings, KV_STORE_DIR_ENV}; 69 use sha2::{Digest, Sha256}; 70 71 /// `ComputeConfig::arith_id` of the omega engine. 72 pub const ARITH_ID: &str = "omega-qwen3-moe"; 73 /// Domain of the omega engine config digest. 74 const OMEGA_ENG_DOMAIN: &[u8] = b"AIEN-PKV-OMEGA-ENG-V1\0"; 75 /// How long a restore waits for its chunks before giving up (plain prefill). 76 pub const LOAD_TIMEOUT: Duration = Duration::from_secs(10); 77 /// How long a park waits for the storage worker's park budget to free (its earlier chunks 78 /// publishing) before it gives up on the rest of the chain. One 256-token chunk of the 30B model 79 /// is 25 MB and the default park budget is 64 MB, so a long turn always waits for credit (#514). 80 pub const PARK_CREDIT_WAIT: Duration = Duration::from_secs(10); 81 82 /// Omega environment switches that are read at run time and can change what the chip computes 83 /// (omega C `getenv` and the engine's own). Their values are part of the engine config digest. 84 pub const NUMERIC_ENV: &[&str] = &[ 85 "AIEN_OMEGA_CTA_BUDGET", 86 "AIEN_OMEGA_DGRAPH_BARRIER", 87 "AIEN_OMEGA_DGRAPH_PREFETCH", 88 "AIEN_OMEGA_FP8_GEMV", 89 "AIEN_OMEGA_FP8_WEIGHT_CACHE", 90 "AIEN_Q38_READING_FAST", 91 "AIEN_Q38_ATTENTION_MIRROR", 92 "OWN30B_DECODE_GRAPH", 93 "OWN30B_DECODE_GRAPH_STAMPS", 94 ]; 95 /// Omega variables that cannot move a K/V byte: timing (spin), build inputs (bound by the archive 96 /// digest in the build id) and test paths. 97 pub const NEUTRAL_ENV: &[&str] = &[ 98 "AIEN_OMEGA_SPIN_US", 99 "AIEN_OMEGA_DIR", 100 "AIEN_OMEGA_GPU", 101 "AIEN_OMEGA_GPU_LIB", 102 "AIEN_OMEGA_GPU_LIB_SHA256", 103 "AIEN_OMEGA_PINNED_SHA", 104 "AIEN_OMEGA_COMPOSE", 105 "AIEN_OMEGA_COMPOSE_DIR", 106 "AIEN_OMEGA_COMPOSE_LIB", 107 "AIEN_OMEGA_COMPOSE_LIB_SHA256", 108 "AIEN_OMEGA_COMPOSE_SHA", 109 "AIEN_OMEGA_COMPOSE_EXPECTED_SHA", 110 "OWN30B_MODEL_DIR", 111 "OWN30B_CHECKPOINT", 112 ]; 113 /// Negative controls: persistence refuses while one is set. 114 pub const MUTANT_ENV: &[&str] = &["OWN30B_DECODE_GRAPH_MUTANT"]; 115 116 /// The build of the engine that writes the K/V. 117 #[derive(Debug, Clone, PartialEq, Eq)] 118 pub struct OmegaBuild { 119 /// The omega commit `omega.lock` pins. 120 pub omega_commit: String, 121 /// How `libomega_gpu.a` was linked (`pinned-source`, `dev-override`, `prebuilt`, `stub`). 122 pub gpu_link: String, 123 /// sha256 of the linked `libomega_gpu.a`. 124 pub gpu_archive_sha256: String, 125 /// `locked` (the sha `native-artifacts.lock` records), `unrecorded` (no record for this 126 /// commit and target), `mismatch` or `none`. 127 pub gpu_digest: String, 128 pub gpu_target: String, 129 /// This crate's commit (`build.rs`). 130 pub sc_commit: String, 131 /// Built from a checkout with modified tracked files (or unknown). 132 pub sc_dirty: bool, 133 } 134 135 impl OmegaBuild { 136 /// What this binary was built from and linked. 137 pub fn linked() -> Self { 138 let id = aien_omega_gpu::native_identity(); 139 let recorded = env!("AIEN_SERVE_HTTP_GPU_RECORDED_SHA256"); 140 let gpu_digest = if id.archive_sha256.is_empty() { 141 "none" 142 } else if recorded == "unrecorded" { 143 "unrecorded" 144 } else if recorded == id.archive_sha256 { 145 "locked" 146 } else { 147 "mismatch" 148 }; 149 let pin = env!("AIEN_SERVE_HTTP_OMEGA_LOCK"); 150 Self { 151 omega_commit: pin.to_string(), 152 // A pinned-source archive built from another commit than the pin is not the pin. 153 gpu_link: if id.link == "pinned-source" && id.source_sha != pin { 154 "pinned-source-other-commit".into() 155 } else { 156 id.link.to_string() 157 }, 158 gpu_archive_sha256: id.archive_sha256.to_string(), 159 gpu_digest: gpu_digest.to_string(), 160 gpu_target: id.target.to_string(), 161 sc_commit: env!("AIEN_SERVE_HTTP_GIT_COMMIT").to_string(), 162 sc_dirty: env!("AIEN_SERVE_HTTP_GIT_DIRTY") != "0", 163 } 164 } 165 166 /// `omega:+libomega_gpu:+sc:`. Refused when any part is unknown or 167 /// cannot be trusted to name the bytes that run (fail closed). 168 pub fn build_id(&self) -> Result { 169 let hex = |s: &str, n: usize| s.len() == n && s.bytes().all(|b| b.is_ascii_hexdigit()); 170 if self.gpu_link != "pinned-source" { 171 return Err(format!( 172 "libomega_gpu.a is linked as {:?}, not built from the omega.lock pin", 173 self.gpu_link 174 )); 175 } 176 if !hex(&self.gpu_archive_sha256, 64) { 177 return Err("the linked libomega_gpu.a has no sha256".into()); 178 } 179 if !matches!(self.gpu_digest.as_str(), "locked" | "unrecorded") { 180 return Err(format!( 181 "libomega_gpu.a digest is {:?} against native-artifacts.lock", 182 self.gpu_digest 183 )); 184 } 185 if !hex(&self.omega_commit, 40) { 186 return Err(format!( 187 "omega.lock commit {:?} is not a 40-hex commit", 188 self.omega_commit 189 )); 190 } 191 if !(self.sc_commit.len() >= 7 192 && self.sc_commit.len() <= 64 193 && hex(&self.sc_commit, self.sc_commit.len())) 194 { 195 return Err(format!( 196 "the engine commit {:?} is unknown (build without git; set AIEN_BUILD_COMMIT)", 197 self.sc_commit 198 )); 199 } 200 if self.sc_dirty { 201 return Err("the binary was built from a checkout with uncommitted changes".into()); 202 } 203 if self.gpu_target.is_empty() { 204 return Err("the linked libomega_gpu.a has no target".into()); 205 } 206 Ok(format!( 207 "omega:{}+libomega_gpu:{}+sc:{}", 208 self.omega_commit, self.gpu_archive_sha256, self.sc_commit 209 )) 210 } 211 } 212 213 /// Everything the omega engine identity is built from. 214 pub struct IdentityInputs<'a> { 215 /// The served model id (namespace field 4). 216 pub model_id: &'a str, 217 pub model_sha256: [u8; 32], 218 /// `file` or `index+shards` ([`checkpoint_digest`]). 219 pub model_digest_kind: &'a str, 220 pub config: &'a Qwen3MoeConfig, 221 /// `config.json` has a non-null `rope_scaling` (the omega engine has no scaled rope: refused). 222 pub rope_scaling: bool, 223 pub weights: WeightFormat, 224 pub switches: OmegaKvSwitches, 225 pub build: &'a OmegaBuild, 226 /// The process environment (name, value). 227 pub env: &'a [(String, String)], 228 } 229 230 /// The owned namespace inputs of the omega door, except the chunk size and the sharing 231 /// namespace (from the settings). 232 #[derive(Debug, Clone, PartialEq)] 233 pub struct OmegaKvIdentity { 234 pub weight_format: aien_kv_store::WeightFormat, 235 pub engine_build_id: String, 236 pub rounding_class: String, 237 pub engine_config_digest: [u8; 32], 238 model_sha256: [u8; 32], 239 model_digest_kind: String, 240 model_id: String, 241 num_layers: u32, 242 num_kv_heads: u32, 243 head_dim: u32, 244 rope_theta: f32, 245 compute_config_digest: [u8; 32], 246 geometry: PoolBlockGeometry, 247 } 248 249 fn store_weight_format(w: WeightFormat) -> aien_kv_store::WeightFormat { 250 match w { 251 WeightFormat::Bf16 => aien_kv_store::WeightFormat::Bf16, 252 WeightFormat::Fp8Experts => aien_kv_store::WeightFormat::Fp8Experts, 253 WeightFormat::Fp8All => aien_kv_store::WeightFormat::Fp8All, 254 } 255 } 256 257 fn weights_label(w: WeightFormat) -> &'static str { 258 match w { 259 WeightFormat::Bf16 => "bf16", 260 WeightFormat::Fp8Experts => "fp8-experts", 261 WeightFormat::Fp8All => "fp8-all", 262 } 263 } 264 265 fn u32_of(name: &str, v: usize) -> Result { 266 u32::try_from(v).map_err(|_| format!("{name} {v} does not fit 32 bits")) 267 } 268 269 impl OmegaKvIdentity { 270 pub fn new(i: &IdentityInputs<'_>) -> Result { 271 if i.rope_scaling { 272 return Err("config.json has rope_scaling, the omega engine has no scaled rope".into()); 273 } 274 // The omega environment: mutants refuse, unknown switches refuse (unsure = refuse), the 275 // numeric ones are bound by value. 276 let mut numeric: BTreeMap<&str, &str> = BTreeMap::new(); 277 for (k, v) in i.env { 278 let omega = k.starts_with("AIEN_OMEGA_") 279 || k.starts_with("OWN30B_") 280 || NUMERIC_ENV.contains(&k.as_str()); 281 if !omega { 282 continue; 283 } 284 if MUTANT_ENV.contains(&k.as_str()) { 285 if !v.is_empty() { 286 return Err(format!( 287 "{k} is set (a negative control): K/V from a mutant must never be stored" 288 )); 289 } 290 } else if let Some(n) = NUMERIC_ENV.iter().find(|n| **n == k.as_str()) { 291 numeric.insert(n, v.as_str()); 292 } else if !NEUTRAL_ENV.contains(&k.as_str()) { 293 return Err(format!("{k} is set and its effect on the K/V is not known")); 294 } 295 } 296 // Exhaustive on purpose: no `..`, so a new run switch has to be placed here. 297 let OmegaKvSwitches { 298 attention_path, 299 device_routing, 300 prefill_chunk, 301 prefill_gemm, 302 prefill_device_routing, 303 whole_prompt, 304 whole_prompt_device_host, 305 decode_graph, 306 lm_head_gemv, 307 routing_mutant, 308 trace_layers, 309 } = i.switches; 310 if routing_mutant { 311 return Err("the engine runs the routing mutant (a negative control)".into()); 312 } 313 // Exhaustive on purpose: no `..`. 314 let Qwen3MoeConfig { 315 layers, 316 hidden, 317 q_heads, 318 kv_heads, 319 head_dim, 320 experts, 321 top_k, 322 moe_intermediate, 323 vocab, 324 rms_eps, 325 rope_theta, 326 norm_topk_prob, 327 tie_word_embeddings, 328 // Decides when a sequence stops, not what is computed. 329 eos_token_ids: _, 330 } = i.config; 331 let engine_build_id = i.build.build_id()?; 332 let base = EngineConfig { 333 num_experts: u32_of("experts", *experts)?, 334 experts_per_token: u32_of("top_k", *top_k)?, 335 expert_intermediate_dim: *moe_intermediate as u64, 336 whole_prompt_prefill: whole_prompt, 337 device_router: device_routing, 338 matmul_path: if prefill_gemm { 339 "fp8-grouped-gemm" 340 } else { 341 "grouped-gemv" 342 }, 343 } 344 .digest() 345 .map_err(|e| format!("engine config: {e:?}"))?; 346 let mut text = format!( 347 "weights={}\nnorm_topk_prob={norm_topk_prob}\nattention_path={attention_path}\nprefill_chunk={prefill_chunk}\nprefill_device_routing={prefill_device_routing}\nwhole_prompt_device_host={whole_prompt_device_host}\ndecode_graph={decode_graph}\nlm_head_gemv={lm_head_gemv}\ntrace_layers={trace_layers}\nq_heads={q_heads}\n", 348 weights_label(i.weights) 349 ); 350 for n in NUMERIC_ENV { 351 match numeric.get(n) { 352 Some(v) => text.push_str(&format!("env {n}={v:?}\n")), 353 None => text.push_str(&format!("env {n} unset\n")), 354 } 355 } 356 let mut h = Sha256::new(); 357 h.update(OMEGA_ENG_DOMAIN); 358 h.update(base); 359 h.update(text.as_bytes()); 360 let engine_config_digest: [u8; 32] = h.finalize().into(); 361 let rounding_class = format!( 362 "omega-gpu/{}/{}/kv-bf16/attn-{attention_path}@kv-arith-epoch-{}", 363 i.build.gpu_target, 364 weights_label(i.weights), 365 aien_inference_abi::KV_ARITH_EPOCH 366 ); 367 let weight_format = store_weight_format(i.weights); 368 let engine = EngineIdentity { 369 weight_format, 370 engine_build_id: &engine_build_id, 371 rounding_class: &rounding_class, 372 engine_config_digest, 373 }; 374 let compute_config_digest = ComputeConfig { 375 num_heads: u32_of("q_heads", *q_heads)?, 376 hidden_dim: *hidden as u64, 377 intermediate_dim: *moe_intermediate as u64, 378 vocab_size: *vocab as u64, 379 rms_norm_eps: *rms_eps, 380 tie_word_embeddings: *tie_word_embeddings, 381 hidden_act: HiddenAct::Silu, 382 arith_id: ARITH_ID, 383 arith_epoch: aien_inference_abi::KV_ARITH_EPOCH, 384 } 385 .digest_with_engine(&engine) 386 .map_err(|e| format!("compute config: {e:?}"))?; 387 Ok(Self { 388 weight_format, 389 engine_build_id, 390 rounding_class, 391 engine_config_digest, 392 model_sha256: i.model_sha256, 393 model_digest_kind: i.model_digest_kind.to_string(), 394 model_id: i.model_id.to_string(), 395 num_layers: u32_of("layers", *layers)?, 396 num_kv_heads: u32_of("kv_heads", *kv_heads)?, 397 head_dim: u32_of("head_dim", *head_dim)?, 398 rope_theta: *rope_theta, 399 compute_config_digest, 400 geometry: PoolBlockGeometry::for_config(i.config), 401 }) 402 } 403 404 /// The namespace fields for `chunk_tokens` and `sharing_namespace`. 405 pub fn fields<'a>( 406 &'a self, 407 chunk_tokens: u32, 408 sharing_namespace: &'a str, 409 ) -> NamespaceFields<'a> { 410 let g = &self.geometry; 411 NamespaceFields { 412 model_sha256: self.model_sha256, 413 model_digest_kind: &self.model_digest_kind, 414 model_id: &self.model_id, 415 num_layers: self.num_layers, 416 num_kv_heads: self.num_kv_heads, 417 head_dim: self.head_dim, 418 block_size: KV_BLOCK_SIZE as u32, 419 rope_theta: self.rope_theta, 420 rope_scaling: None, 421 qk_norm: true, 422 dtype: KvDtype::Bf16, 423 layout: LayoutStrides { 424 head_stride: g.head_stride() as u64, 425 token_stride: g.token_stride() as u64, 426 kv_plane_stride: g.kv_plane_stride() as u64, 427 layer_stride: g.layer_stride() as u64, 428 block_stride: g.block_stride() as u64, 429 element_bytes: 2, 430 }, 431 backend_format: BackendFormat::HostPagedPoolV1, 432 chunk_tokens, 433 sharing_namespace, 434 compute_config_digest: self.compute_config_digest, 435 } 436 } 437 } 438 439 /// Test-only fault hook of the chip acceptance checks (sc#507): `AIEN_KV_TEST_FAULT` = 440 /// `:[:]` makes the store sleep at one point of its protocol so a 441 /// fault lands deterministically: `p1` before the temp write, `p2` before the temp fsync, `p3` 442 /// before the rename that publishes, `p4` before the directory fsync, `p5` before the index 443 /// insert, `load` before a restore read. `count` stalls only the first N passes (default 0: 444 /// every pass). It only delays I/O: no K/V byte changes, so it is not part of the identity. 445 /// Unset in production; a malformed value refuses persistence (fail closed). 446 pub const TEST_FAULT_ENV: &str = "AIEN_KV_TEST_FAULT"; 447 448 /// The parsed `AIEN_KV_TEST_FAULT` stall. 449 pub struct TestFault { 450 boundary: Boundary, 451 stall: Duration, 452 /// Passes still to stall; `u64::MAX` = every pass. 453 left: AtomicU64, 454 spec: String, 455 } 456 457 impl TestFault { 458 /// `None` when the variable is unset or empty. 459 pub fn from_lookup(get: impl Fn(&str) -> Option) -> Result>, String> { 460 let Some(spec) = get(TEST_FAULT_ENV).filter(|s| !s.is_empty()) else { 461 return Ok(None); 462 }; 463 let bad = || { 464 format!( 465 "{TEST_FAULT_ENV}={spec:?}: expected :[:]" 466 ) 467 }; 468 let parts: Vec<&str> = spec.split(':').collect(); 469 if !(2..=3).contains(&parts.len()) { 470 return Err(bad()); 471 } 472 let boundary = match parts[0] { 473 "p1" => Boundary::P1Write, 474 "p2" => Boundary::P2FsyncFile, 475 "p3" => Boundary::P3Rename, 476 "p4" => Boundary::P4FsyncDir, 477 "p5" => Boundary::P5IndexInsert, 478 "load" => Boundary::LoadRead, 479 _ => return Err(bad()), 480 }; 481 let ms: u64 = parts[1].parse().map_err(|_| bad())?; 482 let count: u64 = match parts.get(2) { 483 Some(c) => c.parse().map_err(|_| bad())?, 484 None => 0, 485 }; 486 Ok(Some(Arc::new(Self { 487 boundary, 488 stall: Duration::from_millis(ms), 489 left: AtomicU64::new(if count == 0 { u64::MAX } else { count }), 490 spec, 491 }))) 492 } 493 494 pub fn spec(&self) -> &str { 495 &self.spec 496 } 497 } 498 499 impl FaultHook for TestFault { 500 fn at(&self, boundary: Boundary, _key: &ChunkKey) -> Option { 501 if boundary != self.boundary { 502 return None; 503 } 504 let took = self 505 .left 506 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| match n { 507 0 => None, 508 u64::MAX => Some(u64::MAX), 509 n => Some(n - 1), 510 }) 511 .is_ok(); 512 took.then_some(FaultAction::Stall(self.stall)) 513 } 514 } 515 516 /// Persistence settings when `AIEN_KV_STORE_DIR` is set and not empty; `None` otherwise, having 517 /// read nothing but that one variable (the switch-off path). 518 pub fn settings_from_lookup( 519 get: impl Fn(&str) -> Option, 520 ) -> Option> { 521 let dir = get(KV_STORE_DIR_ENV)?; 522 if dir.is_empty() { 523 return None; 524 } 525 Some(KvPersistSettings::from_lookup(|n| { 526 if n == KV_STORE_DIR_ENV { 527 Some(dir.clone()) 528 } else { 529 get(n) 530 } 531 })) 532 } 533 534 /// The startup read of the server: the persistence settings ([`settings_from_lookup`]), then the 535 /// store key stripped from the environment through `strip` so the key lives on only in the 536 /// settings and no child process inherits it. The key is stripped whether or not 537 /// `AIEN_KV_STORE_DIR` is set (sc#523); the server calls this before it loads the engine. 538 pub fn take_settings( 539 get: impl Fn(&str) -> Option, 540 strip: impl FnOnce(&str), 541 ) -> Option> { 542 let s = settings_from_lookup(get); 543 strip(aien_kv_store::seal::KEY_ENV); 544 s 545 } 546 547 /// Hash exactly the bounded regular file accepted by the checkpoint loader. 548 fn sha256_file(p: &Path) -> Result<[u8; 32], String> { 549 aien_inference_abi::checkpoint_sha256(p).map_err(|e| e.to_string()) 550 } 551 552 fn hex(b: &[u8]) -> String { 553 b.iter().map(|x| format!("{x:02x}")).collect() 554 } 555 556 /// The checkpoint digest of `aien-cli` (`checkpoint_digest`): one weight file is its sha256 557 /// (`file`); a sharded checkpoint is the sha256 of the manifest `aien-checkpoint-digest v1`, 558 /// the index sha256 and one ` ` line per shard (`index+shards`). 559 pub fn checkpoint_digest(model_dir: &Path) -> Result<([u8; 32], &'static str), String> { 560 let index = model_dir.join("model.safetensors.index.json"); 561 let path = if index.exists() { 562 index 563 } else { 564 model_dir.join("model.safetensors") 565 }; 566 let files = aien_inference_abi::checkpoint_files(&path) 567 .map_err(|e| format!("{}: {e}", path.display()))?; 568 let Some(index) = files.index else { 569 let (_, file) = files 570 .weights 571 .first() 572 .ok_or("the checkpoint names no weight file")?; 573 return Ok((sha256_file(file)?, "file")); 574 }; 575 if files.weights.is_empty() { 576 return Err("the shard index names no shard".into()); 577 } 578 let mut manifest = format!( 579 "aien-checkpoint-digest v1\nindex {}\n", 580 hex(&sha256_file(&index)?) 581 ); 582 for (name, file) in &files.weights { 583 manifest.push_str(&format!("{} {name}\n", hex(&sha256_file(file)?))); 584 } 585 Ok((Sha256::digest(manifest.as_bytes()).into(), "index+shards")) 586 } 587 588 /// Whether `config.json` in `model_dir` sets a non-null `rope_scaling`. 589 pub fn config_has_rope_scaling(model_dir: &Path) -> Result { 590 let p = model_dir.join("config.json"); 591 let text = crate::read_model_text(&p).map_err(|e| format!("{}: {e}", p.display()))?; 592 let v: serde_json::Value = 593 serde_json::from_str(&text).map_err(|e| format!("{}: {e}", p.display()))?; 594 Ok(v.get("rope_scaling").is_some_and(|r| !r.is_null())) 595 } 596 597 /// What the door does about persistence. 598 pub enum PersistState { 599 /// `AIEN_KV_STORE_DIR` unset: nothing runs. 600 Off, 601 /// Asked for, refused at start: every prompt is prefilled. 602 Refused(String), 603 On(Box), 604 } 605 606 /// Counters of the persistence path (`/health` `persistent_kv`). 607 #[derive(Debug, Clone, Default, PartialEq, Eq)] 608 pub struct PersistCounters { 609 /// Chunks the store published. 610 pub parked_chunks: u64, 611 pub park_bytes: u64, 612 /// Chunks of the history the store already held. 613 pub park_dedup: u64, 614 /// Chunks the store refused at submit (quota, queue, state). 615 pub park_refused: u64, 616 /// Chunks after a refused one, never submitted: a chain with a hole cannot be restored past it. 617 pub park_dropped: u64, 618 /// Chunks whose export or write failed. 619 pub park_failed: u64, 620 /// Generations not parked because the store was not open (recovering, degraded, failed). 621 pub park_skipped: u64, 622 /// Generations that started from a restored prefix. 623 pub restores: u64, 624 pub restored_tokens: u64, 625 pub restore_bytes: u64, 626 /// Restore attempts that fell back to plain prefill, by reason. 627 pub restore_misses: BTreeMap, 628 /// Start refusals (0 or 1). 629 pub refusals: u64, 630 } 631 632 /// One stored chunk of a restore: `stored` tokens on disk, the first `used` of them restored. 633 struct StoredChunk { 634 key: ChunkKey, 635 parent: Option, 636 first: usize, 637 stored: usize, 638 used: usize, 639 } 640 641 /// A loaded prefix, ready to import. 642 pub struct Fetched { 643 pub tokens: usize, 644 pub payload: Vec, 645 } 646 647 /// One exported chunk waiting for the store. 648 pub struct ParkItem { 649 header: ChunkHeader, 650 tokens: usize, 651 bytes: Vec, 652 } 653 654 /// The landing buffer of one load: shared by the load job (through its holder guard) and the 655 /// door; freed when both let go. 656 struct LandBuf { 657 ptr: *mut u8, 658 len: usize, 659 _buf: Box<[u8]>, 660 } 661 662 // SAFETY: the bytes behind `ptr` are written only by the load job while its holder is held, and 663 // read by the door only after that job's terminal completion was polled (ADR 5.5). 664 unsafe impl Send for LandBuf {} 665 unsafe impl Sync for LandBuf {} 666 667 impl LandBuf { 668 fn new(len: usize) -> Arc { 669 let mut buf = vec![0u8; len].into_boxed_slice(); 670 let ptr = buf.as_mut_ptr(); 671 Arc::new(Self { 672 ptr, 673 len, 674 _buf: buf, 675 }) 676 } 677 /// # Safety 678 /// Only after the load job writing this buffer has reached its terminal completion. 679 unsafe fn bytes(&self) -> &[u8] { 680 std::slice::from_raw_parts(self.ptr, self.len) 681 } 682 } 683 684 #[derive(Default)] 685 struct Inner { 686 counters: PersistCounters, 687 /// In-flight park jobs. 688 stores: HashMap, 689 /// In-flight load jobs: `None` until the terminal arrives. 690 loads: HashMap>>, 691 } 692 693 /// An open store with its worker, for one omega door. 694 pub struct KvPersistence { 695 worker: Arc, 696 /// The store itself, read only for its I/O and recovery counters in `/health` (#509). 697 store: Arc, 698 /// The last recovery step's progress (startup recovery, #509). 699 recovery: Arc>, 700 identity: OmegaKvIdentity, 701 sharing: String, 702 chunk_tokens: usize, 703 ns: NamespaceId, 704 store_dir: PathBuf, 705 park: AtomicBool, 706 restore: bool, 707 drain_ms: u64, 708 inner: Mutex, 709 seq: AtomicU64, 710 /// The armed [`TEST_FAULT_ENV`] spec, if any. 711 test_fault: Option, 712 } 713 714 fn miss_reason(e: &aien_platform::PlatformError) -> &'static str { 715 use aien_platform::PlatformError as P; 716 match e { 717 P::ObjectNotFound(_) => "not-found", 718 P::InvalidLayout => "invalid", 719 P::AccessDenied => "access-denied", 720 P::HardwareFault(_) => "io", 721 P::QueueFull | P::OutOfMemory => "busy", 722 P::DeviceUnavailable => "store-unavailable", 723 _ => "error", 724 } 725 } 726 727 fn now_ns() -> u64 { 728 SystemTime::now() 729 .duration_since(UNIX_EPOCH) 730 .map(|d| d.as_nanos() as u64) 731 .unwrap_or(0) 732 } 733 734 impl KvPersistence { 735 fn fields(&self) -> NamespaceFields<'_> { 736 self.identity 737 .fields(self.chunk_tokens as u32, &self.sharing) 738 } 739 740 fn inc(&self) -> Incarnation { 741 Incarnation::new(self.seq.fetch_add(1, Ordering::Relaxed) + 1, 1) 742 } 743 744 fn block_bytes(&self) -> usize { 745 self.identity.geometry.block_stride() 746 } 747 748 /// `QueueFull` with nothing in flight before and after the submit: no credit will come back, 749 /// so waiting cannot help (sc#523: a chunk larger than the budget; [`open`] refuses those). 750 fn credit_never_frees(&self, idle_before: bool) -> bool { 751 idle_before && self.worker.capacity().inflight_bytes == 0 752 } 753 754 /// The store finished recovery (or failed) within `timeout`. 755 pub fn wait_ready(&self, timeout: Duration) -> bool { 756 let t0 = Instant::now(); 757 loop { 758 if self.worker.capacity().state != StoreState::Recovering { 759 return true; 760 } 761 if t0.elapsed() >= timeout { 762 return false; 763 } 764 std::thread::sleep(Duration::from_millis(2)); 765 } 766 } 767 768 /// Every submitted park reached its terminal within `timeout`. 769 pub fn wait_idle(&self, timeout: Duration) -> bool { 770 let t0 = Instant::now(); 771 loop { 772 { 773 let mut g = self.inner.lock().unwrap_or_else(|p| p.into_inner()); 774 self.pump(&mut g); 775 if g.stores.is_empty() { 776 return true; 777 } 778 } 779 if t0.elapsed() >= timeout { 780 return false; 781 } 782 std::thread::sleep(Duration::from_millis(1)); 783 } 784 } 785 786 pub fn counters(&self) -> PersistCounters { 787 let mut g = self.inner.lock().unwrap_or_else(|p| p.into_inner()); 788 self.pump(&mut g); 789 g.counters.clone() 790 } 791 792 pub fn status_json(&self) -> serde_json::Value { 793 let c = self.counters(); 794 let t = aien_kv_store::seal::seal_timing(); 795 let r = *self.recovery.lock().unwrap_or_else(|p| p.into_inner()); 796 let s = self.store.stats(); 797 let state = match self.worker.capacity().state { 798 StoreState::Recovering => "recovering", 799 StoreState::Open => "open", 800 StoreState::Degraded => "degraded", 801 StoreState::Failed => "failed", 802 }; 803 serde_json::json!({ 804 "state": "on", 805 "store_state": state, 806 "store_dir": self.store_dir.display().to_string(), 807 "namespace": hex(&self.ns.0[..8]), 808 "chunk_tokens": self.chunk_tokens, 809 "park": self.park.load(Ordering::Relaxed), 810 "restore": self.restore, 811 "engine_build_id": self.identity.engine_build_id, 812 "rounding_class": self.identity.rounding_class, 813 "parked_chunks": c.parked_chunks, 814 "park_bytes": c.park_bytes, 815 "park_dedup": c.park_dedup, 816 "park_refused": c.park_refused, 817 "park_dropped": c.park_dropped, 818 "park_failed": c.park_failed, 819 "park_skipped": c.park_skipped, 820 "restores": c.restores, 821 "restored_tokens": c.restored_tokens, 822 "restore_bytes": c.restore_bytes, 823 "restore_misses": c.restore_misses, 824 "refusals": c.refusals, 825 "seal": { 826 "seal_calls": t.seal_calls, 827 "seal_bytes": t.seal_bytes, 828 "seal_ns": t.seal_ns, 829 "open_calls": t.open_calls, 830 "open_bytes": t.open_bytes, 831 "open_ns": t.open_ns, 832 }, 833 "recovery": { 834 "done": r.done, 835 "failed": r.failed, 836 "indexed": r.indexed, 837 "indexed_bytes": r.bytes, 838 "foreign_namespace": r.foreign_namespace, 839 "corrupt_deleted": r.corrupt_deleted, 840 "tmp_deleted": r.tmp_deleted, 841 "elapsed_us": r.elapsed_us, 842 "unlink_failures": s.recovery_unlink_failures, 843 "foreign_files": s.foreign_files, 844 }, 845 "io": { 846 "reads": s.reads, 847 "read_bytes": s.read_bytes, 848 "writes": s.writes, 849 "write_bytes": s.write_bytes, 850 "file_fsyncs": s.file_fsyncs, 851 "published": s.published_total, 852 "disk_full": s.disk_full_total, 853 "queue_full": s.queue_full_total, 854 "indeterminate": s.indeterminate_total, 855 "failed": s.terminal_failed, 856 "corrupt_deleted": s.corrupt_deleted_total, 857 }, 858 "test_fault": self.test_fault, 859 }) 860 } 861 862 fn miss(&self, reason: &str) { 863 let mut g = self.inner.lock().unwrap_or_else(|p| p.into_inner()); 864 *g.counters 865 .restore_misses 866 .entry(reason.to_string()) 867 .or_insert(0) += 1; 868 } 869 870 /// Drains the worker's completions into the counters and the load slots. 871 fn pump(&self, g: &mut Inner) { 872 loop { 873 let batch = self.worker.poll(64); 874 if batch.is_empty() { 875 return; 876 } 877 for c in batch { 878 let Some(t) = c.terminal else { continue }; 879 if let Some(bytes) = g.stores.remove(&c.job) { 880 match t { 881 Terminal::Done(_) => { 882 g.counters.parked_chunks += 1; 883 g.counters.park_bytes += bytes; 884 } 885 Terminal::Failed(_) | Terminal::Cancelled => g.counters.park_failed += 1, 886 } 887 } else if let Some(slot) = g.loads.get_mut(&c.job) { 888 *slot = Some(match t { 889 Terminal::Done(_) => Ok(()), 890 Terminal::Failed(e) => Err(miss_reason(&e).to_string()), 891 Terminal::Cancelled => Err("cancelled".to_string()), 892 }); 893 } 894 // `c.holder` (a load's landing holder) drops here, after the slot is set. 895 } 896 } 897 } 898 899 /// Pauses or resumes parking (the chip check freezes the store after turn 1). 900 pub fn set_park(&self, on: bool) { 901 self.park.store(on, Ordering::Relaxed); 902 } 903 904 pub fn restore_on(&self) -> bool { 905 self.restore 906 } 907 908 /// The chunks of the longest stored prefix of `prompt` (capped at `len - 1`). 909 fn find(&self, prompt: &[u32]) -> Result, &'static str> { 910 let cap = prompt.len().saturating_sub(1); 911 let ct = self.chunk_tokens; 912 if cap == 0 { 913 return Err("short-prompt"); 914 } 915 let full = cap / ct; 916 let keys = if full > 0 { 917 chunk_chain(&self.ns, ct as u32, &prompt[..full * ct]).map_err(|_| "key")? 918 } else { 919 Vec::new() 920 }; 921 let found = self.worker.lookup(&keys); 922 let f = found.iter().take_while(|x| x.is_some()).count(); 923 let mut out: Vec = (0..f) 924 .map(|i| StoredChunk { 925 key: keys[i], 926 parent: i.checked_sub(1).map(|p| keys[p]), 927 first: i * ct, 928 stored: ct, 929 used: ct, 930 }) 931 .collect(); 932 // The tail: the parked history may end inside chunk `f` (a stored partial chunk). 933 let first = f * ct; 934 // Probe up to the prompt end, use up to the cap: a stored tail that runs to the last 935 // prompt token still serves every position before it (ADR 6.5). 936 let max_len = if first < cap { 937 ct.min(prompt.len() - first) 938 } else { 939 0 940 }; 941 let parent = f.checked_sub(1).map(|p| keys[p]); 942 let lens: Vec = (1..=max_len) 943 .rev() 944 .filter(|&l| !(l == ct && f < full)) 945 .collect(); 946 let mut tail_keys = Vec::with_capacity(lens.len()); 947 for &l in &lens { 948 tail_keys.push( 949 chunk_key( 950 &self.ns, 951 parent.as_ref(), 952 first as u32, 953 &prompt[first..first + l], 954 ) 955 .map_err(|_| "key")?, 956 ); 957 } 958 let tail_found = self.worker.lookup(&tail_keys); 959 if let Some(j) = tail_found.iter().position(|x| x.is_some()) { 960 out.push(StoredChunk { 961 key: tail_keys[j], 962 parent, 963 first, 964 stored: lens[j], 965 used: lens[j].min(cap - first), 966 }); 967 } 968 Ok(out) 969 } 970 971 /// Looks up and loads the longest stored prefix of `prompt` when it beats `in_ram`. Runs 972 /// without the GPU lock. `None` = plain prefill (the reason is counted). One deadline, 973 /// [`LOAD_TIMEOUT`] from the start, covers submitting the loads and waiting for them (sc#523). 974 pub fn fetch(&self, prompt: &[u32], in_ram: usize) -> Option { 975 if self.worker.capacity().state == StoreState::Recovering { 976 self.miss("store-recovering"); 977 return None; 978 } 979 let chunks = match self.find(prompt) { 980 Ok(c) => c, 981 Err(r) => { 982 self.miss(r); 983 return None; 984 } 985 }; 986 let r: usize = chunks.iter().map(|c| c.used).sum(); 987 if r == 0 { 988 self.miss("not-found"); 989 return None; 990 } 991 if r <= in_ram { 992 self.miss("ram-prefix-as-long"); 993 return None; 994 } 995 let fields = self.fields(); 996 let mut jobs: Vec<(JobId, Arc)> = Vec::new(); 997 let mut fail: Option = None; 998 let t_fetch = Instant::now(); 999 for c in &chunks { 1000 let (key, tokens) = (c.key, c.stored); 1001 let header = match fields.chunk_header( 1002 &self.ns, 1003 key, 1004 c.parent.as_ref(), 1005 c.first as u32, 1006 tokens as u32, 1007 0, 1008 ) { 1009 Ok(h) => h, 1010 Err(_) => { 1011 fail = Some("header".into()); 1012 break; 1013 } 1014 }; 1015 let len = header.payload_len as usize; 1016 let nb = tokens.div_ceil(KV_BLOCK_SIZE); 1017 if len != nb * self.block_bytes() { 1018 fail = Some("invalid".into()); 1019 break; 1020 } 1021 let buf = LandBuf::new(len); 1022 // A prefix larger than the worker's restore budget is normal on the real model (a 1023 // 2079-token prefix of the 30B is 204 MB, the default restore budget 192 MB): on 1024 // `QueueFull` the chunk waits for the earlier loads to land and free their credit, 1025 // within [`LOAD_TIMEOUT`] of the fetch start (#514). The inner lock is not held 1026 // while waiting. 1027 loop { 1028 let keep = buf.clone(); 1029 // SAFETY: `buf` stays allocated while the guard (held by the job) lives, and 1030 // nobody reads it until the job's terminal completion has been polled. A refused 1031 // submit drops its guard; `buf` itself stays alive for the retry. 1032 let dst = unsafe { 1033 PinnedDest::new( 1034 buf.ptr, 1035 self.block_bytes(), 1036 (0..nb).collect(), 1037 HolderGuard::new(move || drop(keep)), 1038 ) 1039 }; 1040 let mut g = self.inner.lock().unwrap_or_else(|p| p.into_inner()); 1041 self.pump(&mut g); 1042 let idle = self.worker.capacity().inflight_bytes == 0; 1043 match self.worker.submit_load(key, &header, dst, self.inc()) { 1044 Ok(job) => { 1045 g.loads.insert(job, None); 1046 jobs.push((job, buf)); 1047 break; 1048 } 1049 Err(aien_platform::PlatformError::QueueFull) 1050 if self.credit_never_frees(idle) => 1051 { 1052 fail = Some("over-budget".into()); 1053 break; 1054 } 1055 Err(aien_platform::PlatformError::QueueFull) 1056 if t_fetch.elapsed() < LOAD_TIMEOUT => 1057 { 1058 drop(g); 1059 std::thread::sleep(Duration::from_micros(200)); 1060 } 1061 Err(e) => { 1062 fail = Some(miss_reason(&e).to_string()); 1063 break; 1064 } 1065 } 1066 } 1067 if fail.is_some() { 1068 break; 1069 } 1070 } 1071 if fail.is_none() { 1072 loop { 1073 let mut g = self.inner.lock().unwrap_or_else(|p| p.into_inner()); 1074 self.pump(&mut g); 1075 let mut all = true; 1076 for (job, _) in &jobs { 1077 match g.loads.get(job) { 1078 Some(Some(Ok(()))) => {} 1079 Some(Some(Err(e))) => { 1080 fail = Some(e.clone()); 1081 break; 1082 } 1083 _ => all = false, 1084 } 1085 } 1086 if fail.is_some() || all { 1087 break; 1088 } 1089 drop(g); 1090 if t_fetch.elapsed() >= LOAD_TIMEOUT { 1091 fail = Some("timeout".into()); 1092 break; 1093 } 1094 std::thread::sleep(Duration::from_micros(200)); 1095 } 1096 } 1097 let mut g = self.inner.lock().unwrap_or_else(|p| p.into_inner()); 1098 if let Some(reason) = fail { 1099 for (job, _) in &jobs { 1100 if !matches!(g.loads.get(job), Some(Some(_))) { 1101 let _ = self.worker.cancel(*job); 1102 } 1103 g.loads.remove(job); 1104 } 1105 *g.counters.restore_misses.entry(reason).or_insert(0) += 1; 1106 // Buffers of jobs still running stay alive through their guards. 1107 return None; 1108 } 1109 let mut payload = Vec::with_capacity(jobs.iter().map(|(_, b)| b.len).sum()); 1110 for (job, buf) in &jobs { 1111 g.loads.remove(job); 1112 // SAFETY: the job's terminal `Done` was polled above. 1113 payload.extend_from_slice(unsafe { buf.bytes() }); 1114 } 1115 // A tail chunk stored past the cap: keep its first rows, zero the rest of the block. 1116 let g = &self.identity.geometry; 1117 payload.truncate(g.payload_len(r)); 1118 kvio::zero_padding(g, r, &mut payload); 1119 Some(Fetched { tokens: r, payload }) 1120 } 1121 1122 /// Counts a restore that the engine imported. 1123 pub fn note_restored(&self, f: &Fetched) { 1124 let mut g = self.inner.lock().unwrap_or_else(|p| p.into_inner()); 1125 g.counters.restores += 1; 1126 g.counters.restored_tokens += f.tokens as u64; 1127 g.counters.restore_bytes += f.payload.len() as u64; 1128 } 1129 1130 /// Counts a fetched prefix the engine refused to import (it was reset: plain prefill). 1131 pub fn note_import_failed(&self) { 1132 self.miss("import"); 1133 } 1134 1135 /// Counts a fetched prefix never imported because the GPU lock stayed busy (the request was 1136 /// answered busy; sc#523). 1137 pub fn note_lock_busy(&self) { 1138 self.miss("gpu-lock-busy"); 1139 } 1140 1141 /// Under the GPU lock, after a generation: exports the chunks of the engine's history that 1142 /// the store does not hold. Submitting them is [`Self::submit`], after the lock is released. 1143 pub fn snapshot(&self, e: &mut Qwen3MoeOmegaEngine) -> Vec { 1144 if !self.park.load(Ordering::Relaxed) { 1145 return Vec::new(); 1146 } 1147 if self.worker.capacity().state != StoreState::Open { 1148 self.inner 1149 .lock() 1150 .unwrap_or_else(|p| p.into_inner()) 1151 .counters 1152 .park_skipped += 1; 1153 return Vec::new(); 1154 } 1155 let hist = e.history().to_vec(); 1156 if hist.is_empty() { 1157 return Vec::new(); 1158 } 1159 let ct = self.chunk_tokens; 1160 let Ok(keys) = chunk_chain(&self.ns, ct as u32, &hist) else { 1161 self.inner 1162 .lock() 1163 .unwrap_or_else(|p| p.into_inner()) 1164 .counters 1165 .park_failed += 1; 1166 return Vec::new(); 1167 }; 1168 let found = self.worker.lookup(&keys); 1169 let fields = self.fields(); 1170 let written = now_ns(); 1171 let mut items = Vec::new(); 1172 let mut dedup = 0u64; 1173 let mut failed = 0u64; 1174 for (i, key) in keys.iter().enumerate() { 1175 if found.get(i).copied().flatten().is_some() { 1176 dedup += 1; 1177 continue; 1178 } 1179 let first = i * ct; 1180 let tokens = (hist.len() - first).min(ct); 1181 let header = match fields.chunk_header( 1182 &self.ns, 1183 *key, 1184 i.checked_sub(1).map(|p| &keys[p]), 1185 first as u32, 1186 tokens as u32, 1187 written, 1188 ) { 1189 Ok(h) => h, 1190 Err(_) => { 1191 failed += 1; 1192 break; 1193 } 1194 }; 1195 match e.export_kv(first, tokens) { 1196 Ok(bytes) if bytes.len() as u64 == header.payload_len => items.push(ParkItem { 1197 header, 1198 tokens, 1199 bytes, 1200 }), 1201 _ => { 1202 failed += 1; 1203 break; 1204 } 1205 } 1206 } 1207 let mut g = self.inner.lock().unwrap_or_else(|p| p.into_inner()); 1208 g.counters.park_dedup += dedup; 1209 g.counters.park_failed += failed; 1210 items 1211 } 1212 1213 /// Hands exported chunks to the storage worker (no GPU lock held). Stops at the first 1214 /// refusal: a chain with a hole cannot be restored past it (the rest counts in `park_dropped`). 1215 /// 1216 /// A chain longer than the worker's park budget is normal on the real model (one 256-token 1217 /// chunk of the 30B is 25 MB, the default budget 64 MB): on `QueueFull` the chunk waits, up to 1218 /// [`PARK_CREDIT_WAIT`], for the earlier chunks to publish and free their credit, then retries. 1219 /// Runs after the GPU lock is released; the inner lock is not held while waiting. 1220 pub fn submit(&self, items: Vec) { 1221 let n = items.len(); 1222 for (i, it) in items.into_iter().enumerate() { 1223 let nb = it.tokens.div_ceil(KV_BLOCK_SIZE); 1224 let tail_valid = (it.tokens - (nb - 1) * KV_BLOCK_SIZE) as u32; 1225 // Shared so a refused submit (which drops its guard) leaves the bytes for the retry. 1226 let bytes: Arc<[u8]> = it.bytes.into(); 1227 let len = bytes.len() as u64; 1228 let t0 = Instant::now(); 1229 loop { 1230 let mut g = self.inner.lock().unwrap_or_else(|p| p.into_inner()); 1231 self.pump(&mut g); 1232 let idle = self.worker.capacity().inflight_bytes == 0; 1233 let keep = bytes.clone(); 1234 // SAFETY: the guard owns a reference to the bytes, so they live and stay unwritten 1235 // (nothing writes through an `Arc<[u8]>`) until the store releases the holder. 1236 let src = unsafe { 1237 PinnedSource::new( 1238 bytes.as_ptr(), 1239 self.block_bytes(), 1240 (0..nb).collect(), 1241 tail_valid, 1242 HolderGuard::new(move || drop(keep)), 1243 ) 1244 }; 1245 match self.worker.submit_store(it.header, src, self.inc()) { 1246 Ok(job) => { 1247 g.stores.insert(job, len); 1248 break; 1249 } 1250 Err(aien_platform::PlatformError::QueueFull) 1251 if t0.elapsed() < PARK_CREDIT_WAIT && !self.credit_never_frees(idle) => 1252 { 1253 drop(g); 1254 std::thread::sleep(Duration::from_micros(500)); 1255 } 1256 Err(_) => { 1257 g.counters.park_refused += 1; 1258 // A chain with a hole cannot be restored past it: the rest is dropped. 1259 g.counters.park_dropped += (n - i - 1) as u64; 1260 return; 1261 } 1262 } 1263 } 1264 } 1265 } 1266 } 1267 1268 impl Drop for KvPersistence { 1269 fn drop(&mut self) { 1270 // Let the parks of the last turns publish, then stop the worker. 1271 let _ = self.wait_idle(Duration::from_millis(self.drain_ms)); 1272 let _ = self.worker.shutdown(self.drain_ms); 1273 } 1274 } 1275 1276 /// Opens the store for `identity` under `settings`. Every problem refuses (plain prefill) and 1277 /// says why on the returned startup line. 1278 pub fn open( 1279 settings: Result, 1280 identity: Result, 1281 ) -> (PersistState, String) { 1282 open_with_test_fault(settings, identity, Ok(None)) 1283 } 1284 1285 /// [`open`] with the store's test-only stall ([`TEST_FAULT_ENV`]); `Err` (a malformed value) refuses. 1286 pub fn open_with_test_fault( 1287 settings: Result, 1288 identity: Result, 1289 fault: Result>, String>, 1290 ) -> (PersistState, String) { 1291 match open_inner(settings, identity, fault) { 1292 Ok((p, line)) => (PersistState::On(Box::new(p)), line), 1293 Err(why) => { 1294 let line = format!("persistent KV: REFUSED ({why}); running without persistence: no park, no restore, every prompt is prefilled"); 1295 (PersistState::Refused(why), line) 1296 } 1297 } 1298 } 1299 1300 fn open_inner( 1301 settings: Result, 1302 identity: Result, 1303 fault: Result>, String>, 1304 ) -> Result<(KvPersistence, String), String> { 1305 let settings = settings?; 1306 let fault = fault?; 1307 let root = settings.store_dir.clone().ok_or("no store directory")?; 1308 let key = match &settings.store_key { 1309 Some(Ok(k)) => k.clone(), 1310 Some(Err(r)) => { 1311 aien_kv_store::seal::note_key_refusal(); 1312 return Err(format!("{r}")); 1313 } 1314 None => return Err("the store key was not read".into()), 1315 }; 1316 let identity = identity.map_err(|e| format!("engine identity: {e}"))?; 1317 let chunk_tokens = (settings.chunk_blocks as usize) 1318 .checked_mul(KV_BLOCK_SIZE) 1319 .filter(|&t| u32::try_from(t).is_ok()) 1320 .ok_or("AIEN_KV_CHUNK_BLOCKS: chunk size overflows")?; 1321 // One chunk must fit the worker's park budget (a quarter of the in-flight bytes) and its 1322 // restore budget (the rest), the split of `aien_kv_store::worker` (sc#523): a chunk that 1323 // never fits is `QueueFull` forever, and every turn would wait out the credit wait first. 1324 let charge = (identity.geometry.payload_len(chunk_tokens) + HEADER_REGION_LEN) as u64; 1325 let max = settings.worker.max_inflight_bytes; 1326 let (park_budget, restore_budget) = (max / 4, max - max / 4); 1327 for (on, what, budget, share) in [ 1328 (settings.park, "park", park_budget, "a quarter"), 1329 ( 1330 settings.restore, 1331 "restore", 1332 restore_budget, 1333 "three quarters", 1334 ), 1335 ] { 1336 if on && charge > budget { 1337 return Err(format!("one chunk of {chunk_tokens} tokens takes {charge} bytes in flight, more than the storage worker's {what} budget of {budget} bytes ({share} of AIEN_KV_STORE_MAX_INFLIGHT_BYTES={max}); raise it or lower AIEN_KV_CHUNK_BLOCKS")); 1338 } 1339 } 1340 let (ns, mut cfg) = { 1341 let fields = identity.fields(chunk_tokens as u32, &settings.namespace); 1342 let ns = fields 1343 .namespace_id() 1344 .map_err(|e| format!("namespace: {e:?}"))?; 1345 ( 1346 ns, 1347 HostFsConfig::from_fields(root.clone(), &fields) 1348 .map_err(|e| format!("store config: {e:?}"))?, 1349 ) 1350 }; 1351 if let Some(v) = settings.quota_bytes { 1352 cfg.quota_bytes = v; 1353 } 1354 if let Some(v) = settings.max_objects { 1355 cfg.max_objects = v; 1356 } 1357 if let Some(v) = settings.recovery_slice_ms { 1358 cfg.recovery_slice_ms = v; 1359 } 1360 cfg.seal_key = Some(key); 1361 if let Some(f) = &fault { 1362 cfg.faults = Some(f.clone() as Arc); 1363 } 1364 let slice_ms = cfg.recovery_slice_ms; 1365 let recovery = Arc::new(Mutex::new(RecoveryProgress::default())); 1366 let store = Arc::new(HostFsStore::open(cfg).map_err(|e| match e { 1367 // Another open store holds the directory (#521): no privacy hint. 1368 aien_platform::PlatformError::TaskRejected(why) => format!("store open: {why}"), 1369 e => format!("store open at {}: {e:?} (the directory must be private, under a parent only you can write)", root.display()), 1370 })?); 1371 let drive = { 1372 let store = store.clone(); 1373 let progress = recovery.clone(); 1374 let mut recovered = false; 1375 move || { 1376 if !recovered { 1377 let p = store.recover_step(slice_ms); 1378 *progress.lock().unwrap_or_else(|e| e.into_inner()) = p; 1379 recovered = p.done || p.failed; 1380 } 1381 } 1382 }; 1383 let worker = Arc::new( 1384 StorageWorker::spawn(store.clone(), settings.worker.clone(), drive) 1385 .map_err(|e| format!("storage worker: {e:?}"))?, 1386 ); 1387 let line = format!( 1388 "persistent KV: on, store {} namespace {:?} chunk {} tokens, weights {}, engine build {}, rounding {}, park {}, restore {}, drain {} ms (recovering in the background)", 1389 root.display(), 1390 settings.namespace, 1391 chunk_tokens, 1392 identity.weight_format.as_str(), 1393 identity.engine_build_id, 1394 identity.rounding_class, 1395 if settings.park { "on" } else { "off" }, 1396 if settings.restore { "on" } else { "off" }, 1397 settings.worker.drain_ms, 1398 ); 1399 let line = match &fault { 1400 Some(f) => format!( 1401 "{line}; TEST FAULT {TEST_FAULT_ENV}={} armed (chip check only)", 1402 f.spec() 1403 ), 1404 None => line, 1405 }; 1406 Ok(( 1407 KvPersistence { 1408 worker, 1409 store, 1410 recovery, 1411 identity, 1412 sharing: settings.namespace.clone(), 1413 chunk_tokens, 1414 ns, 1415 store_dir: root, 1416 park: AtomicBool::new(settings.park), 1417 restore: settings.restore, 1418 drain_ms: settings.worker.drain_ms, 1419 inner: Mutex::new(Inner::default()), 1420 seq: AtomicU64::new(0), 1421 test_fault: fault.map(|f| f.spec().to_string()), 1422 }, 1423 line, 1424 )) 1425 } 1426 1427 #[cfg(test)] 1428 mod tests { 1429 use super::*; 1430 1431 #[test] 1432 fn checkpoint_digest_accepts_regular_file_and_rejects_shard_symlink() { 1433 let dir = 1434 std::env::temp_dir().join(format!("aien-kv-checkpoint-digest-{}", std::process::id())); 1435 std::fs::create_dir(&dir).unwrap(); 1436 let file = dir.join("model.safetensors"); 1437 std::fs::write(&file, b"fixture").unwrap(); 1438 assert_eq!( 1439 checkpoint_digest(&dir).unwrap(), 1440 (Sha256::digest(b"fixture").into(), "file") 1441 ); 1442 std::fs::remove_file(&file).unwrap(); 1443 std::fs::write( 1444 dir.join("model.safetensors.index.json"), 1445 r#"{"weight_map":{"w":"shard.safetensors"}}"#, 1446 ) 1447 .unwrap(); 1448 std::os::unix::fs::symlink("/dev/zero", dir.join("shard.safetensors")).unwrap(); 1449 assert!(checkpoint_digest(&dir).is_err()); 1450 std::fs::remove_dir_all(&dir).unwrap(); 1451 } 1452 1453 fn build() -> OmegaBuild { 1454 OmegaBuild { 1455 omega_commit: "`d0889a944b02066f84fec71af7b9bbb92f5c986f`".into(), 1456 gpu_link: "pinned-source".into(), 1457 gpu_archive_sha256: "ab".repeat(32), 1458 gpu_digest: "unrecorded".into(), 1459 gpu_target: "aarch64-unknown-linux-gnu".into(), 1460 sc_commit: "cd".repeat(20), 1461 sc_dirty: false, 1462 } 1463 } 1464 1465 fn config() -> Qwen3MoeConfig { 1466 Qwen3MoeConfig { 1467 layers: 48, 1468 hidden: 2048, 1469 q_heads: 32, 1470 kv_heads: 4, 1471 head_dim: 128, 1472 experts: 128, 1473 top_k: 8, 1474 moe_intermediate: 768, 1475 vocab: 151936, 1476 rms_eps: 1e-6, 1477 rope_theta: 1e7, 1478 norm_topk_prob: true, 1479 tie_word_embeddings: false, 1480 eos_token_ids: vec![151645], 1481 } 1482 } 1483 1484 fn switches() -> OmegaKvSwitches { 1485 OmegaKvSwitches { 1486 attention_path: "fused", 1487 device_routing: true, 1488 prefill_chunk: 64, 1489 prefill_gemm: true, 1490 prefill_device_routing: true, 1491 whole_prompt: true, 1492 whole_prompt_device_host: true, 1493 decode_graph: false, 1494 lm_head_gemv: true, 1495 routing_mutant: false, 1496 trace_layers: false, 1497 } 1498 } 1499 1500 struct In { 1501 model_id: String, 1502 sha: [u8; 32], 1503 kind: String, 1504 config: Qwen3MoeConfig, 1505 weights: WeightFormat, 1506 switches: OmegaKvSwitches, 1507 build: OmegaBuild, 1508 env: Vec<(String, String)>, 1509 } 1510 1511 fn base() -> In { 1512 In { 1513 model_id: "qwen3-30b".into(), 1514 sha: [1; 32], 1515 kind: "index+shards".into(), 1516 config: config(), 1517 weights: WeightFormat::Fp8All, 1518 switches: switches(), 1519 build: build(), 1520 env: vec![("PATH".into(), "/bin".into())], 1521 } 1522 } 1523 1524 fn ns(i: &In) -> Result<[u8; 32], String> { 1525 let id = OmegaKvIdentity::new(&IdentityInputs { 1526 model_id: &i.model_id, 1527 model_sha256: i.sha, 1528 model_digest_kind: &i.kind, 1529 config: &i.config, 1530 rope_scaling: false, 1531 weights: i.weights, 1532 switches: i.switches, 1533 build: &i.build, 1534 env: &i.env, 1535 })?; 1536 Ok(id 1537 .fields(256, "default") 1538 .namespace_id() 1539 .map_err(|e| format!("{e:?}"))? 1540 .0) 1541 } 1542 1543 /// Every identity input changed alone gives another namespace (so another chunk key: a 1544 /// parked prefix of the old one can never be found). 1545 #[test] 1546 fn every_identity_input_moves_the_namespace() { 1547 type Change = (&'static str, fn(&mut In)); 1548 let changes: &[Change] = &[ 1549 ("model id", |i| i.model_id.push('x')), 1550 ("model digest", |i| i.sha[0] ^= 1), 1551 ("digest kind", |i| i.kind = "file".into()), 1552 ("layers", |i| i.config.layers += 1), 1553 ("hidden", |i| i.config.hidden += 128), 1554 ("q heads", |i| i.config.q_heads += 1), 1555 ("kv heads", |i| i.config.kv_heads += 1), 1556 ("head dim", |i| i.config.head_dim += 1), 1557 ("experts", |i| i.config.experts += 1), 1558 ("top k", |i| i.config.top_k += 1), 1559 ("moe intermediate", |i| i.config.moe_intermediate += 1), 1560 ("vocab", |i| i.config.vocab += 1), 1561 ("rms eps", |i| i.config.rms_eps *= 2.0), 1562 ("rope theta", |i| i.config.rope_theta *= 2.0), 1563 ("norm topk prob", |i| i.config.norm_topk_prob ^= true), 1564 ("tie embeddings", |i| i.config.tie_word_embeddings ^= true), 1565 ("weights bf16", |i| i.weights = WeightFormat::Bf16), 1566 ("weights fp8 experts", |i| { 1567 i.weights = WeightFormat::Fp8Experts 1568 }), 1569 ("attention path", |i| i.switches.attention_path = "split"), 1570 ("device routing", |i| i.switches.device_routing ^= true), 1571 ("prefill chunk", |i| i.switches.prefill_chunk += 1), 1572 ("prefill gemm", |i| i.switches.prefill_gemm ^= true), 1573 ("prefill device routing", |i| { 1574 i.switches.prefill_device_routing ^= true 1575 }), 1576 ("whole prompt", |i| i.switches.whole_prompt ^= true), 1577 ("whole prompt device host", |i| { 1578 i.switches.whole_prompt_device_host ^= true 1579 }), 1580 ("decode graph", |i| i.switches.decode_graph ^= true), 1581 ("lm head gemv", |i| i.switches.lm_head_gemv ^= true), 1582 ("trace layers", |i| i.switches.trace_layers ^= true), 1583 ("omega commit", |i| i.build.omega_commit = "e".repeat(40)), 1584 ("archive digest", |i| { 1585 i.build.gpu_archive_sha256 = "ef".repeat(32) 1586 }), 1587 ("gpu target", |i| { 1588 i.build.gpu_target = "x86_64-unknown-linux-gnu".into() 1589 }), 1590 ("engine commit", |i| i.build.sc_commit = "ab".repeat(20)), 1591 ("env cta budget", |i| { 1592 i.env.push(("AIEN_OMEGA_CTA_BUDGET".into(), "4".into())) 1593 }), 1594 ("env dgraph barrier", |i| { 1595 i.env.push(("AIEN_OMEGA_DGRAPH_BARRIER".into(), "1".into())) 1596 }), 1597 ("env dgraph prefetch", |i| { 1598 i.env 1599 .push(("AIEN_OMEGA_DGRAPH_PREFETCH".into(), "1".into())) 1600 }), 1601 ("env fp8 gemv", |i| { 1602 i.env.push(("AIEN_OMEGA_FP8_GEMV".into(), "0".into())) 1603 }), 1604 ("env fp8 weight cache", |i| { 1605 i.env 1606 .push(("AIEN_OMEGA_FP8_WEIGHT_CACHE".into(), "1".into())) 1607 }), 1608 ("env scoped reading", |i| { 1609 i.env.push(("AIEN_Q38_READING_FAST".into(), "1".into())) 1610 }), 1611 ("env attention mirror", |i| { 1612 i.env.push(("AIEN_Q38_ATTENTION_MIRROR".into(), "1".into())) 1613 }), 1614 ("env decode graph", |i| { 1615 i.env.push(("OWN30B_DECODE_GRAPH".into(), "1".into())) 1616 }), 1617 ("env decode graph stamps", |i| { 1618 i.env 1619 .push(("OWN30B_DECODE_GRAPH_STAMPS".into(), "1".into())) 1620 }), 1621 ]; 1622 let b = ns(&base()).unwrap(); 1623 let mut seen = vec![b]; 1624 for (what, change) in changes { 1625 let mut i = base(); 1626 change(&mut i); 1627 let n = ns(&i).unwrap_or_else(|e| panic!("{what}: {e}")); 1628 assert!(!seen.contains(&n), "{what} did not move the namespace"); 1629 seen.push(n); 1630 } 1631 // Timing and build-input variables do not move it. 1632 let mut i = base(); 1633 i.env.push(("AIEN_OMEGA_SPIN_US".into(), "50".into())); 1634 i.env.push(("AIEN_OMEGA_DIR".into(), "/x".into())); 1635 assert_eq!(ns(&i).unwrap(), b); 1636 } 1637 1638 #[test] 1639 fn untrusted_builds_and_negative_controls_refuse() { 1640 type Change = (&'static str, fn(&mut In)); 1641 let refusals: &[Change] = &[ 1642 ("stub link", |i| i.build.gpu_link = "stub".into()), 1643 ("dev override", |i| i.build.gpu_link = "dev-override".into()), 1644 ("other commit", |i| { 1645 i.build.gpu_link = "pinned-source-other-commit".into() 1646 }), 1647 ("no archive sha", |i| i.build.gpu_archive_sha256.clear()), 1648 ("digest mismatch", |i| { 1649 i.build.gpu_digest = "mismatch".into() 1650 }), 1651 ("unknown omega commit", |i| { 1652 i.build.omega_commit = "unknown".into() 1653 }), 1654 ("unknown engine commit", |i| { 1655 i.build.sc_commit = "unknown".into() 1656 }), 1657 ("dirty build", |i| i.build.sc_dirty = true), 1658 ("routing mutant", |i| i.switches.routing_mutant = true), 1659 ("decode graph mutant", |i| { 1660 i.env 1661 .push(("OWN30B_DECODE_GRAPH_MUTANT".into(), "skip-norm".into())) 1662 }), 1663 ("unknown omega switch", |i| { 1664 i.env.push(("AIEN_OMEGA_NEW_THING".into(), "1".into())) 1665 }), 1666 ("unknown own30b switch", |i| { 1667 i.env.push(("OWN30B_SOMETHING".into(), "1".into())) 1668 }), 1669 ]; 1670 for (what, change) in refusals { 1671 let mut i = base(); 1672 change(&mut i); 1673 assert!(ns(&i).is_err(), "{what} must refuse persistence"); 1674 } 1675 } 1676 1677 #[test] 1678 fn the_namespace_layout_is_the_pool_layout() { 1679 let i = base(); 1680 let id = OmegaKvIdentity::new(&IdentityInputs { 1681 model_id: &i.model_id, 1682 model_sha256: i.sha, 1683 model_digest_kind: &i.kind, 1684 config: &i.config, 1685 rope_scaling: false, 1686 weights: i.weights, 1687 switches: i.switches, 1688 build: &i.build, 1689 env: &i.env, 1690 }) 1691 .unwrap(); 1692 let f = id.fields(256, "default"); 1693 // [block][layer][K|V][token][head][dim] bf16: 48 x 2 x 16 x 4 x 128 x 2 bytes per block. 1694 assert_eq!(f.layout.block_stride, 48 * 2 * 16 * 4 * 128 * 2); 1695 assert_eq!( 1696 f.expected_payload_len(17).unwrap(), 1697 2 * f.layout.block_stride 1698 ); 1699 assert!(HostFsConfig::from_fields(PathBuf::from("/nonexistent"), &f).is_ok()); 1700 } 1701 }