[ABI][KN][LD][CC][RT][LAB][SP][NT][TM][GW][Proofs][Docs] M0.5: realign workspace to vetta-infer-* microkernel architecture

Dissolve the M0 crates (core/io/proto/telemetry/hip/cli) into the approved
service layout abi/kn/ld/cc/rt/lab/sp/nt/tm/gw (docs/ARCHITECTURE.md).

- kn: Lean-verified control bus + service registry (bus_lifecycle.lean, 14 thms)
  and SlabRing/UMA broker; rt: PrefixState + hybrid checkpoint pool.
- sp: faithful throughput-aware Adaptive-K port of clover_policy.h
  (cooldowns, probes, throughput guards) with scenario parity tests.
- gw: strata-ctl-compatible wire emitters + serve session FSM
  (serve_session.lean, 10 thms); abi::serve accepts image= (Vision delta closed).
- abi: pure contracts, checked JSON/VTC1/GEN parsers, zero-alloc sampler.
- ld/cc: checked safetensors reader + write-once VTC1 writer / O_RDONLY reader.
- tm: lock-free telemetry; nt: LyraRpc; lab shares the rt executor core.
- Docs: ARCHITECTURE.md decision-complete spec (MoE-only scope, .vbundle,
  .vplan->CompiledPlan, wire contract, migration map); AGENTS.md Lean rule
  + tandem/review workflow.

Verified live: cargo test --workspace -D warnings = 46/46 PASS;
lean proofs = 34 theorems (slab_ring_dma 10, bus_lifecycle 14, serve_session 10),
0 sorryAx, standard axioms only; vetta-infer info on Inkling = 1244 tensors,
18.18 GiB, checked bounds.
This commit is contained in:
adm committed 2026-11-30 00:54:00 +01:00
1 parent 63b1668a92
commit 7b50f1c07c
49 files changed
+3211 -1208

No files matched your search

