interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-runtime / src / shared_kv.rs

1092 lines · 45599 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//! One KV for runtime and backend (PREFILL-E2E-0 cut C2).
17//!
18//! Before this module the daemon built the spine on a pool-less KV manager
19//! and the backend with no KV manager at all, so block tables in the runtime
20//! were bookkeeping only and the real K/V lived in the backend's private
21//! dense per-request cache. `build_shared_kv_runtime` creates ONE manager with
22//! a physical tensor pool sized for the loaded model and hands the same `Arc`
23//! to the spine (scheduler, swarm forks, reclaim) and to the backend (which
24//! writes prefill/decode K/V into the pool blocks named by the spine's block
25//! tables).
26//!
27//! Lives in aien-runtime (not aien-cli) because this crate owns the spine and
28//! already depends on aien-inference-abi and aien-kv-cache, so the assembly
29//! can be exercised by integration tests next to the other spine tests.
30
31use std::sync::Arc;
32
33use aien_inference_abi::{NativeTransformerBackend, TensorBackend, TransformerWeights};
34use aien_kv_cache::{
35 create_shared_kv_manager_with_pool, create_shared_kv_manager_with_pool_buffer, KvDType,
36 KvPoolConfig, SharedKvManager,
37};
38use aien_scheduler::SchedulerConfig;
39
40use crate::spine::AienRuntimeSpine;
41
42/// Sizing for the shared runtime/backend KV manager.
43#[derive(Debug, Clone, Copy)]
44pub struct SharedKvSizing {
45 /// Sequence arena capacity of the spine.
46 pub arena_capacity: usize,
47 /// Number of physical KV blocks in the pool (and in the block allocator).
48 pub total_blocks: usize,
49}
50
51/// Builds the pooled KV manager for `weights.config`. The block size is the
52/// model config's `block_size`, because the backend's paged writes index
53/// blocks with `weights.config.block_size`
54/// (aien-inference-abi/src/transformer_backend.rs, prefill paged path).
55pub fn build_model_kv_manager(
56 weights: &TransformerWeights,
57 total_blocks: usize,
58) -> Result<SharedKvManager, String> {
59 let cfg = &weights.config;
60 if cfg.block_size == 0 {
61 return Err("shared KV: model config block_size is 0".to_string());
62 }
63 let pool_cfg = KvPoolConfig::for_model(
64 total_blocks,
65 cfg.block_size,
66 cfg.num_layers,
67 cfg.num_kv_heads,
68 cfg.head_dim,
69 SHARED_KV_DTYPE,
70 );
71 create_shared_kv_manager_with_pool(total_blocks, cfg.block_size, pool_cfg)
72}
73
74/// `build_model_kv_manager` with the pool memory `backend` offers when it has some
75/// (`TensorBackend::alloc_kv_pool`: omega's resident pool, which its paged attention reads in
76/// place instead of staging the KV slices on every call); otherwise the host-mapped pool as before.
77pub fn build_model_kv_manager_for(
78 weights: &TransformerWeights,
79 total_blocks: usize,
80 backend: &dyn TensorBackend,
81) -> Result<SharedKvManager, String> {
82 let cfg = &weights.config;
83 if cfg.block_size == 0 {
84 return Err("shared KV: model config block_size is 0".to_string());
85 }
86 let pool_cfg = KvPoolConfig::for_model(
87 total_blocks,
88 cfg.block_size,
89 cfg.num_layers,
90 cfg.num_kv_heads,
91 cfg.head_dim,
92 SHARED_KV_DTYPE,
93 );
94 let bytes = aien_kv_cache::KvLayout::from_config(&pool_cfg)?.total_bytes;
95 match backend.alloc_kv_pool(bytes) {
96 Some(buffer) => create_shared_kv_manager_with_pool_buffer(
97 total_blocks,
98 cfg.block_size,
99 pool_cfg,
100 buffer,
101 ),
102 None => create_shared_kv_manager_with_pool(total_blocks, cfg.block_size, pool_cfg),
103 }
104}
105
106/// Builds the runtime spine and the native backend over ONE pooled KV
107/// manager. The returned backend's `kv_manager` is the same `Arc` as the
108/// spine's `kv_manager` (`Arc::ptr_eq`).
109pub fn build_shared_kv_runtime(
110 weights: TransformerWeights,
111 tensor_backend: Arc<dyn TensorBackend>,
112 scheduler_config: SchedulerConfig,
113 sizing: SharedKvSizing,
114) -> Result<(AienRuntimeSpine, NativeTransformerBackend), String> {
115 let kv_manager =
116 build_model_kv_manager_for(&weights, sizing.total_blocks, tensor_backend.as_ref())?;
117 let spine = AienRuntimeSpine::new(sizing.arena_capacity, scheduler_config, kv_manager.clone());
118 let backend =
119 NativeTransformerBackend::with_shared_kv_and_backend(weights, tensor_backend, kv_manager);
120 Ok((spine, backend))
121}
122
123/// Element type of the shared pool. `build_model_kv_manager` lays the pool out
124/// in this dtype, and [`KvPoolPlan`] prices it with the same value.
125///
126/// Bf16 since sc#384 (2026-10-12): the Omega GB10 backend runs its paged attention
127/// kernel straight on a bf16 pool, while any other dtype makes it gather the
128/// whole context on the host every call (6 ms of a 92 ms decode step at 300
129/// tokens, growing with context). K/V are rounded to bf16 on write; the
130/// reference CPU path reads bf16 pools too, and the pool costs half the bytes.
131pub const SHARED_KV_DTYPE: KvDType = KvDType::Bf16;
132
133/// The daemon's KV pool, sized from the loaded model (issue #239).
134///
135/// Before #239 the daemon asked for a fixed 8192 blocks for every model. With
136/// the 16-token blocks of `model_dir.rs` that is 131072 tokens, which happens to
137/// be Llama-3.2-1B's `max_position_embeddings`, but it priced every other model
138/// at 131072 tokens too (SmolLM2-1.7B: 48 GiB of Fp32 KV for a model whose
139/// context is 8192 tokens). The plan now takes the declared context budget from
140/// the model itself (`ModelConfig::max_sequence_length`, i.e. config.json
141/// `max_position_embeddings`) and derives
142/// `bytes = blocks * block_size * num_layers * num_kv_heads * head_dim * 2 (K and V) * dtype bytes`,
143/// with `blocks = ceil(context / block_size)`.
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub struct KvPoolPlan {
146 /// Declared context budget in tokens (where it came from: `context_source`).
147 pub context_tokens: usize,
148 /// Where `context_tokens` was taken from, for the startup log.
149 pub context_source: &'static str,
150 pub block_size: usize,
151 pub total_blocks: usize,
152 pub num_layers: usize,
153 pub num_kv_heads: usize,
154 pub head_dim: usize,
155 pub dtype_bytes: usize,
156 /// K plus V bytes for one token across all layers.
157 pub bytes_per_token: usize,
158 /// Bytes of the whole pool (`total_blocks * block_size * bytes_per_token`).
159 pub total_bytes: usize,
160}
161
162const GIB: f64 = (1u64 << 30) as f64;
163
164/// Bytes as GiB with two decimals, for logs and refusals.
165pub fn fmt_gib(bytes: u64) -> String {
166 format!("{:.2} GiB", bytes as f64 / GIB)
167}
168
169impl KvPoolPlan {
170 /// Plan for `cfg` at the model's own declared context (`max_sequence_length`).
171 pub fn for_model(cfg: &aien_inference_abi::ModelConfig) -> Result<Self, String> {
172 Self::for_context(
173 cfg,
174 cfg.max_sequence_length,
175 "model max_sequence_length (config.json max_position_embeddings)",
176 )
177 }
178
179 /// Plan for `cfg` at the model's own context, or at an operator cap that can only
180 /// lower it ([`KV_CONTEXT_CAP_ENV`]). A cap above the model's declared context is
181 /// refused, never used to enlarge the pool.
182 pub fn for_model_capped(
183 cfg: &aien_inference_abi::ModelConfig,
184 cap: Option<usize>,
185 ) -> Result<Self, String> {
186 match cap {
187 None => Self::for_model(cfg),
188 Some(c) if c > cfg.max_sequence_length => Err(format!(
189 "{KV_CONTEXT_CAP_ENV}={c} exceeds the model's declared context ({} tokens); the cap can only lower it",
190 cfg.max_sequence_length
191 )),
192 Some(c) => Self::for_context(cfg, c, "operator cap (AIEN_KV_CONTEXT_TOKENS)"),
193 }
194 }
195
196 /// Plan for `cfg` at an explicit context budget. Every product is checked, so a
197 /// config that would overflow `usize` is refused instead of wrapping.
198 pub fn for_context(
199 cfg: &aien_inference_abi::ModelConfig,
200 context_tokens: usize,
201 context_source: &'static str,
202 ) -> Result<Self, String> {
203 let named = [
204 ("context_tokens", context_tokens),
205 ("block_size", cfg.block_size),
206 ("num_layers", cfg.num_layers),
207 ("num_kv_heads", cfg.num_kv_heads),
208 ("head_dim", cfg.head_dim),
209 ];
210 if let Some((name, _)) = named.iter().find(|(_, v)| *v == 0) {
211 return Err(format!("KV pool plan: {name} is 0"));
212 }
213 // Fp32 is 4 bytes; the f32 accessor is exact for every whole-byte dtype.
214 let dtype_bytes = SHARED_KV_DTYPE.bytes_per_element() as usize;
215 let overflow = || "KV pool plan: size overflows usize".to_string();
216 let bytes_per_token = 2usize
217 .checked_mul(cfg.num_layers)
218 .and_then(|v| v.checked_mul(cfg.num_kv_heads))
219 .and_then(|v| v.checked_mul(cfg.head_dim))
220 .and_then(|v| v.checked_mul(dtype_bytes))
221 .ok_or_else(overflow)?;
222 let total_blocks = context_tokens.div_ceil(cfg.block_size);
223 let total_bytes = total_blocks
224 .checked_mul(cfg.block_size)
225 .and_then(|v| v.checked_mul(bytes_per_token))
226 .ok_or_else(overflow)?;
227 Ok(Self {
228 context_tokens,
229 context_source,
230 block_size: cfg.block_size,
231 total_blocks,
232 num_layers: cfg.num_layers,
233 num_kv_heads: cfg.num_kv_heads,
234 head_dim: cfg.head_dim,
235 dtype_bytes,
236 bytes_per_token,
237 total_bytes,
238 })
239 }
240
241 /// The pool config `build_model_kv_manager` builds for this plan.
242 pub fn pool_config(&self) -> KvPoolConfig {
243 KvPoolConfig::for_model(
244 self.total_blocks,
245 self.block_size,
246 self.num_layers,
247 self.num_kv_heads,
248 self.head_dim,
249 SHARED_KV_DTYPE,
250 )
251 }
252
253 /// One startup log line: size in bytes and GiB plus every derived parameter.
254 pub fn log_line(&self) -> String {
255 format!(
256 "KV pool: {} bytes ({}) = {} blocks x {} tokens x {} layers x {} kv heads x {} head_dim x 2 (K,V) x {} bytes; context {} tokens from {}",
257 self.total_bytes,
258 fmt_gib(self.total_bytes as u64),
259 self.total_blocks,
260 self.block_size,
261 self.num_layers,
262 self.num_kv_heads,
263 self.head_dim,
264 self.dtype_bytes,
265 self.context_tokens,
266 self.context_source,
267 )
268 }
269}
270
271/// `MemAvailable` from the text of `/proc/meminfo`, in bytes (the file reports kB).
272pub fn parse_mem_available(meminfo: &str) -> Option<u64> {
273 meminfo.lines().find_map(|line| {
274 let rest = line.strip_prefix("MemAvailable:")?;
275 let mut parts = rest.split_whitespace();
276 let value: u64 = parts.next()?.parse().ok()?;
277 match parts.next() {
278 Some("kB") => value.checked_mul(1024),
279 _ => None,
280 }
281 })
282}
283
284/// `MemAvailable` of this host in bytes, or `None` where `/proc/meminfo` is absent
285/// or has no parsable `MemAvailable` line.
286pub fn read_mem_available() -> Option<u64> {
287 std::fs::read_to_string("/proc/meminfo")
288 .ok()
289 .as_deref()
290 .and_then(parse_mem_available)
291}
292
293/// Why `MemAvailable` could not be established, as a plain message.
294pub fn parse_mem_available_checked(meminfo: &str) -> Result<u64, String> {
295 parse_mem_available(meminfo)
296 .ok_or_else(|| "/proc/meminfo has no parsable `MemAvailable: <n> kB` line".to_string())
297}
298
299/// `MemAvailable` of this host in bytes, or the reason it cannot be established
300/// (`/proc/meminfo` unreadable, or no parsable `MemAvailable` line).
301pub fn read_mem_available_checked() -> Result<u64, String> {
302 let text = std::fs::read_to_string("/proc/meminfo")
303 .map_err(|e| format!("/proc/meminfo cannot be read: {e}"))?;
304 parse_mem_available_checked(&text)
305}
306
307/// Operator override (documented): set to `1` to let the daemon allocate the KV pool
308/// although `MemAvailable` cannot be established. Without it the daemon refuses to
309/// start (fail closed). Every use is logged loudly on stderr.
310pub const ALLOW_UNCHECKED_MEMORY_ENV: &str = "AIEN_ALLOW_UNCHECKED_KV_MEMORY";
311
312/// True only when [`ALLOW_UNCHECKED_MEMORY_ENV`] is exactly `1`.
313pub fn allow_unchecked_memory_from_env() -> bool {
314 std::env::var(ALLOW_UNCHECKED_MEMORY_ENV).is_ok_and(|v| v == "1")
315}
316
317/// Operator cap (documented): the daemon's KV context budget in tokens, a positive
318/// decimal integer no larger than the model's declared context. Unset: the model's
319/// own context (unchanged behaviour). A sequence that outgrows the capped pool is
320/// refused with `KV_POOL_EXHAUSTED_PREFIX` before anything is mutated.
321pub const KV_CONTEXT_CAP_ENV: &str = "AIEN_KV_CONTEXT_TOKENS";
322
323/// Parses a [`KV_CONTEXT_CAP_ENV`] value: digits only, greater than zero.
324pub fn parse_kv_context_cap(value: &str) -> Result<usize, String> {
325 if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) {
326 return Err(format!(
327 "{KV_CONTEXT_CAP_ENV}={value:?} is not a positive decimal token count"
328 ));
329 }
330 match value.parse::<usize>() {
331 Ok(0) => Err(format!(
332 "{KV_CONTEXT_CAP_ENV}=0: the cap must be at least 1 token"
333 )),
334 Ok(n) => Ok(n),
335 Err(e) => Err(format!("{KV_CONTEXT_CAP_ENV}={value:?}: {e}")),
336 }
337}
338
339/// The operator cap from the environment: `Ok(None)` when unset, a refusal when set
340/// but not a valid count (including non-UTF-8).
341pub fn kv_context_cap_from_env() -> Result<Option<usize>, String> {
342 match std::env::var(KV_CONTEXT_CAP_ENV) {
343 Err(std::env::VarError::NotPresent) => Ok(None),
344 Err(e) => Err(format!("{KV_CONTEXT_CAP_ENV}: {e}")),
345 Ok(v) => parse_kv_context_cap(&v).map(Some),
346 }
347}
348
349/// Refuses the pool when the host reports less available memory than it needs.
350/// `available` is `Err(reason)` when memory could not be established: that refuses
351/// too (fail closed, #254) unless `allow_unchecked` is set, in which case the check
352/// is bypassed with a loud stderr line.
353pub fn check_kv_memory(
354 requested: u64,
355 available: Result<u64, String>,
356 allow_unchecked: bool,
357) -> Result<(), String> {
358 match available {
359 Ok(avail) if requested > avail => Err(format!(
360 "KV pool needs {requested} bytes ({}) but MemAvailable is {avail} bytes ({}); refusing to allocate",
361 fmt_gib(requested),
362 fmt_gib(avail),
363 )),
364 Ok(_) => Ok(()),
365 Err(reason) if allow_unchecked => {
366 eprintln!(
367 "WARNING: KV POOL MEMORY CHECK BYPASSED by {ALLOW_UNCHECKED_MEMORY_ENV}=1: {reason}; allocating {requested} bytes ({}) WITHOUT knowing MemAvailable",
368 fmt_gib(requested)
369 );
370 Ok(())
371 }
372 Err(reason) => Err(format!(
373 "KV pool memory cannot be checked: {reason}; refusing to allocate {requested} bytes ({}). Set {ALLOW_UNCHECKED_MEMORY_ENV}=1 to override (not recommended)",
374 fmt_gib(requested)
375 )),
376 }
377}
378
379/// Daemon planning step (#239): plans the pool for `cfg`, logs the plan, and
380/// checks `MemAvailable` (read through `mem_available`) before anything is
381/// allocated. Allocates nothing itself. Fails closed when memory cannot be
382/// established unless `allow_unchecked` (#254).
383pub fn plan_checked_model_kv(
384 cfg: &aien_inference_abi::ModelConfig,
385 context_cap: Option<usize>,
386 mem_available: &dyn Fn() -> Result<u64, String>,
387 allow_unchecked: bool,
388) -> Result<KvPoolPlan, String> {
389 let plan = KvPoolPlan::for_model_capped(cfg, context_cap)?;
390 println!(" {}", plan.log_line());
391 let available = mem_available();
392 if let Ok(avail) = &available {
393 println!(
394 " KV pool memory check: needs {} bytes ({}), MemAvailable {} bytes ({})",
395 plan.total_bytes,
396 fmt_gib(plan.total_bytes as u64),
397 avail,
398 fmt_gib(*avail)
399 );
400 }
401 check_kv_memory(plan.total_bytes as u64, available, allow_unchecked)?;
402 Ok(plan)
403}
404
405/// Daemon path (#239): [`plan_checked_model_kv`], then builds the spine and
406/// backend over the one pooled manager sized by the plan.
407pub fn build_shared_kv_runtime_for_model(
408 weights: TransformerWeights,
409 tensor_backend: Arc<dyn TensorBackend>,
410 scheduler_config: SchedulerConfig,
411 arena_capacity: usize,
412 context_cap: Option<usize>,
413 mem_available: &dyn Fn() -> Result<u64, String>,
414 allow_unchecked: bool,
415) -> Result<(AienRuntimeSpine, NativeTransformerBackend, KvPoolPlan), String> {
416 let plan = plan_checked_model_kv(&weights.config, context_cap, mem_available, allow_unchecked)?;
417 let (spine, backend) = build_shared_kv_runtime(
418 weights,
419 tensor_backend,
420 scheduler_config,
421 SharedKvSizing {
422 arena_capacity,
423 total_blocks: plan.total_blocks,
424 },
425 )?;
426 Ok((spine, backend, plan))
427}
428
429// ---------------------------------------------------------------------------
430// Persistent KV settings and store construction (ADR 0003, cuts C6 and C7;
431// docs/persistent-kv/METRICS_AND_SETTINGS.md)
432// ---------------------------------------------------------------------------
433
434/// Root of the host object store. Unset: persistence off, no behaviour change.
435pub const KV_STORE_DIR_ENV: &str = "AIEN_KV_STORE_DIR";
436pub const KV_STORE_NAMESPACE_ENV: &str = "AIEN_KV_STORE_NAMESPACE";
437pub const KV_CHUNK_BLOCKS_ENV: &str = "AIEN_KV_CHUNK_BLOCKS";
438pub const KV_RESTORE_MAX_BLOCKS_ENV: &str = "AIEN_KV_RESTORE_MAX_BLOCKS";
439pub const KV_PARK_ENV: &str = "AIEN_KV_PARK";
440pub const KV_RESTORE_ENV: &str = "AIEN_KV_RESTORE";
441pub const KV_RESTORE_RETRY_WINDOW_MS_ENV: &str = "AIEN_KV_RESTORE_RETRY_WINDOW_MS";
442/// Applied to the host store (`host_fs.rs` names); checked here so a bad value
443/// stops the start with its name.
444pub const KV_STORE_QUOTA_BYTES_ENV: &str = "AIEN_KV_STORE_QUOTA_BYTES";
445pub const KV_STORE_MAX_OBJECTS_ENV: &str = "AIEN_KV_STORE_MAX_OBJECTS";
446pub const KV_STORE_RECOVERY_SLICE_MS_ENV: &str = "AIEN_KV_STORE_RECOVERY_SLICE_MS";
447
448/// Default of `AIEN_KV_RESTORE_RETRY_WINDOW_MS`.
449pub const DEFAULT_RESTORE_RETRY_WINDOW_MS: u64 = 60_000;
450
451/// Persistent KV settings read from the environment (or any lookup in tests).
452/// Every value is checked when it is read, whether or not persistence is on,
453/// so a bad value stops the start with its name.
454#[derive(Debug, Clone, PartialEq, Eq)]
455pub struct KvPersistSettings {
456 pub store_dir: Option<std::path::PathBuf>,
457 /// Sharing namespace (ADR 1.2 field 13), at most 64 bytes. Default `default`.
458 pub namespace: String,
459 /// Chunk size in pool blocks. Default 16.
460 pub chunk_blocks: u32,
461 /// Restore holder blocks in flight at once. `None`: a quarter of the pool.
462 pub restore_max_blocks: Option<usize>,
463 /// Default on when the store dir is set.
464 pub park: bool,
465 pub restore: bool,
466 /// `AIEN_KV_RESTORE_RETRY_WINDOW_MS`, default 60000.
467 pub restore_retry_window_ms: u64,
468 /// `AIEN_KV_STORE_QUOTA_BYTES`; `None`: the host store default.
469 pub quota_bytes: Option<u64>,
470 /// `AIEN_KV_STORE_MAX_OBJECTS`; `None`: the host store default.
471 pub max_objects: Option<u64>,
472 /// `AIEN_KV_STORE_RECOVERY_SLICE_MS`; `None`: the host store default.
473 pub recovery_slice_ms: Option<u64>,
474 /// The storage worker's settings (`WorkerConfig::from_lookup`: the
475 /// `AIEN_KV_STORE_MAX_*` bounds and `AIEN_KV_STORE_DRAIN_MS`).
476 pub worker: aien_kv_store::worker::WorkerConfig,
477 /// The store key from `AIEN_KV_STORE_KEY` (ADR 0003 section 20), read only
478 /// when the store dir is set (`None` otherwise). A refusal (missing or
479 /// malformed) does not stop the start: persistence is refused (fail
480 /// closed) and the status says why. The key is redacted in `Debug`.
481 pub store_key:
482 Option<Result<Arc<aien_kv_store::seal::SealKey>, aien_kv_store::seal::KeyRefusal>>,
483}
484
485fn parse_switch(name: &str, v: Option<String>) -> Result<bool, String> {
486 match v.as_deref() {
487 None | Some("1") => Ok(true),
488 Some("0") => Ok(false),
489 Some(other) => Err(format!("{name}={other:?}: must be 1 or 0")),
490 }
491}
492
493fn parse_positive(name: &str, v: &str) -> Result<u64, String> {
494 if v.is_empty() || !v.bytes().all(|b| b.is_ascii_digit()) {
495 return Err(format!("{name}={v:?} is not a positive decimal integer"));
496 }
497 match v.parse::<u64>() {
498 Ok(0) => Err(format!("{name}=0: must be greater than zero")),
499 Ok(n) => Ok(n),
500 Err(e) => Err(format!("{name}={v:?}: {e}")),
501 }
502}
503
504fn parse_optional_positive(
505 get: &impl Fn(&str) -> Option<String>,
506 name: &str,
507) -> Result<Option<u64>, String> {
508 get(name).map(|v| parse_positive(name, &v)).transpose()
509}
510
511impl KvPersistSettings {
512 /// Every value is checked; a bad value is refused, never defaulted.
513 pub fn from_lookup(get: impl Fn(&str) -> Option<String>) -> Result<Self, String> {
514 let store_dir = get(KV_STORE_DIR_ENV)
515 .filter(|s| !s.is_empty())
516 .map(std::path::PathBuf::from);
517 let namespace = get(KV_STORE_NAMESPACE_ENV).unwrap_or_else(|| "default".to_string());
518 if namespace.is_empty()
519 || namespace.len() > aien_kv_store::identity::MAX_SHARING_NAMESPACE_BYTES
520 {
521 return Err(format!(
522 "{KV_STORE_NAMESPACE_ENV}: must be 1 to {} bytes",
523 aien_kv_store::identity::MAX_SHARING_NAMESPACE_BYTES
524 ));
525 }
526 let chunk_blocks = match get(KV_CHUNK_BLOCKS_ENV) {
527 None => 16,
528 Some(v) => u32::try_from(parse_positive(KV_CHUNK_BLOCKS_ENV, &v)?)
529 .map_err(|_| format!("{KV_CHUNK_BLOCKS_ENV}={v:?} is too large"))?,
530 };
531 let restore_max_blocks = match get(KV_RESTORE_MAX_BLOCKS_ENV) {
532 None => None,
533 Some(v) => Some(
534 usize::try_from(parse_positive(KV_RESTORE_MAX_BLOCKS_ENV, &v)?)
535 .map_err(|_| format!("{KV_RESTORE_MAX_BLOCKS_ENV}={v:?} is too large"))?,
536 ),
537 };
538 let restore_retry_window_ms =
539 parse_optional_positive(&get, KV_RESTORE_RETRY_WINDOW_MS_ENV)?
540 .unwrap_or(DEFAULT_RESTORE_RETRY_WINDOW_MS);
541 let worker = aien_kv_store::worker::WorkerConfig::from_lookup(&get)
542 .map_err(|e| format!("persistent KV worker setting {e}"))?;
543 let store_key = store_dir
544 .is_some()
545 .then(|| aien_kv_store::seal::SealKey::from_lookup(&get).map(Arc::new));
546 Ok(Self {
547 store_dir,
548 namespace,
549 chunk_blocks,
550 restore_max_blocks,
551 park: parse_switch(KV_PARK_ENV, get(KV_PARK_ENV))?,
552 restore: parse_switch(KV_RESTORE_ENV, get(KV_RESTORE_ENV))?,
553 restore_retry_window_ms,
554 quota_bytes: parse_optional_positive(&get, KV_STORE_QUOTA_BYTES_ENV)?,
555 max_objects: parse_optional_positive(&get, KV_STORE_MAX_OBJECTS_ENV)?,
556 recovery_slice_ms: parse_optional_positive(&get, KV_STORE_RECOVERY_SLICE_MS_ENV)?,
557 worker,
558 store_key,
559 })
560 }
561
562 /// From the process environment. `AIEN_KV_STORE_KEY` is removed from the
563 /// environment once read (whatever its value), so no child process
564 /// inherits it; the key lives on only in the settings (ADR 0003 section 20).
565 pub fn from_env() -> Result<Self, String> {
566 let got = Self::from_lookup(|n| std::env::var(n).ok());
567 std::env::remove_var(aien_kv_store::seal::KEY_ENV);
568 got
569 }
570
571 /// Persistence is on only when a store directory is configured.
572 pub fn enabled(&self) -> bool {
573 self.store_dir.is_some()
574 }
575
576 /// The residency settings for a pool of `total_blocks`, capped at the
577 /// operator context `context_cap` (`AIEN_KV_CONTEXT_TOKENS`).
578 pub fn residency_config(
579 &self,
580 total_blocks: usize,
581 context_cap: Option<usize>,
582 ) -> crate::kv_residency::KvResidencyConfig {
583 crate::kv_residency::KvResidencyConfig {
584 chunk_blocks: self.chunk_blocks,
585 context_cap,
586 restore_max_blocks: self
587 .restore_max_blocks
588 .unwrap_or_else(|| (total_blocks / 4).max(1)),
589 park: self.park,
590 restore: self.restore,
591 restore_retry_window_ms: self.restore_retry_window_ms,
592 drain_ms: self.worker.drain_ms,
593 }
594 }
595}
596
597/// Opens the host object store under `settings.store_dir` for `fields` (whose
598/// `chunk_tokens` must be `chunk_blocks * block_size`), puts the storage worker
599/// in front of it, and builds the residency layer over `kv`. `Ok(None)` when
600/// persistence is off. The worker's drive runs the resumable recovery in
601/// `AIEN_KV_STORE_RECOVERY_SLICE_MS` slices on the worker thread until it is
602/// done; until then the store is `Recovering` and every lookup misses (ADR
603/// 4.1), so the step loop is never blocked and a cold start only costs plain
604/// prefills.
605pub fn open_host_kv_residency(
606 settings: &KvPersistSettings,
607 fields: &aien_kv_store::NamespaceFields<'_>,
608 kv: SharedKvManager,
609 context_cap: Option<usize>,
610) -> Result<Option<crate::kv_residency::KvResidency>, String> {
611 use aien_kv_store::host_fs::{HostFsConfig, HostFsStore};
612 use aien_kv_store::worker::StorageWorker;
613 use aien_kv_store::KvStore;
614
615 let Some(root) = settings.store_dir.clone() else {
616 return Ok(None);
617 };
618 let seal_key = match &settings.store_key {
619 Some(Ok(k)) => k.clone(),
620 Some(Err(r)) => return Err(format!("persistent KV refused: {r}")),
621 None => return Err("persistent KV: the store key was not read".to_string()),
622 };
623 let identity = crate::kv_residency::KvIdentity::new(fields)
624 .map_err(|e| format!("persistent KV identity: {e}"))?;
625 let mut cfg = HostFsConfig::from_fields(root.clone(), fields)
626 .map_err(|e| format!("persistent KV store config: {e:?}"))?;
627 if let Some(v) = settings.quota_bytes {
628 cfg.quota_bytes = v;
629 }
630 if let Some(v) = settings.max_objects {
631 cfg.max_objects = v;
632 }
633 if let Some(v) = settings.recovery_slice_ms {
634 cfg.recovery_slice_ms = v;
635 }
636 cfg.seal_key = Some(seal_key);
637 let slice_ms = cfg.recovery_slice_ms;
638 let store = Arc::new(HostFsStore::open(cfg).map_err(|e| {
639 format!(
640 "persistent KV store open at {} ({KV_STORE_DIR_ENV}): {e:?}",
641 root.display()
642 )
643 })?);
644 let drive = {
645 let store = store.clone();
646 let mut recovered = false;
647 move || {
648 if !recovered {
649 let p = store.recover_step(slice_ms);
650 recovered = p.done || p.failed;
651 }
652 }
653 };
654 let worker = Arc::new(
655 StorageWorker::spawn(store, settings.worker.clone(), drive)
656 .map_err(|e| format!("persistent KV worker: {e:?}"))?,
657 );
658 let total_blocks = kv.read().total_block_count();
659 let residency = crate::kv_residency::KvResidency::new(
660 settings.residency_config(total_blocks, context_cap),
661 identity,
662 worker,
663 kv,
664 )?;
665 Ok(Some(residency))
666}
667
668/// What the daemon knows about the loaded model that the namespace binds
669/// (ADR 1.2): the resolved config, the backend that computes the K/V, the
670/// weights digest, and the engine identity (ADR 1.2.2, sc#504).
671/// `engine` has no default: the host path passes
672/// `compute_config::HostEngineIdentity::reference(arith_id).identity()`, an
673/// engine with its own build, weight format or run switches passes its own.
674#[derive(Debug, Clone, Copy)]
675pub struct ModelKvBinding<'a> {
676 pub model: &'a aien_abi_core::ModelConfig,
677 /// `TensorBackend::name()` of the backend that writes the K/V.
678 pub arith_id: &'a str,
679 pub model_sha256: [u8; 32],
680 pub model_digest_kind: &'a str,
681 /// Weight format as loaded, engine build, rounding class and engine config
682 /// digest of the engine that writes the K/V.
683 pub engine: aien_kv_store::EngineIdentity<'a>,
684}
685
686/// Parses a 64-hex-digit sha256 (the daemon's `ModelIdentity::model_sha256`).
687pub fn parse_sha256_hex(hex: &str) -> Result<[u8; 32], String> {
688 let hex = hex.trim();
689 if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
690 return Err(format!("model digest {hex:?} is not 64 hex digits"));
691 }
692 let mut out = [0u8; 32];
693 for (i, byte) in out.iter_mut().enumerate() {
694 *byte = u8::from_str_radix(&hex[2 * i..2 * i + 2], 16)
695 .map_err(|e| format!("model digest: {e}"))?;
696 }
697 Ok(out)
698}
699
700fn kv_dtype_of(d: KvDType) -> aien_kv_store::KvDtype {
701 match d {
702 KvDType::Fp4 => aien_kv_store::KvDtype::Fp4,
703 KvDType::Fp8 => aien_kv_store::KvDtype::Fp8,
704 KvDType::Bf16 => aien_kv_store::KvDtype::Bf16,
705 KvDType::Fp16 => aien_kv_store::KvDtype::Fp16,
706 KvDType::Fp32 => aien_kv_store::KvDtype::Fp32,
707 }
708}
709
710/// Daemon wiring (cut C7): with `AIEN_KV_STORE_DIR` set, binds the namespace
711/// to `model` and the spine's pool, opens the host store, starts the storage
712/// worker (recovery runs on it in slices), and installs the residency layer
713/// and its finish hook in the spine. Returns the startup log line, or
714/// `Ok(None)` with persistence off, in which case nothing at all is created or
715/// changed.
716pub fn enable_persistent_kv(
717 spine: &mut AienRuntimeSpine,
718 settings: &KvPersistSettings,
719 model: &ModelKvBinding<'_>,
720 context_cap: Option<usize>,
721) -> Result<Option<String>, String> {
722 use crate::compute_config::{ModelBinding, StoreInputs};
723 if !settings.enabled() {
724 return Ok(None);
725 }
726 // Fail closed without a valid store key (ADR 0003 section 20): no store is
727 // opened and nothing is written; the daemon serves with plain prefill.
728 if let Some(Err(refusal)) = &settings.store_key {
729 aien_kv_store::seal::note_key_refusal();
730 spine.refuse_kv_persistence(refusal.reason());
731 return Ok(Some(format!(
732 "persistent KV: REFUSED ({refusal}); running without persistence: no park, no restore, every prompt is prefilled"
733 )));
734 }
735 let kv = spine.kv_manager.clone();
736 let (layout, dtype, block_size) = {
737 let guard = kv.read();
738 let pool = guard
739 .pool()
740 .ok_or("persistent KV: the runtime KV manager has no tensor pool")?;
741 (
742 crate::kv_residency::layout_strides(pool.layout()),
743 kv_dtype_of(pool.config().dtype),
744 guard.block_size(),
745 )
746 };
747 let chunk_tokens = (settings.chunk_blocks as usize)
748 .checked_mul(block_size)
749 .and_then(|t| u32::try_from(t).ok())
750 .ok_or_else(|| format!("{KV_CHUNK_BLOCKS_ENV}: chunk size overflows"))?;
751 let binding = ModelBinding::from_model(model.model, model.arith_id)
752 .map_err(|e| format!("persistent KV model binding: {e}"))?;
753 let fields = binding
754 .namespace_fields(
755 &StoreInputs {
756 model_sha256: model.model_sha256,
757 model_digest_kind: model.model_digest_kind,
758 dtype,
759 layout,
760 backend_format: aien_kv_store::BackendFormat::HostPagedPoolV1,
761 chunk_tokens,
762 sharing_namespace: &settings.namespace,
763 },
764 &model.engine,
765 )
766 .map_err(|e| format!("persistent KV namespace: {e}"))?;
767 let Some(residency) = open_host_kv_residency(settings, &fields, kv, context_cap)? else {
768 return Ok(None);
769 };
770 let line = format!(
771 "persistent KV: store {} namespace {:?} chunk {} tokens, weights {}, engine build {:?}, rounding {:?}, park {}, restore {}, retry window {} ms, drain {} ms (recovering in the background)",
772 settings
773 .store_dir
774 .as_deref()
775 .map(|p| p.display().to_string())
776 .unwrap_or_default(),
777 settings.namespace,
778 chunk_tokens,
779 model.engine.weight_format.as_str(),
780 model.engine.engine_build_id,
781 model.engine.rounding_class,
782 if settings.park { "on" } else { "off" },
783 if settings.restore { "on" } else { "off" },
784 settings.restore_retry_window_ms,
785 settings.worker.drain_ms,
786 );
787 spine.enable_kv_residency(residency);
788 Ok(Some(line))
789}
790
791/// [`enable_persistent_kv`] with the settings read from the environment.
792pub fn enable_persistent_kv_from_env(
793 spine: &mut AienRuntimeSpine,
794 model: &ModelKvBinding<'_>,
795 context_cap: Option<usize>,
796) -> Result<Option<String>, String> {
797 let settings = KvPersistSettings::from_env()?;
798 enable_persistent_kv(spine, &settings, model, context_cap)
799}
800
801#[cfg(test)]
802mod tests {
803 use super::*;
804 use aien_inference_abi::model_config_from_hf_json;
805
806 /// Blocks the daemon asked for before #239 (aien-cli/src/commands.rs,
807 /// `SharedKvSizing { total_blocks: 8192 }`, sovereign-core 328a7e9).
808 const OLD_FIXED_DAEMON_BLOCKS: usize = 8192;
809
810 /// unsloth/Llama-3.2-1B-Instruct config.json, snapshot 5a8abab (the KV-relevant
811 /// fields as on disk; same text as the model_dir.rs fixture).
812 const LLAMA32_1B_CONFIG: &str = r#"{
813 "architectures": ["LlamaForCausalLM"], "attention_bias": false, "attention_dropout": 0.0,
814 "bos_token_id": 128000, "eos_token_id": 128009, "head_dim": 64, "hidden_act": "silu",
815 "hidden_size": 2048, "initializer_range": 0.02, "intermediate_size": 8192,
816 "max_position_embeddings": 131072, "mlp_bias": false, "model_type": "llama",
817 "num_attention_heads": 32, "num_hidden_layers": 16, "num_key_value_heads": 8,
818 "pad_token_id": 128004, "pretraining_tp": 1, "rms_norm_eps": 1e-05,
819 "rope_scaling": {"factor": 32.0, "high_freq_factor": 4.0, "low_freq_factor": 1.0,
820 "original_max_position_embeddings": 8192, "rope_type": "llama3"},
821 "rope_theta": 500000.0, "tie_word_embeddings": true, "torch_dtype": "bfloat16",
822 "vocab_size": 128256
823}"#;
824
825 /// HuggingFaceTB/SmolLM2-1.7B-Instruct config.json, revision 31b70e2e (the
826 /// fields this engine reads, as on disk; transformers.js block dropped).
827 const SMOLLM2_17B_CONFIG: &str = r#"{
828 "architectures": ["LlamaForCausalLM"], "attention_bias": false, "attention_dropout": 0.0,
829 "bos_token_id": 1, "eos_token_id": 2, "hidden_act": "silu", "hidden_size": 2048,
830 "initializer_range": 0.02, "intermediate_size": 8192, "max_position_embeddings": 8192,
831 "mlp_bias": false, "model_type": "llama", "num_attention_heads": 32,
832 "num_hidden_layers": 24, "num_key_value_heads": 32, "pad_token_id": 2,
833 "pretraining_tp": 1, "rms_norm_eps": 1e-05, "rope_scaling": null, "rope_theta": 130000,
834 "tie_word_embeddings": true, "torch_dtype": "bfloat16", "use_cache": true,
835 "vocab_size": 49152
836}"#;
837
838 fn cfg(id: &str, json: &str) -> aien_inference_abi::ModelConfig {
839 model_config_from_hf_json(id, json, None).expect("config.json parses")
840 }
841
842 fn old_fixed_bytes(c: &aien_inference_abi::ModelConfig) -> usize {
843 KvPoolConfig::for_model(
844 OLD_FIXED_DAEMON_BLOCKS,
845 c.block_size,
846 c.num_layers,
847 c.num_kv_heads,
848 c.head_dim,
849 SHARED_KV_DTYPE,
850 )
851 .total_bytes()
852 }
853
854 #[test]
855 fn llama32_1b_plan_is_byte_identical_to_the_old_fixed_pool() {
856 let c = cfg("unsloth/Llama-3.2-1B-Instruct", LLAMA32_1B_CONFIG);
857 let plan = KvPoolPlan::for_model(&c).unwrap();
858 assert_eq!(plan.context_tokens, 131_072);
859 assert_eq!(plan.block_size, 16);
860 assert_eq!(
861 (plan.num_layers, plan.num_kv_heads, plan.head_dim),
862 (16, 8, 64)
863 );
864 assert_eq!(plan.total_blocks, OLD_FIXED_DAEMON_BLOCKS);
865 // 2 * 16 * 8 * 64 * 2 (bf16 pool, SHARED_KV_DTYPE)
866 assert_eq!(plan.bytes_per_token, 32_768);
867 assert_eq!(plan.total_bytes, 4_294_967_296); // 4.00 GiB
868 assert_eq!(plan.total_bytes, old_fixed_bytes(&c));
869 assert_eq!(plan.total_bytes, plan.pool_config().total_bytes());
870 }
871
872 #[test]
873 fn smollm2_plan_is_sized_from_its_own_context() {
874 let c = cfg("HuggingFaceTB/SmolLM2-1.7B-Instruct", SMOLLM2_17B_CONFIG);
875 let plan = KvPoolPlan::for_model(&c).unwrap();
876 assert_eq!(plan.context_tokens, 8192);
877 assert_eq!(
878 (plan.num_layers, plan.num_kv_heads, plan.head_dim),
879 (24, 32, 64)
880 );
881 assert_eq!(plan.total_blocks, 512);
882 // 2 * 24 * 32 * 64 * 2 (bf16)
883 assert_eq!(plan.bytes_per_token, 196_608);
884 assert_eq!(plan.total_bytes, 1_610_612_736); // 1.50 GiB
885 assert_eq!(plan.total_bytes, plan.pool_config().total_bytes());
886 // The old fixed pool was 16x larger: 24.00 GiB (25.8 GB) at the same bf16 element.
887 assert_eq!(old_fixed_bytes(&c), 25_769_803_776);
888 assert_eq!(old_fixed_bytes(&c), 16 * plan.total_bytes);
889 }
890
891 #[test]
892 fn plan_rounds_a_partial_block_up_and_refuses_zero_or_overflow() {
893 let mut c = cfg("unsloth/Llama-3.2-1B-Instruct", LLAMA32_1B_CONFIG);
894 let plan = KvPoolPlan::for_context(&c, 17, "test").unwrap();
895 assert_eq!(plan.total_blocks, 2);
896 assert_eq!(plan.total_bytes, 2 * 16 * 32_768);
897 assert!(KvPoolPlan::for_context(&c, 0, "test")
898 .unwrap_err()
899 .contains("context_tokens is 0"));
900 c.num_layers = usize::MAX / 2;
901 assert!(KvPoolPlan::for_model(&c).unwrap_err().contains("overflow"));
902 }
903
904 #[test]
905 fn log_line_names_bytes_gib_and_every_parameter() {
906 let c = cfg("unsloth/Llama-3.2-1B-Instruct", LLAMA32_1B_CONFIG);
907 let line = KvPoolPlan::for_model(&c).unwrap().log_line();
908 for want in [
909 "4294967296 bytes",
910 "4.00 GiB",
911 "8192 blocks",
912 "16 tokens",
913 "16 layers",
914 "8 kv heads",
915 "64 head_dim",
916 "2 bytes",
917 "context 131072 tokens",
918 "max_position_embeddings",
919 ] {
920 assert!(line.contains(want), "{want:?} missing from {line:?}");
921 }
922 }
923
924 #[test]
925 fn mem_available_parses_kb_and_rejects_garbage() {
926 let meminfo =
927 "MemTotal: 130000000 kB\nMemFree: 1000 kB\nMemAvailable: 62000000 kB\n";
928 assert_eq!(parse_mem_available(meminfo), Some(62_000_000 * 1024));
929 assert_eq!(parse_mem_available("MemTotal: 1 kB\n"), None);
930 assert_eq!(parse_mem_available("MemAvailable: x kB\n"), None);
931 assert_eq!(parse_mem_available("MemAvailable: 5\n"), None);
932 }
933
934 #[test]
935 fn memory_check_refuses_with_requested_and_available_bytes() {
936 let err = check_kv_memory(3_221_225_472, Ok(1_073_741_824), false).unwrap_err();
937 assert!(err.contains("3221225472 bytes (3.00 GiB)"), "{err}");
938 assert!(err.contains("1073741824 bytes (1.00 GiB)"), "{err}");
939 assert!(err.contains("refusing"), "{err}");
940 assert!(check_kv_memory(10, Ok(10), false).is_ok());
941 }
942
943 fn tiny_config() -> aien_inference_abi::ModelConfig {
944 aien_inference_abi::ModelConfig {
945 model_id: "kv239-tiny".to_string(),
946 max_sequence_length: 40,
947 block_size: 16,
948 num_layers: 2,
949 num_heads: 4,
950 head_dim: 16,
951 num_kv_heads: 2,
952 hidden_dim: 64,
953 intermediate_dim: 128,
954 vocab_size: 64,
955 rms_norm_eps: 1e-5,
956 rope_theta: 10000.0,
957 rope_scaling: None,
958 tie_word_embeddings: false,
959 eos_token_ids: Vec::new(),
960 qk_norm: false,
961 }
962 }
963
964 // ---- #254: fail closed when memory cannot be established ----
965
966 #[test]
967 fn unreadable_meminfo_refuses_the_pool() {
968 let cfg = tiny_config();
969 let err = plan_checked_model_kv(
970 &cfg,
971 None,
972 &|| Err("/proc/meminfo cannot be read: No such file".to_string()),
973 false,
974 )
975 .unwrap_err();
976 assert!(err.contains("cannot be checked"), "{err}");
977 assert!(err.contains("refusing to allocate"), "{err}");
978 assert!(err.contains(ALLOW_UNCHECKED_MEMORY_ENV), "{err}");
979 }
980
981 #[test]
982 fn unreadable_meminfo_with_override_proceeds() {
983 // The override path also prints a WARNING line on stderr (see check_kv_memory).
984 let cfg = tiny_config();
985 let plan = plan_checked_model_kv(&cfg, None, &|| Err("unreadable".to_string()), true)
986 .expect("override set: proceeds");
987 assert_eq!(plan.total_blocks, 3);
988 // The override never bypasses a known shortage.
989 assert!(check_kv_memory(10, Ok(1), true).is_err());
990 }
991
992 #[test]
993 fn unparsable_meminfo_refuses_the_pool() {
994 for text in [
995 "MemTotal: 1 kB\n",
996 "MemAvailable: x kB\n",
997 "MemAvailable: 5\n",
998 "",
999 ] {
1000 let cfg = tiny_config();
1001 let err =
1002 plan_checked_model_kv(&cfg, None, &|| parse_mem_available_checked(text), false)
1003 .unwrap_err();
1004 assert!(err.contains("no parsable"), "{text:?}: {err}");
1005 }
1006 }
1007 #[test]
1008 fn daemon_plan_refuses_before_allocating_and_sizes_the_manager() {
1009 // Exercises the planning, memory check and pooled manager without building a
1010 // spine: a spine creates a RuntimeController, which reads the process-wide
1011 // AIEN_RUNTIME_STATE_DIR that other tests in this crate point at temp dirs.
1012 let cfg = tiny_config();
1013 let err = plan_checked_model_kv(&cfg, None, &|| Ok(1), false).unwrap_err();
1014 assert!(err.contains("refusing"), "{err}");
1015
1016 let plan =
1017 plan_checked_model_kv(&cfg, None, &|| Ok(1 << 30), false).expect("enough memory");
1018 // ceil(40 / 16) = 3 blocks of 16 tokens * (2 * 2 * 2 * 16 * 2) bytes per token (bf16).
1019 assert_eq!(plan.total_blocks, 3);
1020 assert_eq!(plan.total_bytes, 3 * 16 * 256);
1021
1022 let weights = TransformerWeights::reference_test_weights(&cfg);
1023 let mgr = build_model_kv_manager(&weights, plan.total_blocks).expect("pool built");
1024 assert_eq!(mgr.read().total_block_count(), 3);
1025 assert_eq!(plan.pool_config().total_bytes(), plan.total_bytes);
1026 }
1027
1028 #[test]
1029 fn kv_context_cap_parse_is_strict() {
1030 assert_eq!(parse_kv_context_cap("8192"), Ok(8192));
1031 assert_eq!(parse_kv_context_cap("1"), Ok(1));
1032 for bad in [
1033 "",
1034 "0",
1035 "00",
1036 "-1",
1037 "+5",
1038 " 8",
1039 "8 ",
1040 "8k",
1041 "1e3",
1042 "0x10",
1043 "99999999999999999999999",
1044 ] {
1045 let err = parse_kv_context_cap(bad).unwrap_err();
1046 assert!(err.contains(KV_CONTEXT_CAP_ENV), "{bad:?}: {err}");
1047 }
1048 }
1049
1050 #[test]
1051 fn kv_context_cap_only_lowers_the_model_context() {
1052 let cfg = tiny_config(); // max_sequence_length 40, block 16
1053 assert_eq!(
1054 KvPoolPlan::for_model_capped(&cfg, None).unwrap(),
1055 KvPoolPlan::for_model(&cfg).unwrap()
1056 );
1057 let capped = KvPoolPlan::for_model_capped(&cfg, Some(17)).unwrap();
1058 assert_eq!((capped.context_tokens, capped.total_blocks), (17, 2));
1059 assert!(capped.context_source.contains(KV_CONTEXT_CAP_ENV));
1060 assert_eq!(
1061 KvPoolPlan::for_model_capped(&cfg, Some(40))
1062 .unwrap()
1063 .total_blocks,
1064 3
1065 );
1066 let err = KvPoolPlan::for_model_capped(&cfg, Some(41)).unwrap_err();
1067 assert!(err.contains("can only lower"), "{err}");
1068 }
1069
1070 #[test]
1071 fn kv_context_cap_lets_a_long_context_model_fit_and_sizes_the_real_pool() {
1072 let cfg = tiny_config();
1073 let uncapped = KvPoolPlan::for_model(&cfg).unwrap().total_bytes as u64;
1074 let capped = KvPoolPlan::for_model_capped(&cfg, Some(16))
1075 .unwrap()
1076 .total_bytes as u64;
1077 assert!(capped < uncapped);
1078 // Memory between the two: the model's own context is refused, the cap fits.
1079 let avail = capped;
1080 assert!(plan_checked_model_kv(&cfg, None, &|| Ok(avail), false).is_err());
1081 let plan = plan_checked_model_kv(&cfg, Some(16), &|| Ok(avail), false).unwrap();
1082 assert_eq!(plan.total_blocks, 1);
1083 // The capped plan sizes the real pool. No spine here: a spine creates a
1084 // RuntimeController, which reads the process-wide AIEN_RUNTIME_STATE_DIR that
1085 // control::tests points at a dir holding deliberately damaged state files.
1086 let plan = plan_checked_model_kv(&cfg, Some(17), &|| Ok(1 << 30), false).unwrap();
1087 assert_eq!(plan.total_blocks, 2);
1088 let weights = TransformerWeights::reference_test_weights(&cfg);
1089 let mgr = build_model_kv_manager(&weights, plan.total_blocks).expect("pool built");
1090 assert_eq!(mgr.read().total_block_count(), 2);
1091 }
1092}