+272
View File
@@ -0,0 +1,272 @@
//! `vetta-infer-cc`: cache & storage (docs/ARCHITECTURE.md §2, §9).
//!
//! Hot/Cold MoE expert residency policy (LFU/LRU + domain pre-warm) and the
//! strictly `O_RDONLY` `VTC1` cache reader (0 SSD writes on every reload).
//! NVMe `io_uring O_DIRECT` zero-copy streaming into the `kn` SlabRing lands
//! with M2 (the only `unsafe` syscall surface of the engine).
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::os::unix::fs::FileExt;
use std::path::Path;
use vetta_infer_abi::vtc1::{
deserialize_meta, CacheRecord, CACHE_MAGIC, CACHE_VERSION, HEADER_SIZE,
};
use vetta_infer_abi::ExpertKey;
// ============================================================================
// 1. Hot/Cold MoE Expert Cache Policy
// ============================================================================
#[derive(Debug, Clone, Copy)]
struct ResidentMeta {
slot: usize,
hits: u64,
last_tick: u64,
pinned: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CacheLookup {
Hit { slot: usize },
Miss,
}
/// Manages a fixed pool of UMA resident expert slots (`capacity` experts).
#[derive(Debug, Clone)]
pub struct HotColdExpertCache {
capacity: usize,
tick: u64,
map: HashMap<ExpertKey, ResidentMeta>,
free_slots: Vec<usize>,
pub total_hits: u64,
pub total_misses: u64,
}
impl HotColdExpertCache {
pub fn new(capacity: usize) -> Self {
let cap = capacity.max(1);
let free_slots = (0..cap).rev().collect();
Self {
capacity: cap,
tick: 0,
map: HashMap::with_capacity(cap),
free_slots,
total_hits: 0,
total_misses: 0,
}
}
pub fn capacity(&self) -> usize {
self.capacity
}
pub fn resident_count(&self) -> usize {
self.map.len()
}
pub fn hit_rate(&self) -> f64 {
let tot = self.total_hits + self.total_misses;
if tot == 0 { 0.0 } else { self.total_hits as f64 / tot as f64 }
}
pub fn lookup(&mut self, key: ExpertKey) -> CacheLookup {
self.tick += 1;
if let Some(m) = self.map.get_mut(&key) {
m.hits += 1;
m.last_tick = self.tick;
self.total_hits += 1;
CacheLookup::Hit { slot: m.slot }
} else {
self.total_misses += 1;
CacheLookup::Miss
}
}
/// Picks a target slot to load `key` into (free slot or LFU+LRU unpinned victim).
/// Does not mutate residency until `commit_load` succeeds.
pub fn plan_load(&self, key: ExpertKey) -> Option<(usize, Option<ExpertKey>)> {
if let Some(m) = self.map.get(&key) {
return Some((m.slot, None));
}
if let Some(&slot) = self.free_slots.last() {
return Some((slot, None));
}
// Evict lowest-hit, oldest unpinned resident expert.
self.map
.iter()
.filter(|(_, m)| !m.pinned)
.min_by_key(|(_, m)| (m.hits, m.last_tick))
.map(|(&k, m)| (m.slot, Some(k)))
}
pub fn commit_load(&mut self, key: ExpertKey, slot: usize, evicted: Option<ExpertKey>, pinned: bool) {
self.tick += 1;
if let Some(ev) = evicted {
self.map.remove(&ev);
} else if let Some(pos) = self.free_slots.iter().position(|&s| s == slot) {
self.free_slots.swap_remove(pos);
}
self.map.insert(
key,
ResidentMeta {
slot,
hits: 1,
last_tick: self.tick,
pinned,
},
);
}
/// Returns the subset of domain-recommended experts not currently resident (candidates for NVMe pre-warm).
pub fn missing_for_prewarm(&self, recommended: &[ExpertKey]) -> Vec<ExpertKey> {
recommended
.iter()
.copied()
.filter(|k| !self.map.contains_key(k))
.collect()
}
}
// ============================================================================
// 2. Strictly `O_RDONLY` VTC1 Cache Reader (0 SSD writes on reload)
// ============================================================================
pub struct DiskCacheReader {
file: File,
pub file_size: u64,
pub records: Vec<CacheRecord>,
}
impl DiskCacheReader {
pub fn open_and_validate(path: impl AsRef<Path>, expected_fp: u64) -> Result<Self, String> {
let path = path.as_ref();
let file = OpenOptions::new()
.read(true)
.open(path)
.map_err(|e| format!("open cache {}: {e}", path.display()))?;
let file_size = file.metadata().map_err(|e| format!("stat cache: {e}"))?.len();
if file_size < HEADER_SIZE as u64 {
return Err("cache file too small".into());
}
let mut hdr = [0u8; HEADER_SIZE];
file.read_exact_at(&mut hdr, 0)
.map_err(|e| format!("read cache hdr: {e}"))?;
if hdr[0..8] != CACHE_MAGIC {
return Err("cache bad magic".into());
}
let version = u32::from_le_bytes(hdr[8..12].try_into().unwrap());
if version != CACHE_VERSION {
return Err(format!("cache version mismatch: {version}"));
}
let count = u32::from_le_bytes(hdr[12..16].try_into().unwrap());
let fp = u64::from_le_bytes(hdr[16..24].try_into().unwrap());
if fp != expected_fp {
return Err("cache fingerprint mismatch".into());
}
let meta_off = u64::from_le_bytes(hdr[24..32].try_into().unwrap());
let meta_bytes = u64::from_le_bytes(hdr[32..40].try_into().unwrap());
let total_bytes = u64::from_le_bytes(hdr[40..48].try_into().unwrap());
if total_bytes != file_size {
return Err("cache file size mismatch (incomplete)".into());
}
if meta_off < HEADER_SIZE as u64
|| meta_off > file_size
|| meta_bytes > file_size - meta_off
|| meta_bytes > 64 * 1024 * 1024
{
return Err("cache metadata out of bounds".into());
}
let mut mblob = vec![0u8; meta_bytes as usize];
file.read_exact_at(&mut mblob, meta_off)
.map_err(|e| format!("read cache meta: {e}"))?;
let records = deserialize_meta(&mblob, count)?;
for r in &records {
if r.data_offset > file_size || r.data_bytes > file_size - r.data_offset {
return Err(format!("cache record '{}' payload OOB", r.name));
}
}
Ok(Self { file, file_size, records })
}
pub fn read_slice(&self, off: u64, dst: &mut [u8]) -> Result<(), String> {
let len = dst.len() as u64;
if off > self.file_size || len > self.file_size - off {
return Err("cache read_slice OOB".into());
}
self.file
.read_exact_at(dst, off)
.map_err(|e| format!("cache pread: {e}"))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lfu_lru_eviction_and_domain_prewarm() {
let mut c = HotColdExpertCache::new(2);
let k0 = ExpertKey { layer: 0, expert: 1 };
let k1 = ExpertKey { layer: 0, expert: 2 };
let k2 = ExpertKey { layer: 0, expert: 3 };
assert_eq!(c.lookup(k0), CacheLookup::Miss);
let (s0, ev0) = c.plan_load(k0).unwrap();
assert!(ev0.is_none());
c.commit_load(k0, s0, ev0, false);
// Make k0 hot
assert_eq!(c.lookup(k0), CacheLookup::Hit { slot: s0 });
assert_eq!(c.lookup(k0), CacheLookup::Hit { slot: s0 });
let (s1, ev1) = c.plan_load(k1).unwrap();
c.commit_load(k1, s1, ev1, false);
// k2 should evict cold k1, keeping hot k0
let (s2, ev2) = c.plan_load(k2).unwrap();
assert_eq!(ev2, Some(k1));
assert_eq!(s2, s1);
c.commit_load(k2, s2, ev2, false);
assert_eq!(c.lookup(k0), CacheLookup::Hit { slot: s0 });
assert_eq!(c.missing_for_prewarm(&[k0, k1, k2]), vec![k1]);
}
#[test]
fn disk_cache_roundtrip_readonly_and_fingerprint() {
let p = std::env::temp_dir().join(format!("vetta_cc_cache_{}.bin", std::process::id()));
let _ = std::fs::remove_file(&p);
let fp = 0x1234_5678_ABCD_EF01u64;
let payload = vec![0x5Au8; 8192];
let mut wr = vetta_infer_ld::DiskCacheWriter::begin(&p, fp).unwrap();
wr.write_record(
CacheRecord {
kind: 1,
i0: 128,
i1: 256,
i2: 0,
flags: 0,
u0: 4096,
u1: 0,
data_offset: 0,
data_bytes: 0,
name: "layer.0.q8".into(),
},
&payload,
)
.unwrap();
wr.commit().unwrap();
let rd = DiskCacheReader::open_and_validate(&p, fp).unwrap();
assert_eq!(rd.records.len(), 1);
let mut got = vec![0u8; payload.len()];
rd.read_slice(rd.records[0].data_offset, &mut got).unwrap();
assert_eq!(got, payload);
assert!(DiskCacheReader::open_and_validate(&p, fp ^ 1).is_err());
assert!(rd.read_slice(u64::MAX, &mut got).is_err());
let _ = std::fs::remove_file(&p);
}
}