[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

-16
View File
@@ -1,16 +0,0 @@
[package]
name = "vetta-cli"
version.workspace = true
edition.workspace = true
license.workspace = true
[[bin]]
name = "vetta-infer"
path = "src/main.rs"
[dependencies]
vetta-core = { path = "../vetta-core" }
vetta-io = { path = "../vetta-io" }
vetta-proto = { path = "../vetta-proto" }
vetta-telemetry = { path = "../vetta-telemetry" }
vetta-hip = { path = "../vetta-hip" }
-9
View File
@@ -1,9 +0,0 @@
//! `vetta-core`: pure-Rust domain types, state machines, sampling, MoE cache policies, and traits.
//!
//! Zero external dependencies; 100% testable on CPU without a GPU.
pub mod moe;
pub mod prefix;
pub mod sampler;
pub mod slab;
pub mod traits;
-155
View File
@@ -1,155 +0,0 @@
//! Hot/Cold MoE expert cache policy for UMA + NVMe zero-copy DMA streaming.
//!
//! Tracks LFU/LRU expert residency in UMA memory and accepts domain pre-warm hints
//! from local telemetry or a remote control-plane router (Lyra).
use std::collections::HashMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ExpertKey {
pub layer: u16,
pub expert: u16,
}
#[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()
}
}
#[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]);
}
}
-105
View File
@@ -1,105 +0,0 @@
//! Core pluggable traits for WeightStore, Speculative Drafting (local or Lyra LAN), and Prefetching.
use crate::moe::ExpertKey;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuantFormat {
Bf16,
Fp32,
Q8G64T16,
Q4G64T16,
NvFp4,
MxFp8,
}
#[derive(Debug, Clone)]
pub struct DraftProposal {
pub tokens: Vec<i32>,
/// Optional scalar draft probabilities `q(x_j)` for lossless non-greedy Leviathan verification.
pub draft_probs: Option<Vec<f32>>,
}
/// Pluggable speculative drafter:
/// - Local MTP (1-layer) / Block-Diffusion preview
/// - Remote LAN drafter on **Lyra** (`~128 B/step`, `~0.3 ms` RTT on 2.5 Gbps Ethernet)
pub trait DraftProvider: Send {
fn name(&self) -> &'static str;
fn propose(&mut self, prefix_tail: &[i32], max_k: usize) -> Result<DraftProposal, String>;
fn notify_accepted(&mut self, accepted_tokens: &[i32]) -> Result<(), String>;
fn reset(&mut self);
}
/// Pluggable MoE prefetch advisor:
/// - Local router lookahead (`h_{L-1} -> W_router[L]`)
/// - Remote domain classifier on **Lyra** (`Dante/letteratura` vs `Lean 4/matematica` -> NVMe pre-warm)
pub trait PrefetchAdvisor: Send {
fn on_prompt_domain(&mut self, domain_tag: &str) -> Vec<ExpertKey>;
fn on_layer_routed(&mut self, layer: u16, active_experts: &[u16]) -> Vec<ExpertKey>;
}
/// Throughput-aware Adaptive-K speculative controller (prevents K=16 prose traps).
#[derive(Debug, Clone)]
pub struct AdaptiveKController {
k_max: usize,
cur_k: usize,
ema_ms_per_tok: [f64; 5], // index: 0->K=1, 1->K=4, 2->K=8, 3->K=12, 4->K=16
full_k8_streak: u32,
}
impl AdaptiveKController {
pub fn new(k_max: usize) -> Self {
let km = k_max.max(1);
Self {
k_max: km,
cur_k: km.min(8),
ema_ms_per_tok: [0.0; 5],
full_k8_streak: 0,
}
}
pub fn next_k(&self, rem_tokens: usize, ctx_room: usize) -> usize {
self.cur_k.min(self.k_max).min(rem_tokens.max(1)).min(ctx_room.max(1))
}
fn bucket(k: usize) -> usize {
match k {
0..=1 => 0,
2..=4 => 1,
5..=8 => 2,
9..=12 => 3,
_ => 4,
}
}
pub fn observe(&mut self, k_used: usize, accepted: usize, step_ms: f64) {
let mpt = step_ms / (accepted.max(1) as f64);
let b = Self::bucket(k_used);
self.ema_ms_per_tok[b] = if self.ema_ms_per_tok[b] == 0.0 {
mpt
} else {
0.7 * self.ema_ms_per_tok[b] + 0.3 * mpt
};
if k_used >= 8 && accepted >= k_used {
self.full_k8_streak += 1;
} else {
self.full_k8_streak = 0;
}
if accepted <= 2 && self.cur_k > 4 {
self.cur_k = 4;
} else if self.full_k8_streak >= 2 && self.k_max >= 16 {
// Only promote to K=16 if K=16 isn't demonstrably slower per token than K=8
if self.ema_ms_per_tok[4] == 0.0
|| self.ema_ms_per_tok[2] == 0.0
|| self.ema_ms_per_tok[4] <= self.ema_ms_per_tok[2] * 1.02
{
self.cur_k = 16;
}
} else if accepted >= 4 && self.cur_k < 8 && self.k_max >= 8 {
self.cur_k = 8;
} else if k_used >= 16 && accepted < 10 {
self.cur_k = 8;
}
}
}
+7
View File
@@ -0,0 +1,7 @@
[package]
name = "vetta-infer-abi"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
+77
View File
@@ -0,0 +1,77 @@
//! Control-bus contracts: service identity, lifecycle states and message formats.
//!
//! Lifecycle transitions are verified in `proofs/bus_lifecycle.lean` and
//! enforced by `vetta-infer-kn` (registry + bus). These are the shared types
//! every service speaks; the bus carries control-plane messages only — the
//! data plane exchanges UMA memory handles, never tensor copies.
/// Stable identity of a registered service (handed out by the registry, two-phase).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ServiceId(pub u32);
/// The service kinds of the approved architecture (docs/ARCHITECTURE.md §2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ServiceKind {
/// `ld` — loader & compiler (dual-step → `.vbundle/`)
Loader,
/// `cc` — cache & storage (UMA residency, NVMe streaming, Hot/Cold experts)
Cache,
/// `rt` — operational runtime (CompiledPlan on HIP, zero probes)
Runtime,
/// `lab` — laboratory runtime (same executor + probe hooks)
Lab,
/// `sp` — speculative coordinator (lossless verification, Adaptive-K)
Spec,
/// `nt` — LAN bridge to Lyra
Net,
/// `tm` — telemetry observer
Telemetry,
/// `gw` — gateway & CLI (`--serve`, HTTP, `vetta-infer`)
Gateway,
}
/// Lifecycle of one service — mirrors `SvcState` in `proofs/bus_lifecycle.lean`.
/// `Stopping` = STOP issued, draining in-flight work; `Stopped` is terminal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ServiceState {
Registered,
Running,
Stopping,
Stopped,
}
/// Typed control-plane payloads. Extended additively as services land;
/// unknown-to-a-service payloads are rejected explicitly, never silently.
#[derive(Debug, Clone, PartialEq)]
pub enum BusPayload {
/// Kernel → service: stop accepting new work and drain.
Stop,
/// Service → kernel: drain complete, resources released (acks `Stop`).
StopAck,
/// Domain routing hint (e.g. `"lean4"`, `"dante"`) for cache pre-warm.
DomainHint(String),
}
/// One routed control-plane message.
#[derive(Debug, Clone, PartialEq)]
pub struct BusMsg {
pub src: ServiceId,
pub dst: ServiceId,
pub payload: BusPayload,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn msg_shape() {
let m = BusMsg {
src: ServiceId(0),
dst: ServiceId(1),
payload: BusPayload::DomainHint("lean4".into()),
};
assert_eq!(m.dst, ServiceId(1));
assert_eq!(m.payload, BusPayload::DomainHint("lean4".into()));
}
}
+225
View File
@@ -0,0 +1,225 @@
//! Minimal checked JSON parser (zero external deps, strict UTF-8/escapes).
//! Pure parsing shared by `ld` (safetensors headers, index.json), `cc` and `gw`
//! (manifest, `.vplan`). No IO here.
#[derive(Debug, Clone, PartialEq)]
pub enum JsonVal {
Null,
Bool(bool),
Num(f64),
Int(u64),
Str(String),
Arr(Vec<JsonVal>),
Obj(std::collections::HashMap<String, JsonVal>),
}
impl JsonVal {
pub fn as_obj(&self) -> Option<&std::collections::HashMap<String, JsonVal>> {
match self {
JsonVal::Obj(m) => Some(m),
_ => None,
}
}
pub fn as_arr(&self) -> Option<&[JsonVal]> {
match self {
JsonVal::Arr(v) => Some(v),
_ => None,
}
}
pub fn as_str(&self) -> Option<&str> {
match self {
JsonVal::Str(s) => Some(s),
_ => None,
}
}
pub fn as_u64(&self) -> Option<u64> {
match self {
JsonVal::Int(n) => Some(*n),
JsonVal::Num(f) if *f >= 0.0 && f.fract() == 0.0 && *f <= (u64::MAX as f64) => Some(*f as u64),
_ => None,
}
}
}
struct JsonParser<'a> {
b: &'a [u8],
i: usize,
}
impl<'a> JsonParser<'a> {
fn skip_ws(&mut self) {
while self.i < self.b.len() && matches!(self.b[self.i], b' ' | b'\n' | b'\r' | b'\t') {
self.i += 1;
}
}
fn parse_str(&mut self) -> Result<String, String> {
if self.b.get(self.i) != Some(&b'"') {
return Err("expected '\"'".into());
}
self.i += 1;
let mut out = Vec::new();
while self.i < self.b.len() {
let c = self.b[self.i];
self.i += 1;
if c == b'"' {
return String::from_utf8(out).map_err(|_| "invalid UTF-8 in JSON string".into());
}
if c == b'\\' {
if self.i >= self.b.len() {
return Err("truncated JSON escape".into());
}
let e = self.b[self.i];
self.i += 1;
match e {
b'"' => out.push(b'"'),
b'\\' => out.push(b'\\'),
b'/' => out.push(b'/'),
b'b' => out.push(0x08),
b'f' => out.push(0x0C),
b'n' => out.push(b'\n'),
b'r' => out.push(b'\r'),
b't' => out.push(b'\t'),
b'u' => {
if self.i + 4 > self.b.len() {
return Err("truncated \\u escape".into());
}
let hex = std::str::from_utf8(&self.b[self.i..self.i + 4])
.map_err(|_| "bad \\u hex")?;
let code = u32::from_str_radix(hex, 16).map_err(|_| "bad \\u hex")?;
self.i += 4;
let ch = char::from_u32(code).unwrap_or('\u{FFFD}');
let mut buf = [0u8; 4];
out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
}
_ => return Err("unsupported JSON escape".into()),
}
} else {
out.push(c);
}
}
Err("unterminated JSON string".into())
}
fn parse_val(&mut self, depth: usize) -> Result<JsonVal, String> {
if depth > 64 {
return Err("JSON nesting too deep".into());
}
self.skip_ws();
let &c = self.b.get(self.i).ok_or_else(|| "unexpected EOF in JSON".to_string())?;
match c {
b'"' => Ok(JsonVal::Str(self.parse_str()?)),
b'{' => {
self.i += 1;
let mut map = std::collections::HashMap::new();
self.skip_ws();
if self.b.get(self.i) == Some(&b'}') {
self.i += 1;
return Ok(JsonVal::Obj(map));
}
loop {
self.skip_ws();
let k = self.parse_str()?;
self.skip_ws();
if self.b.get(self.i) != Some(&b':') {
return Err("expected ':'".into());
}
self.i += 1;
let v = self.parse_val(depth + 1)?;
map.insert(k, v);
self.skip_ws();
match self.b.get(self.i) {
Some(&b',') => self.i += 1,
Some(&b'}') => {
self.i += 1;
return Ok(JsonVal::Obj(map));
}
_ => return Err("expected ',' or '}'".into()),
}
}
}
b'[' => {
self.i += 1;
let mut arr = Vec::new();
self.skip_ws();
if self.b.get(self.i) == Some(&b']') {
self.i += 1;
return Ok(JsonVal::Arr(arr));
}
loop {
arr.push(self.parse_val(depth + 1)?);
self.skip_ws();
match self.b.get(self.i) {
Some(&b',') => self.i += 1,
Some(&b']') => {
self.i += 1;
return Ok(JsonVal::Arr(arr));
}
_ => return Err("expected ',' or ']'".into()),
}
}
}
b't' if self.b[self.i..].starts_with(b"true") => {
self.i += 4;
Ok(JsonVal::Bool(true))
}
b'f' if self.b[self.i..].starts_with(b"false") => {
self.i += 5;
Ok(JsonVal::Bool(false))
}
b'n' if self.b[self.i..].starts_with(b"null") => {
self.i += 4;
Ok(JsonVal::Null)
}
b'-' | b'0'..=b'9' => {
let start = self.i;
if self.b[self.i] == b'-' {
self.i += 1;
}
let mut is_float = false;
while self.i < self.b.len() {
match self.b[self.i] {
b'0'..=b'9' => self.i += 1,
b'.' | b'e' | b'E' | b'+' | b'-' => {
is_float = true;
self.i += 1;
}
_ => break,
}
}
let s = std::str::from_utf8(&self.b[start..self.i]).map_err(|_| "bad number")?;
if !is_float && !s.starts_with('-') {
if let Ok(u) = s.parse::<u64>() {
return Ok(JsonVal::Int(u));
}
}
let f = s.parse::<f64>().map_err(|_| format!("invalid number '{s}'"))?;
Ok(JsonVal::Num(f))
}
_ => Err(format!("unexpected char '{}' in JSON", c as char)),
}
}
}
pub fn parse_json(text: &str) -> Result<JsonVal, String> {
let mut p = JsonParser { b: text.as_bytes(), i: 0 };
let v = p.parse_val(0)?;
p.skip_ws();
if p.i != p.b.len() {
return Err("trailing characters in JSON".into());
}
Ok(v)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strict_parsing() {
assert!(parse_json("{\"a\":[1,2.5,true,null]}").is_ok());
assert!(parse_json("{\"a\":1} trailing").is_err());
assert!(parse_json("\"\\u0041\"").unwrap().as_str() == Some("A"));
assert!(parse_json("[1,2").is_err());
}
}
+16
View File
@@ -0,0 +1,16 @@
//! `vetta-infer-abi`: shared contracts between the microkernel and all services.
//!
//! Domain types, bus message formats, `.vplan` opcodes, wire-protocol parsing,
//! pure checked parsers (JSON, VTC1 metadata) and sampling algorithms
//! (docs/ARCHITECTURE.md §2, §4, §6, §9).
//! Zero external dependencies; pure data and pure functions only — no IO, no syscalls.
pub mod bus;
pub mod json;
pub mod sampler;
pub mod serve;
pub mod traits;
pub mod vplan;
pub mod vtc1;
pub use traits::ExpertKey;
@@ -2,6 +2,7 @@
//!
//! Eliminates F-07 (centralized `mask_token_id` suppression) and F-09 (no 1 MiB/token heap churn,
//! no silent 256-token truncation for `top_k == 0`, explicit non-finite logit count).
//! Pure algorithms shared by `rt`, `sp` and `gw` (docs/ARCHITECTURE.md §9).
use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap};
@@ -470,4 +471,4 @@ mod tests {
assert_eq!(rep.nonfinite_logits, 1);
assert_eq!(rep.token, 3); // token 2 was suppressed
}
}
}
@@ -1,7 +1,13 @@
//! `vetta-proto`: unified `--serve` wire protocol (`strata-ctl` compatible, including `GEN 0` pre-warm)
//! and lightweight Lyra LAN control-plane message schemas.
//! `--serve` wire protocol parsing — `strata-ctl` compatible (docs/ARCHITECTURE.md §6).
//!
//! Living consumer spec: `strata-ctl/src/engine/protocol.rs` (`Sampling::keys`,
//! `gen_line`). Accepted keys include everything the consumer emits today:
//! `temperature`, `top_p`, `top_k`, `min_p`, `penalty_*`, `seed`, `image=`
//! (repeatable, Vision), plus engine extensions `spec`, `domain`, `draft_top_k`.
//! Unknown keys are rejected explicitly (`ERR`), never silently ignored.
//! `GEN 0` = prefill + immediate `DONE` (pre-warm), never an error.
use vetta_core::sampler::SamplingOpts;
use crate::sampler::SamplingOpts;
#[derive(Debug, Clone, PartialEq)]
pub enum ServeCommand {
@@ -19,6 +25,8 @@ pub struct ParsedGen {
pub spec_mode: Option<usize>,
pub draft_top_k: Option<usize>,
pub domain_hint: Option<String>,
/// `image=<encoded path>` keys in prompt order (strata-ctl Vision).
pub images: Vec<String>,
pub ids: Vec<i32>,
}
@@ -63,6 +71,7 @@ pub fn parse_serve_line(line: &str, vocab_size: usize) -> Result<ServeCommand, S
let mut spec_mode = None;
let mut draft_top_k = None;
let mut domain_hint = None;
let mut images = Vec::new();
for &kv in &toks[2..toks.len() - 1] {
let (k, v) = kv
@@ -122,6 +131,9 @@ pub fn parse_serve_line(line: &str, vocab_size: usize) -> Result<ServeCommand, S
let n: usize = v.parse().map_err(|_| format!("GEN: bad {k}"))?;
draft_top_k = Some(n.min(16));
}
"image" => {
images.push(v.to_string());
}
_ => return Err(format!("GEN: unknown key '{k}'")),
}
}
@@ -133,6 +145,7 @@ pub fn parse_serve_line(line: &str, vocab_size: usize) -> Result<ServeCommand, S
spec_mode,
draft_top_k,
domain_hint,
images,
ids,
}))
}
@@ -145,14 +158,6 @@ fn parse_finite_f32(v: &str, key: &str) -> Result<f32, String> {
Ok(f)
}
/// Compact LAN RPC messages for Sogliola <-> Lyra (`< 1 KB/step` on 2.5 Gbps Ethernet).
#[derive(Debug, Clone, PartialEq)]
pub enum LyraRpc {
DraftRequest { session_id: u64, accepted_tail: Vec<i32>, max_k: u8 },
DraftResponse { session_id: u64, proposed: Vec<i32>, probs: Vec<f32> },
DomainHint { session_id: u64, domain: String, confidence: f32 },
}
#[cfg(test)]
mod tests {
use super::*;
@@ -172,4 +177,35 @@ mod tests {
assert!(parse_serve_line("GEN 16 temperature=nan 1,2", 100).is_err());
assert!(parse_serve_line("GEN 16 unknown=1 1,2", 100).is_err());
}
}
#[test]
fn strata_ctl_exact_lines_parse() {
// Verbatim shapes emitted by strata-ctl `Sampling::keys` + `gen_line`.
let cmd = parse_serve_line("GEN 512 temperature=0.8 image=%2Fmnt%2Fpic.png 1,2,300", 1000).unwrap();
let ServeCommand::Gen(g) = cmd else { panic!("expected Gen") };
assert_eq!(g.max_new, 512);
assert_eq!(g.sampling.temperature, 0.8);
assert_eq!(g.images, vec!["%2Fmnt%2Fpic.png"]);
assert_eq!(g.ids, vec![1, 2, 300]);
// top_k=0 maps to 64 on the consumer side; penalties drag the window.
let cmd = parse_serve_line("GEN 128 top_k=64 penalty_repeat=1.1 penalty_last_n=64 seed=42 7,8", 1000).unwrap();
let ServeCommand::Gen(g) = cmd else { panic!("expected Gen") };
assert_eq!(g.sampling.top_k, 64);
assert_eq!(g.sampling.penalty_repeat, 1.1);
assert_eq!(g.sampling.penalty_last_n, 64);
assert_eq!(g.sampling.seed, 42);
// Multiple images keep prompt order.
let cmd = parse_serve_line("GEN 16 image=a.png image=b.png 1", 100).unwrap();
let ServeCommand::Gen(g) = cmd else { panic!("expected Gen") };
assert_eq!(g.images, vec!["a.png", "b.png"]);
}
#[test]
fn lifecycle_commands() {
assert_eq!(parse_serve_line("STOP", 10).unwrap(), ServeCommand::Stop);
assert_eq!(parse_serve_line("QUIT", 10).unwrap(), ServeCommand::Quit);
assert_eq!(parse_serve_line("RESET", 10).unwrap(), ServeCommand::Reset);
}
}
+44
View File
@@ -0,0 +1,44 @@
//! Core pluggable traits and shared domain types: WeightStore quantization formats,
//! Speculative Drafting (local or Lyra LAN), and Prefetching.
/// `(layer, expert)` identity of one MoE expert (shared by cc, tm, sp).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ExpertKey {
pub layer: u16,
pub expert: u16,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuantFormat {
Bf16,
Fp32,
Q8G64T16,
Q4G64T16,
NvFp4,
MxFp8,
}
#[derive(Debug, Clone)]
pub struct DraftProposal {
pub tokens: Vec<i32>,
/// Optional scalar draft probabilities `q(x_j)` for lossless non-greedy Leviathan verification.
pub draft_probs: Option<Vec<f32>>,
}
/// Pluggable speculative drafter:
/// - Local MTP (1-layer) / Block-Diffusion preview
/// - Remote LAN drafter on **Lyra** (`~128 B/step`, `~0.3 ms` RTT on 2.5 Gbps Ethernet)
pub trait DraftProvider: Send {
fn name(&self) -> &'static str;
fn propose(&mut self, prefix_tail: &[i32], max_k: usize) -> Result<DraftProposal, String>;
fn notify_accepted(&mut self, accepted_tokens: &[i32]) -> Result<(), String>;
fn reset(&mut self);
}
/// Pluggable MoE prefetch advisor:
/// - Local router lookahead (`h_{L-1} -> W_router[L]`)
/// - Remote domain classifier on **Lyra** (`Dante/letteratura` vs `Lean 4/matematica` -> NVMe pre-warm)
pub trait PrefetchAdvisor: Send {
fn on_prompt_domain(&mut self, domain_tag: &str) -> Vec<ExpertKey>;
fn on_layer_routed(&mut self, layer: u16, active_experts: &[u16]) -> Vec<ExpertKey>;
}
+53
View File
@@ -0,0 +1,53 @@
//! `.vplan` micro-bytecode opcodes (docs/ARCHITECTURE.md §4).
//!
//! Flat, fixed, non-Turing-complete: each compute opcode maps 1:1 to a HIP
//! microkernel in `kernels/hip/vetta_kernels.h`. Control flow is limited to
//! `LoopLayer` / `BranchB` so `memory.vplan` arena safety stays decidable
//! in Lean 4. Operands are resolved at boot into `CompiledPlan` (rt), never
//! looked up per token.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VplanOp {
// Compute opcodes (1:1 with the <15 microkernel set)
EmbedBf16,
RmsNorm,
QuantizeXG64,
GemmQ8G64T16,
GemmQ4G64T16,
GemmNvfp4Mxfp8,
RopeKvWrite,
FlashGqaWmma,
GdnChunkwiseWy,
GdnRecurrentStep,
MoeRouteBucket,
MoeW13Wmma,
MoeW2Wmma,
MoeReduce,
VitFlashAttnWmma,
GpuPenaltiesTopk,
// Restricted control flow
/// Repeat the enclosed layer body for each model layer.
LoopLayer,
/// Batch-size dispatch (e.g. prefill `B >= 16` vs Split-KV decode `B <= 2`).
BranchB,
}
impl VplanOp {
/// True for the two restricted control-flow opcodes.
pub fn is_control(self) -> bool {
matches!(self, Self::LoopLayer | Self::BranchB)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn control_vs_compute() {
assert!(VplanOp::LoopLayer.is_control());
assert!(VplanOp::BranchB.is_control());
assert!(!VplanOp::GemmQ8G64T16.is_control());
assert!(!VplanOp::GdnChunkwiseWy.is_control());
}
}
+150
View File
@@ -0,0 +1,150 @@
//! `VTC1` write-once NVMe cache format — pure metadata contracts shared by
//! `ld` (atomic writer) and `cc` (`O_RDONLY` reader).
//!
//! Eliminates audit-05 F-05 (pre-reserve OOM on corrupt count) by construction:
//! the record count is validated against the blob size BEFORE any allocation.
pub const CACHE_MAGIC: [u8; 8] = *b"VTCACHE1";
pub const CACHE_VERSION: u32 = 1;
pub const CACHE_ALIGN: u64 = 4096;
pub const HEADER_SIZE: usize = 48;
pub const MIN_REC_BYTES: usize = 1 + 4 * 4 + 4 * 8 + 4; // 53 B minimum per serialized record
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CacheRecord {
pub kind: u8,
pub i0: i32,
pub i1: i32,
pub i2: i32,
pub flags: u32,
pub u0: u64,
pub u1: u64,
pub data_offset: u64,
pub data_bytes: u64,
pub name: String,
}
pub fn fnv1a_u64(bytes: &[u8], seed: u64) -> u64 {
let mut h = seed;
for &b in bytes {
h ^= b as u64;
h = h.wrapping_mul(0x0000_0100_0000_01B3);
}
h
}
pub fn align_up(v: u64, align: u64) -> Result<u64, String> {
let rem = v % align;
if rem == 0 {
Ok(v)
} else {
v.checked_add(align - rem).ok_or_else(|| "align_up overflow".into())
}
}
pub fn serialize_meta(recs: &[CacheRecord]) -> Vec<u8> {
let mut out = Vec::new();
for r in recs {
out.push(r.kind);
out.extend_from_slice(&r.i0.to_le_bytes());
out.extend_from_slice(&r.i1.to_le_bytes());
out.extend_from_slice(&r.i2.to_le_bytes());
out.extend_from_slice(&r.flags.to_le_bytes());
out.extend_from_slice(&r.u0.to_le_bytes());
out.extend_from_slice(&r.u1.to_le_bytes());
out.extend_from_slice(&r.data_offset.to_le_bytes());
out.extend_from_slice(&r.data_bytes.to_le_bytes());
let nlen = r.name.len() as u32;
out.extend_from_slice(&nlen.to_le_bytes());
out.extend_from_slice(r.name.as_bytes());
}
out
}
pub fn deserialize_meta(blob: &[u8], count: u32) -> Result<Vec<CacheRecord>, String> {
// Anti-OOM check BEFORE `Vec::with_capacity(count)` (audit-05 F-05)
if (count as usize) > blob.len() / MIN_REC_BYTES {
return Err(format!(
"corrupt cache metadata: count={count} exceeds blob capacity ({} B)",
blob.len()
));
}
let mut out = Vec::with_capacity(count as usize);
let mut pos = 0usize;
let take = |pos: &mut usize, n: usize| -> Result<&[u8], String> {
if n > blob.len().saturating_sub(*pos) {
return Err("truncated cache metadata".into());
}
let s = &blob[*pos..*pos + n];
*pos += n;
Ok(s)
};
for _ in 0..count {
let kind = take(&mut pos, 1)?[0];
let i0 = i32::from_le_bytes(take(&mut pos, 4)?.try_into().unwrap());
let i1 = i32::from_le_bytes(take(&mut pos, 4)?.try_into().unwrap());
let i2 = i32::from_le_bytes(take(&mut pos, 4)?.try_into().unwrap());
let flags = u32::from_le_bytes(take(&mut pos, 4)?.try_into().unwrap());
let u0 = u64::from_le_bytes(take(&mut pos, 8)?.try_into().unwrap());
let u1 = u64::from_le_bytes(take(&mut pos, 8)?.try_into().unwrap());
let data_offset = u64::from_le_bytes(take(&mut pos, 8)?.try_into().unwrap());
let data_bytes = u64::from_le_bytes(take(&mut pos, 8)?.try_into().unwrap());
let nlen = u32::from_le_bytes(take(&mut pos, 4)?.try_into().unwrap()) as usize;
if nlen > 4096 {
return Err("cache record name too long".into());
}
let nbytes = take(&mut pos, nlen)?;
let name = std::str::from_utf8(nbytes)
.map_err(|_| "non-UTF-8 cache record name")?
.to_string();
out.push(CacheRecord {
kind,
i0,
i1,
i2,
flags,
u0,
u1,
data_offset,
data_bytes,
name,
});
}
if pos != blob.len() {
return Err("trailing bytes in cache metadata".into());
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn anti_oom_before_reserve() {
// Absurd entry count rejected BEFORE Vec::with_capacity
assert!(deserialize_meta(&[0u8; 64], u32::MAX).is_err());
}
#[test]
fn meta_roundtrip_and_alignment() {
let rec = CacheRecord {
kind: 1,
i0: 128,
i1: 256,
i2: 0,
flags: 0,
u0: 4096,
u1: 0,
data_offset: 4096,
data_bytes: 8192,
name: "layer.0.q8".into(),
};
let blob = serialize_meta(&[rec.clone()]);
let back = deserialize_meta(&blob, 1).unwrap();
assert_eq!(back, vec![rec]);
assert_eq!(align_up(4097, CACHE_ALIGN).unwrap(), 8192);
assert_eq!(align_up(4096, CACHE_ALIGN).unwrap(), 4096);
assert!(align_up(u64::MAX, CACHE_ALIGN).is_err());
}
}
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "vetta-infer-cc"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
vetta-infer-abi = { path = "../vetta-infer-abi" }
[dev-dependencies]
vetta-infer-ld = { path = "../vetta-infer-ld" }
+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);
}
}
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "vetta-infer-gw"
version.workspace = true
edition.workspace = true
license.workspace = true
[[bin]]
name = "vetta-infer"
path = "src/main.rs"
[dependencies]
vetta-infer-abi = { path = "../vetta-infer-abi" }
vetta-infer-ld = { path = "../vetta-infer-ld" }
+143
View File
@@ -0,0 +1,143 @@
//! `vetta-infer-gw`: gateway & CLI (docs/ARCHITECTURE.md §2, §6).
//!
//! Engine → consumer wire emitters, matching `strata-ctl/src/engine/protocol.rs`
//! (`EngineLine::parse`) field for field:
//! `READY <ctx> [stop] [hold] [holdb]`, `INFO k=v …`, `T <id>`,
//! `PP <read> <total> [ms] [tok_s]`, `RESUME <n>`,
//! `DONE <gen> <prompt> <prompt_ms> <decode_ms> <finish> [extra…]`, `ERR <msg>`.
//!
//! `DONE` fields 1–5 are stable; the tail is kept raw by the consumer, so new
//! statistics can be appended without breaking it. Floats use Python-repr
//! spelling (`1.0`), which the consumer's parser expects.
pub mod session;
/// Python-repr float spelling (always a decimal point), as `strata-ctl` emits.
fn fmt_float(v: f64) -> String {
let s = format!("{v}");
if s.contains('.') {
s
} else {
format!("{s}.0")
}
}
/// First meaningful line after startup. `INFO` may precede it; the consumer
/// treats any other pre-`READY` line as startup chatter and `ERR` as refusal.
pub fn ready_line(max_context: u32, can_stop: bool, can_hold: bool, can_hold_batch: bool) -> String {
let mut s = format!("READY {max_context}");
if can_stop {
s.push_str(" stop");
}
if can_hold {
s.push_str(" hold");
}
if can_hold_batch {
s.push_str(" holdb");
}
s
}
pub fn info_line(pairs: &[(&str, &str)]) -> String {
let mut s = String::from("INFO");
for (k, v) in pairs {
s.push(' ');
s.push_str(k);
s.push('=');
s.push_str(v);
}
s
}
pub fn token_line(id: u32) -> String {
format!("T {id}")
}
/// Prefill progress, one per chunk. `tok_s_mean` is optional (4th field).
pub fn pp_line(read: u32, total: u32, ms: f64, tok_s_mean: Option<f64>) -> String {
match tok_s_mean {
Some(ts) => format!("PP {read} {total} {} {}", fmt_float(ms), fmt_float(ts)),
None => format!("PP {read} {total} {}", fmt_float(ms)),
}
}
pub fn resume_line(n: u32) -> String {
format!("RESUME {n}")
}
/// End of request. Fields 1–5 stable across versions; `extra` is the raw tail
/// (draft stats, cache hits, expert tiers, …) the consumer preserves verbatim.
pub fn done_line(
generated: u32,
prompt_tokens: u32,
prompt_ms: f64,
decode_ms: f64,
finish: &str,
extra: &[String],
) -> String {
let mut s = format!(
"DONE {generated} {prompt_tokens} {} {} {finish}",
fmt_float(prompt_ms),
fmt_float(decode_ms)
);
for e in extra {
s.push(' ');
s.push_str(e);
}
s
}
pub fn err_line(msg: &str) -> String {
format!("ERR {msg}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ready_flags_match_consumer_parse() {
assert_eq!(ready_line(262144, true, true, false), "READY 262144 stop hold");
assert_eq!(ready_line(4096, false, false, false), "READY 4096");
assert_eq!(ready_line(8192, true, false, true), "READY 8192 stop holdb");
}
#[test]
fn info_and_token_shapes() {
assert_eq!(
info_line(&[("version", "0.1.0"), ("expert_slots", "64")]),
"INFO version=0.1.0 expert_slots=64"
);
assert_eq!(token_line(151645), "T 151645");
assert_eq!(resume_line(512), "RESUME 512");
}
#[test]
fn prefill_progress_optional_mean() {
assert_eq!(pp_line(1024, 8192, 431.5, Some(2373.2)), "PP 1024 8192 431.5 2373.2");
assert_eq!(pp_line(128, 512, 90.0, None), "PP 128 512 90.0");
}
#[test]
fn done_five_stable_fields_and_raw_tail() {
assert_eq!(
done_line(41, 128, 90.5, 310.25, "stop", &[]),
"DONE 41 128 90.5 310.25 stop"
);
let extra: Vec<String> = ["7", "10", "55", "chunk=2048"].iter().map(|s| s.to_string()).collect();
assert_eq!(
done_line(41, 128, 90.5, 310.25, "length", &extra),
"DONE 41 128 90.5 310.25 length 7 10 55 chunk=2048"
);
// Integral floats keep the Python-repr ".0" spelling.
assert_eq!(done_line(1, 2, 3.0, 4.0, "stop", &[]), "DONE 1 2 3.0 4.0 stop");
}
#[test]
fn err_shape() {
assert_eq!(
err_line("GEN: unknown/unsupported key pen_from"),
"ERR GEN: unknown/unsupported key pen_from"
);
}
}
@@ -1,9 +1,9 @@
//! `vetta-infer` CLI entrypoint.
//! `vetta-infer` CLI entrypoint (gateway crate).
use std::collections::BTreeMap;
use std::env;
use std::process::ExitCode;
use vetta_io::SafetensorsArchive;
use vetta_infer_ld::SafetensorsArchive;
fn usage() {
eprintln!("vetta-infer {} — MoE-first microkernel inference engine (Rust + HIP)", env!("CARGO_PKG_VERSION"));
@@ -62,4 +62,4 @@ fn main() -> ExitCode {
ExitCode::from(2)
}
}
}
}
+263
View File
@@ -0,0 +1,263 @@
//! `--serve` request lifecycle — implements `proofs/serve_session.lean`.
//!
//! The engine-side spine that talks to `strata-ctl` (docs/ARCHITECTURE.md §6):
//! GEN/STOP/QUIT, `GEN 0` pre-warm, and the STOP→DONE drain guarantee. Pure
//! state machine emitting wire lines via the `gw` emitters; the GPU backend
//! feeds it events, so the whole contract is CPU-testable without a device.
use vetta_infer_abi::serve::ParsedGen;
use crate::{done_line, err_line, pp_line, resume_line, token_line};
/// Mirrors `ReqState` in `proofs/serve_session.lean`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionState {
Idle,
Prefilling,
Decoding,
Stopping,
Done,
}
#[derive(Debug, Clone)]
pub struct ServeSession {
state: SessionState,
max_new: usize,
generated: u32,
prompt_tokens: u32,
reused: u32,
prompt_ms: f64,
decode_ms: f64,
finish: String,
}
impl Default for ServeSession {
fn default() -> Self {
Self::new()
}
}
impl ServeSession {
pub fn new() -> Self {
Self {
state: SessionState::Idle,
max_new: 0,
generated: 0,
prompt_tokens: 0,
reused: 0,
prompt_ms: 0.0,
decode_ms: 0.0,
finish: String::new(),
}
}
pub fn state(&self) -> SessionState {
self.state
}
pub fn generated(&self) -> u32 {
self.generated
}
fn done(&mut self, finish: &str, decode_ms: f64) -> Vec<String> {
self.decode_ms = decode_ms;
self.finish = finish.to_string();
self.state = SessionState::Done;
vec![done_line(
self.generated,
self.prompt_tokens,
self.prompt_ms,
self.decode_ms,
&self.finish,
&[],
)]
}
/// `ReqStep.gen`: Idle -> Prefilling. Wrong state is an explicit error.
pub fn on_gen(&mut self, g: &ParsedGen) -> Result<Vec<String>, String> {
if self.state != SessionState::Idle {
return Err(format!("GEN while {:?}", self.state));
}
self.max_new = g.max_new;
self.prompt_tokens = g.ids.len() as u32;
self.generated = 0;
self.reused = 0;
self.prompt_ms = 0.0;
self.decode_ms = 0.0;
self.finish.clear();
self.state = SessionState::Prefilling;
Ok(Vec::new()) // PP lines arrive per chunk via on_prefill_chunk
}
/// Prefill progress (Prefilling only): one `PP` line per chunk.
pub fn on_prefill_chunk(&mut self, read: u32, total: u32, ms: f64) -> Result<Vec<String>, String> {
if self.state != SessionState::Prefilling {
return Err(format!("PP while {:?}", self.state));
}
Ok(vec![pp_line(read, total, ms, None)])
}
/// `ReqStep.prefillComplete` (max_new > 0) or `ReqStep.prewarm` (max_new == 0).
pub fn on_prefill_complete(&mut self, reused: u32, prompt_ms: f64) -> Result<Vec<String>, String> {
if self.state != SessionState::Prefilling {
return Err(format!("prefill-complete while {:?}", self.state));
}
self.reused = reused;
self.prompt_ms = prompt_ms;
let mut out = Vec::new();
if reused > 0 {
out.push(resume_line(reused));
}
if self.max_new == 0 {
// GEN 0 pre-warm: DONE immediately, never enters decode (Theorem 7).
out.extend(self.done("stop", 0.0));
} else {
self.state = SessionState::Decoding;
}
Ok(out)
}
/// Token emission is gated to Decoding (Theorem 9).
pub fn on_token(&mut self, id: u32) -> Result<Vec<String>, String> {
if self.state != SessionState::Decoding {
return Err(format!("T while {:?}", self.state));
}
self.generated += 1;
Ok(vec![token_line(id)])
}
/// `ReqStep.stopPrefill` / `stopDecode`. STOP in Idle/Done is a no-op
/// (Theorem 2); STOP while already Stopping is idempotent.
pub fn on_stop(&mut self) -> Vec<String> {
match self.state {
SessionState::Prefilling | SessionState::Decoding => {
self.state = SessionState::Stopping;
}
_ => {}
}
Vec::new()
}
/// `ReqStep.drain`: Stopping -> Done. The STOP guarantee (Theorem 4):
/// a drained request always ends in exactly one DONE, with no tokens.
pub fn on_drain_complete(&mut self, decode_ms: f64) -> Result<Vec<String>, String> {
if self.state != SessionState::Stopping {
return Err(format!("drain while {:?}", self.state));
}
Ok(self.done("stop", decode_ms))
}
/// `ReqStep.finish`: Decoding -> Done (stop / length / nonfinite).
pub fn on_finish(&mut self, reason: &str, decode_ms: f64) -> Result<Vec<String>, String> {
if self.state != SessionState::Decoding {
return Err(format!("finish while {:?}", self.state));
}
Ok(self.done(reason, decode_ms))
}
/// Failure: emit `ERR`, and a trailing `DONE` if a request was in flight
/// (the consumer swallows it — `swallow_trailing_done`).
pub fn on_error(&mut self, msg: &str) -> Vec<String> {
let mut out = vec![err_line(msg)];
if matches!(self.state, SessionState::Prefilling | SessionState::Decoding | SessionState::Stopping) {
out.extend(self.done("error", self.decode_ms));
}
out
}
/// `ReqStep.nextRequest`: Done -> Idle (clean request boundary, Theorem 8/10).
pub fn on_next(&mut self) -> Result<(), String> {
if self.state != SessionState::Done {
return Err(format!("next while {:?}", self.state));
}
self.state = SessionState::Idle;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use vetta_infer_abi::serve::parse_serve_line;
fn gen_cmd(line: &str) -> ParsedGen {
match parse_serve_line(line, 1000).unwrap() {
vetta_infer_abi::serve::ServeCommand::Gen(g) => g,
_ => panic!("expected GEN"),
}
}
#[test]
fn gen_zero_prewarm_emits_done_without_tokens() {
let mut s = ServeSession::new();
s.on_gen(&gen_cmd("GEN 0 1,2,3")).unwrap();
assert_eq!(s.state(), SessionState::Prefilling);
let out = s.on_prefill_complete(0, 12.0).unwrap();
assert_eq!(s.state(), SessionState::Done);
assert!(out.iter().any(|l| l.starts_with("DONE 0 3")));
assert!(!out.iter().any(|l| l.starts_with("T ")));
assert!(s.on_token(5).is_err()); // never entered decode
}
#[test]
fn normal_flow_prefill_decode_finish() {
let mut s = ServeSession::new();
s.on_gen(&gen_cmd("GEN 3 1,2")).unwrap();
let pp = s.on_prefill_chunk(2, 2, 8.0).unwrap();
assert_eq!(pp, vec!["PP 2 2 8.0"]);
let out = s.on_prefill_complete(1, 8.0).unwrap();
assert_eq!(out, vec!["RESUME 1"]);
assert_eq!(s.state(), SessionState::Decoding);
assert_eq!(s.on_token(10).unwrap(), vec!["T 10"]);
assert_eq!(s.on_token(11).unwrap(), vec!["T 11"]);
let done = s.on_finish("length", 40.0).unwrap();
assert_eq!(done, vec!["DONE 2 2 8.0 40.0 length"]);
assert_eq!(s.state(), SessionState::Done);
assert!(s.on_gen(&gen_cmd("GEN 1 1")).is_err()); // must pass through idle
s.on_next().unwrap();
assert_eq!(s.state(), SessionState::Idle);
}
#[test]
fn stop_mid_decode_drains_to_done_no_more_tokens() {
let mut s = ServeSession::new();
s.on_gen(&gen_cmd("GEN 8 1,2")).unwrap();
s.on_prefill_complete(0, 5.0).unwrap();
s.on_token(10).unwrap();
assert!(s.on_stop().is_empty());
assert_eq!(s.state(), SessionState::Stopping);
assert!(s.on_token(11).is_err()); // no tokens while draining
let done = s.on_drain_complete(20.0).unwrap();
assert_eq!(done, vec!["DONE 1 2 5.0 20.0 stop"]);
assert_eq!(s.state(), SessionState::Done);
}
#[test]
fn stop_in_idle_is_noop_and_stop_prefill_drains() {
let mut s = ServeSession::new();
assert!(s.on_stop().is_empty());
assert_eq!(s.state(), SessionState::Idle);
s.on_gen(&gen_cmd("GEN 4 1,2,3")).unwrap();
s.on_stop();
assert_eq!(s.state(), SessionState::Stopping);
let done = s.on_drain_complete(0.0).unwrap();
assert_eq!(done, vec!["DONE 0 3 0.0 0.0 stop"]);
}
#[test]
fn error_emits_err_and_trailing_done_when_active() {
let mut s = ServeSession::new();
s.on_gen(&gen_cmd("GEN 4 1")).unwrap();
let out = s.on_error("boom");
assert_eq!(out[0], "ERR boom");
assert!(out[1].starts_with("DONE "));
assert_eq!(s.state(), SessionState::Done);
// ERR in idle: no trailing DONE (nothing in flight)
let mut s2 = ServeSession::new();
let out2 = s2.on_error("bad command");
assert_eq!(out2, vec!["ERR bad command"]);
assert_eq!(s2.state(), SessionState::Idle);
}
}
@@ -1,8 +1,8 @@
[package]
name = "vetta-proto"
name = "vetta-infer-kn"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
vetta-core = { path = "../vetta-core" }
vetta-infer-abi = { path = "../vetta-infer-abi" }
+133
View File
@@ -0,0 +1,133 @@
//! Typed control bus — delivery gated on lifecycle state (`proofs/bus_lifecycle.lean`,
//! Theorems 13–14). In-process routing for now; the contract allows out-of-process
//! or Lyra transports later without changing message semantics.
//!
//! The bus carries control-plane messages only. Tensor data never crosses it:
//! the data plane uses UMA handles granted by the `SlabRing` broker.
use vetta_infer_abi::bus::{BusMsg, BusPayload, ServiceId, ServiceState};
use crate::registry::{Registry, RegistryError};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BusError {
Registry(RegistryError),
/// Destination exists but is not in a state that accepts this payload.
NotDeliverable { dst: ServiceId, state: ServiceState },
}
impl std::fmt::Display for BusError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{self:?}")
}
}
impl std::error::Error for BusError {}
impl From<RegistryError> for BusError {
fn from(e: RegistryError) -> Self {
Self::Registry(e)
}
}
#[derive(Debug, Default)]
pub struct ControlBus {
registry: Registry,
delivered: Vec<BusMsg>,
}
impl ControlBus {
pub fn new() -> Self {
Self::default()
}
pub fn registry(&self) -> &Registry {
&self.registry
}
pub fn registry_mut(&mut self) -> &mut Registry {
&mut self.registry
}
/// Routes one message, enforcing the verified delivery rules:
/// - `Stop` is accepted only by a `Running` service and starts its drain;
/// - `StopAck` is accepted only from a `Stopping` service and completes it;
/// - every other payload is deliverable only to `Running`.
pub fn send(&mut self, msg: BusMsg) -> Result<(), BusError> {
let state = self.registry.state(msg.dst)?;
match &msg.payload {
BusPayload::Stop => {
if state != ServiceState::Running {
return Err(BusError::NotDeliverable { dst: msg.dst, state });
}
self.registry.request_stop(msg.dst)?;
}
BusPayload::StopAck => {
if state != ServiceState::Stopping {
return Err(BusError::NotDeliverable { dst: msg.dst, state });
}
self.registry.drain_done(msg.dst)?;
}
_ => {
if state != ServiceState::Running {
return Err(BusError::NotDeliverable { dst: msg.dst, state });
}
}
}
self.delivered.push(msg);
Ok(())
}
/// In-order log of accepted messages (transport seam: a real transport
/// replaces this with per-service queues without changing `send` rules).
pub fn delivered(&self) -> &[BusMsg] {
&self.delivered
}
}
#[cfg(test)]
mod tests {
use super::*;
use vetta_infer_abi::bus::ServiceKind;
fn running_bus() -> (ControlBus, ServiceId) {
let mut bus = ControlBus::new();
let id = bus.registry().prepare();
bus.registry_mut().commit(id, ServiceKind::Cache).unwrap();
bus.registry_mut().start(id).unwrap();
(bus, id)
}
#[test]
fn stop_drains_to_stopped_and_blocks_further_delivery() {
let (mut bus, id) = running_bus();
let hint = BusMsg { src: ServiceId(0), dst: id, payload: BusPayload::DomainHint("lean4".into()) };
bus.send(hint.clone()).unwrap();
let stop = BusMsg { src: ServiceId(0), dst: id, payload: BusPayload::Stop };
bus.send(stop).unwrap();
assert_eq!(bus.registry().state(id).unwrap(), ServiceState::Stopping);
// Draining service accepts no new work
assert!(bus.send(hint).is_err());
// Nor a second STOP
assert!(bus.send(BusMsg { src: ServiceId(0), dst: id, payload: BusPayload::Stop }).is_err());
let ack = BusMsg { src: id, dst: id, payload: BusPayload::StopAck };
bus.send(ack).unwrap();
assert_eq!(bus.registry().state(id).unwrap(), ServiceState::Stopped);
assert!(bus.send(BusMsg { src: id, dst: id, payload: BusPayload::StopAck }).is_err());
assert_eq!(bus.delivered().len(), 3); // hint, stop, ack — rejected msgs never logged
}
#[test]
fn no_delivery_to_registered_or_unknown() {
let mut bus = ControlBus::new();
let id = bus.registry().prepare();
bus.registry_mut().commit(id, ServiceKind::Net).unwrap();
let msg = BusMsg { src: ServiceId(0), dst: id, payload: BusPayload::DomainHint("dante".into()) };
assert!(bus.send(msg.clone()).is_err()); // Registered is not deliverable
assert!(bus.send(BusMsg { src: ServiceId(0), dst: ServiceId(77), payload: BusPayload::Stop }).is_err());
assert!(bus.delivered().is_empty());
}
}
+16
View File
@@ -0,0 +1,16 @@
//! `vetta-infer-kn`: the pure microkernel (docs/ARCHITECTURE.md §2).
//!
//! Three responsibilities, zero model logic:
//! 1. Service registry & lifecycle (two-phase commit, STOP/cancellation drain)
//! — verified in `proofs/bus_lifecycle.lean`.
//! 2. Typed control bus (delivery gated on lifecycle state).
//! 3. Memory/DMA broker (`SlabRing` fence-guarded UMA slot ownership)
//! — verified in `proofs/slab_ring_dma.lean`.
//!
//! The data plane never crosses this crate: services exchange UMA handles,
//! the bus carries only control-plane messages.
pub mod bus;
pub mod registry;
pub mod slab;
pub mod uma;
+168
View File
@@ -0,0 +1,168 @@
//! Service registry & lifecycle — implements `proofs/bus_lifecycle.lean`.
//!
//! Two-phase registration (prepare/commit): a failed resource allocation that
//! never calls `commit` leaves zero ghost entries (Theorem 12). Transitions
//! mirror `SvcStep`: no resurrection, no skipping the drain phase.
use vetta_infer_abi::bus::{ServiceId, ServiceKind, ServiceState};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RegistryError {
UnknownService(ServiceId),
/// `commit` called with an id that is not the currently prepared one.
NotPrepared { expected: ServiceId, got: ServiceId },
InvalidTransition { id: ServiceId, state: ServiceState, op: &'static str },
}
impl std::fmt::Display for RegistryError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{self:?}")
}
}
impl std::error::Error for RegistryError {}
#[derive(Debug, Clone)]
pub struct ServiceEntry {
pub id: ServiceId,
pub kind: ServiceKind,
pub state: ServiceState,
}
/// Committed entries only — a prepared-but-uncommitted entry is unobservable.
#[derive(Debug, Clone, Default)]
pub struct Registry {
entries: Vec<ServiceEntry>,
next_id: u32,
}
impl Registry {
pub fn new() -> Self {
Self::default()
}
/// Phase 1 (pure peek): the candidate id for a new service. No mutation.
pub fn prepare(&self) -> ServiceId {
ServiceId(self.next_id)
}
/// Phase 2: commit the prepared entry. Call ONLY after the service's
/// resources were successfully allocated.
pub fn commit(&mut self, id: ServiceId, kind: ServiceKind) -> Result<(), RegistryError> {
let expected = self.prepare();
if id != expected {
return Err(RegistryError::NotPrepared { expected, got: id });
}
self.entries.push(ServiceEntry { id, kind, state: ServiceState::Registered });
self.next_id += 1;
Ok(())
}
pub fn entries(&self) -> &[ServiceEntry] {
&self.entries
}
pub fn state(&self, id: ServiceId) -> Result<ServiceState, RegistryError> {
self.entries
.iter()
.find(|e| e.id == id)
.map(|e| e.state)
.ok_or(RegistryError::UnknownService(id))
}
fn entry_mut(&mut self, id: ServiceId) -> Result<&mut ServiceEntry, RegistryError> {
self.entries
.iter_mut()
.find(|e| e.id == id)
.ok_or(RegistryError::UnknownService(id))
}
fn transition(
&mut self,
id: ServiceId,
from: ServiceState,
to: ServiceState,
op: &'static str,
) -> Result<(), RegistryError> {
let e = self.entry_mut(id)?;
if e.state != from {
return Err(RegistryError::InvalidTransition { id, state: e.state, op });
}
e.state = to;
Ok(())
}
/// `SvcStep.start`: Registered -> Running.
pub fn start(&mut self, id: ServiceId) -> Result<(), RegistryError> {
self.transition(id, ServiceState::Registered, ServiceState::Running, "start")
}
/// `SvcStep.stop`: Running -> Stopping (drain begins, no new work).
pub fn request_stop(&mut self, id: ServiceId) -> Result<(), RegistryError> {
self.transition(id, ServiceState::Running, ServiceState::Stopping, "request_stop")
}
/// `SvcStep.drain`: Stopping -> Stopped (drain ack observed).
pub fn drain_done(&mut self, id: ServiceId) -> Result<(), RegistryError> {
self.transition(id, ServiceState::Stopping, ServiceState::Stopped, "drain_done")
}
/// `SvcStep.cancelReady`: Registered -> Stopped (cancelled before start).
pub fn cancel_ready(&mut self, id: ServiceId) -> Result<(), RegistryError> {
self.transition(id, ServiceState::Registered, ServiceState::Stopped, "cancel_ready")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn two_phase_commit_no_ghost_entries() {
let mut r = Registry::new();
let id = r.prepare();
assert!(r.entries().is_empty()); // failed alloc before commit: zero ghosts
assert_eq!(r.prepare(), id); // prepare is pure
assert!(r.commit(ServiceId(99), ServiceKind::Cache).is_err()); // not prepared
assert!(r.entries().is_empty());
r.commit(id, ServiceKind::Cache).unwrap();
assert_eq!(r.entries().len(), 1);
assert_eq!(r.state(id).unwrap(), ServiceState::Registered);
assert_eq!(r.prepare(), ServiceId(1)); // fresh id, never collides
}
#[test]
fn lifecycle_happy_path_and_cancellation() {
let mut r = Registry::new();
let a = r.prepare();
r.commit(a, ServiceKind::Runtime).unwrap();
r.start(a).unwrap();
r.request_stop(a).unwrap();
assert_eq!(r.state(a).unwrap(), ServiceState::Stopping);
r.drain_done(a).unwrap();
assert_eq!(r.state(a).unwrap(), ServiceState::Stopped);
let b = r.prepare();
r.commit(b, ServiceKind::Lab).unwrap();
r.cancel_ready(b).unwrap(); // cancelled before ever running
assert_eq!(r.state(b).unwrap(), ServiceState::Stopped);
}
#[test]
fn illegal_transitions_rejected() {
let mut r = Registry::new();
let id = r.prepare();
r.commit(id, ServiceKind::Spec).unwrap();
assert!(r.request_stop(id).is_err()); // not running yet
assert!(r.drain_done(id).is_err()); // not stopping
r.start(id).unwrap();
assert!(r.start(id).is_err()); // already running
assert!(r.drain_done(id).is_err()); // must pass through Stopping
r.request_stop(id).unwrap();
assert!(r.start(id).is_err()); // no resurrection while draining
r.drain_done(id).unwrap();
assert!(r.start(id).is_err()); // stopped is terminal
assert!(r.request_stop(id).is_err());
assert!(r.state(ServiceId(42)).is_err()); // unknown service
}
}
@@ -160,4 +160,4 @@ mod tests {
ring.complete_gpu(s0, 42).unwrap();
assert_eq!(ring.state(s0).unwrap(), SlotState::Free);
}
}
}
@@ -1,23 +1,12 @@
//! `vetta-hip`: thin HIP microkernel boundary & fence-guarded zero-copy UMA ring buffers.
//! UMA slab pool — the broker's buffer ownership surface.
//!
//! All unsafe GPU/DMA lifetime invariants are mediated by `vetta_core::slab::SlabRing`
//! (formally verified in `proofs/slab_ring_dma.lean`).
//! In M2 this wraps `mmap` + `hipHostRegisterMapped` + `io_uring` fixed buffers;
//! today it runs on CPU aligned buffers with the exact same `SlabRing` state
//! machine verified in `proofs/slab_ring_dma.lean`. The HIP FFI side lands in `rt`.
use vetta_core::slab::{SlabError, SlabRing, SlotState};
#[derive(Debug, Clone)]
pub struct DeviceInfo {
pub name: String,
pub gcn_arch: String,
pub cu_count: u32,
pub wave_size: u32,
pub total_vram_bytes: u64,
pub is_uma: bool,
}
use crate::slab::{SlabError, SlabRing, SlotState};
/// Page-aligned host/UMA ring backing `SlabRing` transitions.
/// In Milestone 2 this wraps `mmap` + `hipHostRegisterMapped` + `io_uring` fixed buffers;
/// in Milestone 0/tests it runs directly on CPU aligned buffers with the exact same state machine.
pub struct UmaSlabPool {
ring: SlabRing,
buffers: Vec<Vec<u8>>,
@@ -102,4 +91,4 @@ mod tests {
pool.abort_io(s1, req1).unwrap();
assert_eq!(pool.slot_state(s1).unwrap(), SlotState::Free);
}
}
}
@@ -1,8 +1,8 @@
[package]
name = "vetta-io"
name = "vetta-infer-lab"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
vetta-core = { path = "../vetta-core" }
vetta-infer-rt = { path = "../vetta-infer-rt" }
+20
View File
@@ -0,0 +1,20 @@
//! `vetta-infer-lab`: laboratory runtime (docs/ARCHITECTURE.md §5).
//!
//! Executes the *identical* `CompiledPlan` as `rt` — the executor core is
//! shared by construction, not duplicated. `lab` only interleaves the
//! observation points declared in `probe.vplan`; `rt` runs with an empty
//! probe table (zero probes, zero debug branching on the hot path).
//!
//! The probe-hook table and the shared plan executor land with M1; this crate
//! already pins the structural guarantee: lab depends on rt's executor.
#[cfg(test)]
mod tests {
#[test]
fn shares_executor_core_with_rt() {
// Structural guarantee: lab sees the exact same prefix/state machinery
// as rt (no forked executor).
let st = vetta_infer_rt::prefix::PrefixState::target_only(4);
assert_eq!(st.len(), 4);
}
}
@@ -1,8 +1,8 @@
[package]
name = "vetta-hip"
name = "vetta-infer-ld"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
vetta-core = { path = "../vetta-core" }
vetta-infer-abi = { path = "../vetta-infer-abi" }
+421
View File
@@ -0,0 +1,421 @@
//! `vetta-infer-ld`: loader & compiler (docs/ARCHITECTURE.md §3, §9).
//!
//! Checked `.safetensors` reader (index.json + directory fallback + `pread` +
//! overflow-safe slice checks) and the write-once `VTC1` atomic cache writer
//! (`.tmp.<pid>` + `fsync` + `rename`). The dual-step ModelImporter → IR →
//! BackendPacker pipeline lands here with M1; `cc` owns the `O_RDONLY` reload.
//!
//! Eliminates audit-05 F-02 (shard bounds, u64 slice overflow, missing
//! index.json) and F-05 (PID-isolated atomic commit) by construction.
use std::collections::{BTreeSet, HashMap};
use std::fs::{self, File, OpenOptions};
use std::os::unix::fs::FileExt;
use std::path::{Path, PathBuf};
use vetta_infer_abi::json::parse_json;
use vetta_infer_abi::vtc1::{
align_up, serialize_meta, CacheRecord, CACHE_ALIGN, CACHE_MAGIC, CACHE_VERSION, HEADER_SIZE,
};
// ============================================================================
// 1. Checked Safetensors Archive Reader (`pread`, `index.json`, strict bounds)
// ============================================================================
#[derive(Debug, Clone)]
pub struct TensorInfo {
pub shard_idx: usize,
pub dtype: String,
pub shape: Vec<u64>,
pub begin: u64,
pub end: u64,
}
impl TensorInfo {
pub fn byte_len(&self) -> u64 {
self.end - self.begin
}
}
pub struct SafetensorsShard {
pub path: PathBuf,
pub file: File,
pub file_size: u64,
pub data_start: u64,
}
pub struct SafetensorsArchive {
pub dir: PathBuf,
pub shards: Vec<SafetensorsShard>,
pub tensors: HashMap<String, TensorInfo>,
}
const MAX_HEADER_BYTES: u64 = 128 * 1024 * 1024;
impl SafetensorsArchive {
pub fn open(dir: impl AsRef<Path>) -> Result<Self, String> {
let dir = dir.as_ref().to_path_buf();
let shard_paths = discover_shards(&dir)?;
if shard_paths.is_empty() {
return Err(format!("no .safetensors shards found in {}", dir.display()));
}
let mut shards = Vec::with_capacity(shard_paths.len());
let mut tensors = HashMap::new();
for (shard_idx, path) in shard_paths.into_iter().enumerate() {
let file = OpenOptions::new()
.read(true)
.open(&path)
.map_err(|e| format!("open {}: {e}", path.display()))?;
let file_size = file
.metadata()
.map_err(|e| format!("stat {}: {e}", path.display()))?
.len();
if file_size < 8 {
return Err(format!("truncated safetensors file {}", path.display()));
}
let mut len_buf = [0u8; 8];
file.read_exact_at(&mut len_buf, 0)
.map_err(|e| format!("read header len {}: {e}", path.display()))?;
let hlen = u64::from_le_bytes(len_buf);
let data_start = 8u64
.checked_add(hlen)
.ok_or_else(|| format!("header length overflow in {}", path.display()))?;
if hlen == 0 || hlen > MAX_HEADER_BYTES || data_start > file_size {
return Err(format!(
"invalid header length {hlen} (file_size={file_size}) in {}",
path.display()
));
}
let mut hbytes = vec![0u8; hlen as usize];
file.read_exact_at(&mut hbytes, 8)
.map_err(|e| format!("read header {}: {e}", path.display()))?;
let hstr = std::str::from_utf8(&hbytes)
.map_err(|_| format!("non-UTF-8 header in {}", path.display()))?;
let root = parse_json(hstr)?;
let obj = root
.as_obj()
.ok_or_else(|| format!("header root is not JSON object in {}", path.display()))?;
let avail = file_size - data_start;
for (name, val) in obj {
if name == "__metadata__" {
continue;
}
let to = val
.as_obj()
.ok_or_else(|| format!("tensor '{name}' entry is not object"))?;
let dtype = to
.get("dtype")
.and_then(|v| v.as_str())
.ok_or_else(|| format!("tensor '{name}' missing dtype"))?
.to_string();
let shape_arr = to
.get("shape")
.and_then(|v| v.as_arr())
.ok_or_else(|| format!("tensor '{name}' missing shape"))?;
let mut shape = Vec::with_capacity(shape_arr.len());
for d in shape_arr {
shape.push(d.as_u64().ok_or_else(|| format!("tensor '{name}' bad dim"))?);
}
let offs = to
.get("data_offsets")
.and_then(|v| v.as_arr())
.ok_or_else(|| format!("tensor '{name}' missing data_offsets"))?;
if offs.len() != 2 {
return Err(format!("tensor '{name}' data_offsets len != 2"));
}
let begin = offs[0].as_u64().ok_or_else(|| format!("tensor '{name}' bad begin"))?;
let end = offs[1].as_u64().ok_or_else(|| format!("tensor '{name}' bad end"))?;
if end < begin || end > avail {
return Err(format!(
"tensor '{name}' out of shard bounds [{begin}, {end}) vs avail={avail} in {}",
path.display()
));
}
if tensors.contains_key(name) {
return Err(format!("duplicate tensor '{name}' across shards"));
}
tensors.insert(
name.clone(),
TensorInfo {
shard_idx,
dtype,
shape,
begin,
end,
},
);
}
shards.push(SafetensorsShard {
path,
file,
file_size,
data_start,
});
}
Ok(Self { dir, shards, tensors })
}
pub fn total_tensor_bytes(&self) -> u64 {
self.tensors.values().map(|t| t.byte_len()).sum()
}
pub fn read_slice(&self, name: &str, rel_off: u64, dst: &mut [u8]) -> Result<(), String> {
let info = self
.tensors
.get(name)
.ok_or_else(|| format!("tensor not found: {name}"))?;
let total = info.byte_len();
let req = dst.len() as u64;
if rel_off > total || req > total - rel_off {
return Err(format!(
"slice OOB for '{name}': rel_off={rel_off} len={req} total={total}"
));
}
let sh = &self.shards[info.shard_idx];
let file_off = sh
.data_start
.checked_add(info.begin)
.and_then(|v| v.checked_add(rel_off))
.ok_or_else(|| format!("file offset overflow for '{name}'"))?;
sh.file
.read_exact_at(dst, file_off)
.map_err(|e| format!("pread '{}' at {file_off}: {e}", sh.path.display()))
}
}
fn discover_shards(dir: &Path) -> Result<Vec<PathBuf>, String> {
let idx_path = dir.join("model.safetensors.index.json");
if idx_path.is_file() {
let raw = fs::read_to_string(&idx_path)
.map_err(|e| format!("read {}: {e}", idx_path.display()))?;
let root = parse_json(&raw)?;
let wm = root
.as_obj()
.and_then(|o| o.get("weight_map"))
.and_then(|v| v.as_obj())
.ok_or_else(|| format!("missing weight_map in {}", idx_path.display()))?;
let mut uniq = BTreeSet::new();
for v in wm.values() {
if let Some(fname) = v.as_str() {
if !fname.is_empty() {
uniq.insert(dir.join(fname));
}
}
}
return Ok(uniq.into_iter().collect());
}
let entries = fs::read_dir(dir).map_err(|e| format!("list {}: {e}", dir.display()))?;
let mut out = Vec::new();
for entry in entries {
let e = entry.map_err(|e| format!("dir entry {}: {e}", dir.display()))?;
let p = e.path();
if p.is_file() && p.extension().and_then(|x| x.to_str()) == Some("safetensors") {
out.push(p);
}
}
out.sort();
Ok(out)
}
// ============================================================================
// 2. Write-Once `VTC1` Atomic Cache Writer (`.tmp.<pid>` + fsync + rename)
// ============================================================================
pub struct DiskCacheWriter {
final_path: PathBuf,
tmp_path: PathBuf,
file: Option<File>,
fingerprint: u64,
cursor: u64,
records: Vec<CacheRecord>,
}
impl DiskCacheWriter {
pub fn begin(final_path: impl AsRef<Path>, fingerprint: u64) -> Result<Self, String> {
let final_path = final_path.as_ref().to_path_buf();
if let Some(parent) = final_path.parent() {
fs::create_dir_all(parent).map_err(|e| format!("mkdir {}: {e}", parent.display()))?;
}
let pid = std::process::id();
let tmp_path = PathBuf::from(format!("{}.tmp.{pid}", final_path.display()));
let file = OpenOptions::new()
.create(true)
.truncate(true)
.read(true)
.write(true)
.open(&tmp_path)
.map_err(|e| format!("create {}: {e}", tmp_path.display()))?;
Ok(Self {
final_path,
tmp_path,
file: Some(file),
fingerprint,
cursor: CACHE_ALIGN,
records: Vec::new(),
})
}
pub fn write_record(&mut self, mut rec: CacheRecord, payload: &[u8]) -> Result<u64, String> {
let f = self.file.as_ref().ok_or_else(|| "writer closed".to_string())?;
rec.data_offset = align_up(self.cursor, CACHE_ALIGN)?;
rec.data_bytes = payload.len() as u64;
self.cursor = align_up(
rec.data_offset
.checked_add(rec.data_bytes)
.ok_or_else(|| "cache offset overflow".to_string())?,
CACHE_ALIGN,
)?;
f.write_all_at(payload, rec.data_offset)
.map_err(|e| format!("write payload: {e}"))?;
let off = rec.data_offset;
self.records.push(rec);
Ok(off)
}
pub fn commit(mut self) -> Result<PathBuf, String> {
let f = self.file.take().ok_or_else(|| "writer closed".to_string())?;
let meta = serialize_meta(&self.records);
let meta_off = align_up(self.cursor, CACHE_ALIGN)?;
f.write_all_at(&meta, meta_off)
.map_err(|e| format!("write meta: {e}"))?;
let total_bytes = meta_off
.checked_add(meta.len() as u64)
.ok_or_else(|| "total_bytes overflow".to_string())?;
let mut hdr = [0u8; HEADER_SIZE];
hdr[0..8].copy_from_slice(&CACHE_MAGIC);
hdr[8..12].copy_from_slice(&CACHE_VERSION.to_le_bytes());
hdr[12..16].copy_from_slice(&(self.records.len() as u32).to_le_bytes());
hdr[16..24].copy_from_slice(&self.fingerprint.to_le_bytes());
hdr[24..32].copy_from_slice(&meta_off.to_le_bytes());
hdr[32..40].copy_from_slice(&(meta.len() as u64).to_le_bytes());
hdr[40..48].copy_from_slice(&total_bytes.to_le_bytes());
f.write_all_at(&hdr, 0).map_err(|e| format!("write hdr: {e}"))?;
f.sync_all().map_err(|e| format!("fsync cache: {e}"))?;
drop(f);
fs::rename(&self.tmp_path, &self.final_path)
.map_err(|e| format!("rename cache: {e}"))?;
Ok(self.final_path.clone())
}
}
impl Drop for DiskCacheWriter {
fn drop(&mut self) {
if self.file.take().is_some() {
let _ = fs::remove_file(&self.tmp_path);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
fn write_mini_st(path: &Path, name: &str, data: &[u8], truncate: bool, invert: bool) {
let (b, e) = if invert { (data.len(), 0) } else { (0, data.len()) };
let hdr = format!(
"{{\"{name}\":{{\"dtype\":\"F32\",\"shape\":[{}],\"data_offsets\":[{b},{e}]}}}}",
data.len() / 4
);
let mut f = File::create(path).unwrap();
f.write_all(&(hdr.len() as u64).to_le_bytes()).unwrap();
f.write_all(hdr.as_bytes()).unwrap();
let take = if truncate && !data.is_empty() { data.len() - 1 } else { data.len() };
f.write_all(&data[..take]).unwrap();
}
#[test]
fn safetensors_bounds_overflow_and_index_json() {
let root = std::env::temp_dir().join(format!("vetta_ld_test_{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).unwrap();
// Non-existent dir fails cleanly
assert!(SafetensorsArchive::open(root.join("missing")).is_err());
// Truncated shard rejected
let d_trunc = root.join("trunc");
fs::create_dir_all(&d_trunc).unwrap();
write_mini_st(&d_trunc.join("a.safetensors"), "w", &[1, 2, 3, 4, 5, 6, 7, 8], true, false);
assert!(SafetensorsArchive::open(&d_trunc).is_err());
// Inverted offsets rejected
let d_inv = root.join("inv");
fs::create_dir_all(&d_inv).unwrap();
write_mini_st(&d_inv.join("a.safetensors"), "w", &[1, 2, 3, 4], false, true);
assert!(SafetensorsArchive::open(&d_inv).is_err());
// Valid + index.json ignoring stray backup + u64 overflow slice check
let d_ok = root.join("ok");
fs::create_dir_all(&d_ok).unwrap();
let bytes = [10u8, 20, 30, 40, 50, 60, 70, 80];
write_mini_st(&d_ok.join("s1.safetensors"), "w", &bytes, false, false);
write_mini_st(&d_ok.join("backup.safetensors"), "w", &bytes, false, false);
fs::write(
d_ok.join("model.safetensors.index.json"),
r#"{"weight_map":{"w":"s1.safetensors"}}"#,
)
.unwrap();
let ar = SafetensorsArchive::open(&d_ok).unwrap();
assert_eq!(ar.shards.len(), 1);
let mut got = [0u8; 4];
ar.read_slice("w", 4, &mut got).unwrap();
assert_eq!(got, [50, 60, 70, 80]);
assert!(ar.read_slice("w", u64::MAX, &mut got).is_err());
let _ = fs::remove_dir_all(&root);
}
#[test]
fn writer_atomic_commit_and_drop_cleanup() {
let p = std::env::temp_dir().join(format!("vetta_ld_cache_{}.bin", std::process::id()));
let _ = fs::remove_file(&p);
let fp = 0x1234_5678_ABCD_EF01u64;
let payload = vec![0x5Au8; 8192];
let mut wr = 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();
let committed = wr.commit().unwrap();
assert_eq!(committed, p);
assert!(p.is_file());
assert!(!PathBuf::from(format!("{}.tmp.{}", p.display(), std::process::id())).exists());
// An abandoned writer cleans up its .tmp (no ghost final file)
let p2 = std::env::temp_dir().join(format!("vetta_ld_cache2_{}.bin", std::process::id()));
{
let mut wr2 = DiskCacheWriter::begin(&p2, fp).unwrap();
wr2.write_record(
CacheRecord {
kind: 1, i0: 0, i1: 0, i2: 0, flags: 0, u0: 0, u1: 0,
data_offset: 0, data_bytes: 0, name: "x".into(),
},
&payload,
).unwrap();
}
assert!(!p2.exists());
let _ = fs::remove_file(&p);
}
}
@@ -1,7 +1,7 @@
[package]
name = "vetta-core"
name = "vetta-infer-nt"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
[dependencies]
+32
View File
@@ -0,0 +1,32 @@
//! `vetta-infer-nt`: LAN bridge to Lyra (docs/ARCHITECTURE.md §2, "Lyra control/co-processor split").
//!
//! Compact RPC messages for Sogliola <-> Lyra (`< 1 KB/step` on 2.5 Gbps Ethernet):
//! remote drafting (same tokenizer as the target), domain routing hints, and
//! lightweight Vision/RAG offload. The TCP transport lands with M3; the message
//! contract is fixed here so both ends can be built and tested independently.
/// Compact LAN RPC messages for Sogliola <-> Lyra (`< 1 KB/step`, `~0.3 ms` RTT).
#[derive(Debug, Clone, PartialEq)]
pub enum LyraRpc {
DraftRequest { session_id: u64, accepted_tail: Vec<i32>, max_k: u8 },
DraftResponse { session_id: u64, proposed: Vec<i32>, probs: Vec<f32> },
DomainHint { session_id: u64, domain: String, confidence: f32 },
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn draft_roundtrip_shapes() {
let req = LyraRpc::DraftRequest { session_id: 1, accepted_tail: vec![10, 20], max_k: 8 };
let resp = LyraRpc::DraftResponse {
session_id: 1,
proposed: vec![30, 40, 50],
probs: vec![0.6, 0.3, 0.1],
};
let LyraRpc::DraftResponse { proposed, probs, .. } = resp else { panic!("shape") };
assert_eq!(proposed.len(), probs.len()); // lossless Leviathan needs one q(x) per proposal
assert!(matches!(req, LyraRpc::DraftRequest { max_k: 8, .. }));
}
}
+8
View File
@@ -0,0 +1,8 @@
[package]
name = "vetta-infer-rt"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
vetta-infer-abi = { path = "../vetta-infer-abi" }
+8
View File
@@ -0,0 +1,8 @@
//! `vetta-infer-rt`: operational runtime (docs/ARCHITECTURE.md §2, §5).
//!
//! Executes the boot-lowered `CompiledPlan` on the HIP backend at full speed,
//! zero probes on the hot path. `lab` shares this executor core. Today it
//! hosts the hybrid prefix/checkpoint state; the HIP FFI and plan executor
//! land with M1.
pub mod prefix;
@@ -171,4 +171,4 @@ mod tests {
pool.invalidate_above(2);
assert!(pool.entries().is_empty());
}
}
}
+7
View File
@@ -0,0 +1,7 @@
[package]
name = "vetta-infer-sp"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
+378
View File
@@ -0,0 +1,378 @@
//! Throughput-aware Adaptive-K controller — FAITHFUL port of the measured
//! `strata-clover/engine/src/clover/clover_policy.h` `AdaptiveKController`
//! (the policy behind 21.0 tok/s prose / 42.1 tok/s code, 100% exact vs AR).
//!
//! Ported elements (the M0 sketch lacked all of them):
//! - cooldowns: `ar_cooldown` (8), `k8_cooldown` (12), `k16_cooldown` (12);
//! - `just_probed` one-shot sensitivity after an AR->K=4 probe;
//! - per-band throughput guards (EMA ms/tok ratios 1.06 / 1.06 / 1.05);
//! - promotion to K=16 only on a full 8/8 streak x2 AND `k16_cooldown == 0`
//! (the prose trap fix, commit `f2a79ada4`);
//! - EMA smoothing 0.65/0.35 over K buckets {1, 4, 8, 16}.
//!
//! Lossless exactness vs AR for every K is inherited from the verification
//! machine (see `strata-clover/proofs/clover_gdn_ckpt.lean`,
//! `adaptive_spec_exact_vs_ar`); this controller only chooses K.
/// Mirrors `clamp_adaptive_k`.
fn clamp_k(k: usize, k_max: usize) -> usize {
if k_max <= 1 {
return 1;
}
k.max(1).min(k_max)
}
#[derive(Debug, Clone)]
pub struct AdaptiveKController {
k_max: usize,
cur_k: usize,
/// Plain AR (K=1) steps remaining before the next K=4 probe.
ar_cooldown: u32,
/// K=8 steps remaining before re-trying K=16 after throughput demotion.
k16_cooldown: u32,
/// K=4 steps remaining before re-trying K=8 after throughput demotion.
k8_cooldown: u32,
low_streak: u32,
high_streak: u32,
just_probed: bool,
/// Empirical ms/tok EMA for K buckets {1, 4, 8, 16}.
ema_mpt: [f64; 4],
}
impl AdaptiveKController {
pub fn new(k_max: usize) -> Self {
let km = k_max.max(1);
Self {
k_max: km,
cur_k: clamp_k(if km >= 8 { 8 } else if km >= 4 { 4 } else { 1 }, km),
ar_cooldown: 0,
k16_cooldown: 0,
k8_cooldown: 0,
low_streak: 0,
high_streak: 0,
just_probed: false,
ema_mpt: [0.0; 4],
}
}
pub fn reset(&mut self, k_max: usize) {
*self = Self::new(k_max);
}
pub fn k_max(&self) -> usize {
self.k_max
}
pub fn cur_k(&self) -> usize {
self.cur_k
}
fn bucket(k: usize) -> usize {
if k <= 1 {
0
} else if k <= 4 {
1
} else if k <= 8 {
2
} else {
3
}
}
/// Mirrors `next_k(rem_tokens, ctx_room)`.
pub fn next_k(&self, rem_tokens: usize, ctx_room: usize) -> usize {
let cap = self.k_max.min(rem_tokens.min(ctx_room));
if cap <= 1 {
return 1;
}
if self.ar_cooldown > 0 {
return 1;
}
clamp_k(self.cur_k, cap)
}
/// Mirrors `observe(used_k, accepted_tokens, step_ms)` branch by branch.
pub fn observe(&mut self, used_k: usize, accepted_tokens: usize, step_ms: f64) {
if self.k_max <= 1 {
self.cur_k = 1;
return;
}
let acc = accepted_tokens.max(1);
let b = Self::bucket(used_k);
if step_ms > 0.0 {
let mpt = step_ms / acc as f64;
self.ema_mpt[b] = if self.ema_mpt[b] <= 0.0 {
mpt
} else {
0.65 * self.ema_mpt[b] + 0.35 * mpt
};
}
if used_k <= 1 {
if self.ar_cooldown > 0 {
self.ar_cooldown -= 1;
}
if self.ar_cooldown == 0 {
self.cur_k = clamp_k(4, self.k_max);
self.just_probed = true;
self.low_streak = 0;
self.high_streak = 0;
}
return;
}
if used_k <= 4 {
if self.k8_cooldown > 0 {
self.k8_cooldown -= 1;
}
// Throughput guard: K=4 measurably slower than observed AR -> AR cooldown.
if self.ema_mpt[1] > 0.0
&& self.ema_mpt[0] > 0.0
&& self.ema_mpt[1] > self.ema_mpt[0] * 1.06
{
self.low_streak += 1;
self.high_streak = 0;
if self.just_probed || self.low_streak >= 2 {
self.cur_k = 1;
self.ar_cooldown = 8;
self.low_streak = 0;
self.just_probed = false;
return;
}
}
if accepted_tokens >= 3 {
if self.k8_cooldown == 0 {
self.cur_k = clamp_k(8, self.k_max);
self.low_streak = 0;
self.high_streak = 0;
self.just_probed = false;
} else {
self.low_streak = 0;
self.just_probed = false;
}
} else if accepted_tokens <= 2 {
self.low_streak += 1;
self.high_streak = 0;
if self.just_probed || self.low_streak >= 2 {
self.cur_k = 1;
self.ar_cooldown = 8;
self.low_streak = 0;
self.just_probed = false;
}
} else {
self.just_probed = false;
}
return;
}
if used_k <= 8 {
self.just_probed = false;
if self.k16_cooldown > 0 {
self.k16_cooldown -= 1;
}
// Throughput guard: K=8 measurably slower than observed K=4 -> step back.
if self.ema_mpt[2] > 0.0
&& self.ema_mpt[1] > 0.0
&& self.ema_mpt[2] > self.ema_mpt[1] * 1.06
{
self.low_streak += 1;
self.high_streak = 0;
if self.low_streak >= 2 {
self.cur_k = clamp_k(4, self.k_max);
self.k8_cooldown = 12;
self.low_streak = 0;
return;
}
}
// Promote to K=16 only on full 8/8 acceptance streak (prose trap fix).
if accepted_tokens >= 8 {
self.high_streak += 1;
self.low_streak = 0;
if self.high_streak >= 2 && self.k_max >= 16 && self.k16_cooldown == 0 {
self.cur_k = clamp_k(16, self.k_max);
self.high_streak = 0;
}
} else if accepted_tokens <= 3 {
self.low_streak += 1;
self.high_streak = 0;
if self.low_streak >= 2 {
self.cur_k = clamp_k(4, self.k_max);
self.low_streak = 0;
}
} else {
self.high_streak = 0;
self.low_streak = 0;
}
return;
}
// used_k > 8 (e.g. 16): require >= 10 accepted AND competitive ms/tok to stay.
self.just_probed = false;
if self.ema_mpt[3] > 0.0
&& self.ema_mpt[2] > 0.0
&& self.ema_mpt[3] > self.ema_mpt[2] * 1.05
{
self.cur_k = clamp_k(8, self.k_max);
self.k16_cooldown = 12;
self.low_streak = 0;
self.high_streak = 0;
return;
}
if accepted_tokens <= 9 {
self.low_streak += 1;
self.high_streak = 0;
if self.low_streak >= 2 {
self.cur_k = clamp_k(8, self.k_max);
self.k16_cooldown = 12;
self.low_streak = 0;
}
} else {
self.low_streak = 0;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
// Scenario parity tests: expected values derived by hand from the C++
// reference (clover_policy.h), branch by branch.
#[test]
fn initial_state_and_caps() {
let c = AdaptiveKController::new(16);
assert_eq!(c.cur_k(), 8);
assert_eq!(c.next_k(100, 100), 8);
assert_eq!(c.next_k(3, 100), 3); // rem_tokens cap
assert_eq!(c.next_k(100, 1), 1); // ctx_room cap <= 1
let c4 = AdaptiveKController::new(4);
assert_eq!(c4.cur_k(), 4);
let c1 = AdaptiveKController::new(1);
assert_eq!(c1.cur_k(), 1);
assert_eq!(c1.next_k(100, 100), 1);
}
#[test]
fn k_max_one_forces_ar() {
let mut c = AdaptiveKController::new(1);
c.observe(16, 16, 10.0);
assert_eq!(c.cur_k(), 1);
assert_eq!(c.next_k(100, 100), 1);
}
#[test]
fn promotion_requires_two_full_streaks_and_no_cooldown() {
let mut c = AdaptiveKController::new(16);
c.observe(8, 8, 80.0); // high_streak = 1, not yet 16
assert_eq!(c.cur_k(), 8);
c.observe(8, 8, 80.0); // high_streak = 2 -> promote
assert_eq!(c.cur_k(), 16);
assert_eq!(c.next_k(100, 100), 16);
}
#[test]
fn prose_trap_k16_slower_than_k8_demotes_with_cooldown() {
let mut c = AdaptiveKController::new(16);
// Establish K=8 at 10 ms/tok, then promote to 16.
c.observe(8, 8, 80.0);
c.observe(8, 8, 80.0);
assert_eq!(c.cur_k(), 16);
// K=16 step: 16 accepted in 200 ms = 12.5 ms/tok > 10 * 1.05 -> demote.
c.observe(16, 16, 200.0);
assert_eq!(c.cur_k(), 8);
assert_eq!(c.next_k(100, 100), 8);
// During the 12-step cooldown, full 8/8 streaks must NOT re-promote.
for _ in 0..11 {
c.observe(8, 8, 80.0);
assert_eq!(c.cur_k(), 8, "promotion must wait out k16_cooldown");
}
// 12th observe drains the cooldown; the accumulated full-acceptance
// streak (never reset while cooling down) immediately re-promotes.
c.observe(8, 8, 80.0);
assert_eq!(c.cur_k(), 16);
}
#[test]
fn k16_low_acceptance_demotes_after_two_strikes() {
let mut c = AdaptiveKController::new(16);
c.observe(8, 8, 80.0);
c.observe(8, 8, 80.0); // now K=16
c.observe(16, 5, 0.0); // low_streak = 1, stays 16
assert_eq!(c.cur_k(), 16);
c.observe(16, 5, 0.0); // low_streak = 2 -> demote + cooldown
assert_eq!(c.cur_k(), 8);
}
#[test]
fn ar_probe_cycle_and_one_shot_probe_sensitivity() {
let mut c = AdaptiveKController::new(16);
// Two weak K=4 steps -> drop to AR with cooldown 8.
c.observe(4, 1, 0.0);
c.observe(4, 1, 0.0);
assert_eq!(c.cur_k(), 1);
assert_eq!(c.next_k(100, 100), 1); // ar_cooldown forces K=1
// Drain the 8 AR steps; the 8th re-probes K=4 with just_probed.
for _ in 0..8 {
c.observe(1, 1, 0.0);
}
assert_eq!(c.cur_k(), 4);
// A single weak probe step immediately drops back (just_probed).
c.observe(4, 1, 0.0);
assert_eq!(c.cur_k(), 1);
assert_eq!(c.next_k(100, 100), 1);
}
#[test]
fn k4_promotes_to_k8_on_three_accepted() {
let mut c = AdaptiveKController::new(16);
c.observe(4, 3, 0.0);
assert_eq!(c.cur_k(), 8);
}
#[test]
fn k8_throughput_guard_steps_back_to_k4_with_cooldown() {
let mut c = AdaptiveKController::new(16);
// K=4 at 5 ms/tok promotes to K=8.
c.observe(4, 4, 20.0);
assert_eq!(c.cur_k(), 8);
// One weak K=8 step (no timing): low_streak = 1, survives (no demotion yet).
c.observe(8, 3, 0.0);
assert_eq!(c.cur_k(), 8);
// K=8 at 10 ms/tok (> 5 * 1.06): guard sees low_streak 1 -> 2 -> demote + cooldown.
c.observe(8, 8, 80.0);
assert_eq!(c.cur_k(), 4);
// During k8_cooldown, good K=4 acceptance must not re-promote to 8.
for _ in 0..11 {
c.observe(4, 4, 20.0);
assert_eq!(c.cur_k(), 4);
}
c.observe(4, 4, 20.0); // cooldown drained, accepted >= 3 -> promote
assert_eq!(c.cur_k(), 8);
}
#[test]
fn k4_throughput_guard_vs_ar_one_shot_probe() {
let mut c = AdaptiveKController::new(16);
// AR at 5 ms/tok; cooldown == 0 re-probes K=4 with just_probed.
c.observe(1, 1, 5.0);
assert_eq!(c.cur_k(), 4);
// K=4 at 10 ms/tok (> 5 * 1.06): a single weak probe step drops back
// immediately (just_probed), with the 8-step AR cooldown.
c.observe(4, 4, 40.0);
assert_eq!(c.cur_k(), 1);
assert_eq!(c.next_k(100, 100), 1);
}
#[test]
fn reset_restores_initial_state() {
let mut c = AdaptiveKController::new(16);
c.observe(8, 8, 80.0);
c.observe(8, 8, 80.0);
c.observe(16, 5, 0.0);
c.observe(16, 5, 0.0);
c.reset(16);
assert_eq!(c.cur_k(), 8);
assert_eq!(c.next_k(100, 100), 8);
}
}
+8
View File
@@ -0,0 +1,8 @@
//! `vetta-infer-sp`: speculative coordinator (docs/ARCHITECTURE.md §2).
//!
//! Lossless verification (Leviathan, in `abi`), throughput-aware Adaptive-K,
//! local MTP/Block-Diffusion drafting or remote via `nt`. Every policy here is
//! a faithful port of the measured strata reference, with scenario parity
//! tests — never a simplified re-interpretation.
pub mod adaptive_k;
+8
View File
@@ -0,0 +1,8 @@
[package]
name = "vetta-infer-tm"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
vetta-infer-abi = { path = "../vetta-infer-abi" }
@@ -1,8 +1,9 @@
//! `vetta-telemetry`: first-class, low-overhead inference statistics & MoE routing analytics.
//! `vetta-infer-tm`: first-class, low-overhead inference statistics & MoE routing analytics.
//!
//! Tracks per-layer expert activation Zipf curves, `L -> L+1` co-activation transitions,
//! domain-tagged expert profiles (for NVMe Hot/Cold pre-warming and Lyra domain routing),
//! speculative acceptance histograms, and exports structured JSONL asynchronously.
//! Writes the updatable `stats/` profiles of the `.vbundle` (docs/ARCHITECTURE.md §3).
use std::collections::HashMap;
use std::fs::OpenOptions;
@@ -10,7 +11,7 @@ use std::io::{BufWriter, Write};
use std::path::Path;
use std::sync::mpsc::{self, SyncSender, TrySendError};
use std::thread::{self, JoinHandle};
use vetta_core::moe::ExpertKey;
use vetta_infer_abi::ExpertKey;
#[derive(Debug, Clone)]
pub enum TelemetryEvent {
@@ -235,7 +236,7 @@ mod tests {
#[test]
fn domain_expert_profile_and_async_jsonl() {
let p = std::env::temp_dir().join(format!("vetta_tel_{}.jsonl", std::process::id()));
let p = std::env::temp_dir().join(format!("vetta_tm_{}.jsonl", std::process::id()));
let _ = std::fs::remove_file(&p);
let mut h = TelemetryHandle::start(Some(&p), 128).unwrap();
for _ in 0..5 {
@@ -267,4 +268,4 @@ mod tests {
assert!(std::fs::read_to_string(&p).unwrap().contains("\"ev\":\"spec\""));
let _ = std::fs::remove_file(&p);
}
}
}
-804
View File
@@ -1,804 +0,0 @@
//! `vetta-io`: unified checked `.safetensors` reader and write-once `O_RDONLY` NVMe disk cache.
//!
//! Eliminates audit-05 F-02 (shard bounds, u64 slice overflow, missing index.json) and F-05
//! (pre-reserve OOM on corrupt count, PID-isolated `.tmp.<pid>` atomic commit) by construction.
use std::collections::{BTreeSet, HashMap};
use std::fs::{self, File, OpenOptions};
use std::io::{self, Read, Write};
use std::os::unix::fs::FileExt;
use std::path::{Path, PathBuf};
// ============================================================================
// 1. Minimal Checked JSON Parser (zero external deps, strict UTF-8/escapes)
// ============================================================================
#[derive(Debug, Clone, PartialEq)]
pub enum JsonVal {
Null,
Bool(bool),
Num(f64),
Int(u64),
Str(String),
Arr(Vec<JsonVal>),
Obj(HashMap<String, JsonVal>),
}
impl JsonVal {
pub fn as_obj(&self) -> Option<&HashMap<String, JsonVal>> {
match self {
JsonVal::Obj(m) => Some(m),
_ => None,
}
}
pub fn as_arr(&self) -> Option<&[JsonVal]> {
match self {
JsonVal::Arr(v) => Some(v),
_ => None,
}
}
pub fn as_str(&self) -> Option<&str> {
match self {
JsonVal::Str(s) => Some(s),
_ => None,
}
}
pub fn as_u64(&self) -> Option<u64> {
match self {
JsonVal::Int(n) => Some(*n),
JsonVal::Num(f) if *f >= 0.0 && f.fract() == 0.0 && *f <= (u64::MAX as f64) => Some(*f as u64),
_ => None,
}
}
}
struct JsonParser<'a> {
b: &'a [u8],
i: usize,
}
impl<'a> JsonParser<'a> {
fn skip_ws(&mut self) {
while self.i < self.b.len() && matches!(self.b[self.i], b' ' | b'\n' | b'\r' | b'\t') {
self.i += 1;
}
}
fn parse_str(&mut self) -> Result<String, String> {
if self.b.get(self.i) != Some(&b'"') {
return Err("expected '\"'".into());
}
self.i += 1;
let mut out = Vec::new();
while self.i < self.b.len() {
let c = self.b[self.i];
self.i += 1;
if c == b'"' {
return String::from_utf8(out).map_err(|_| "invalid UTF-8 in JSON string".into());
}
if c == b'\\' {
if self.i >= self.b.len() {
return Err("truncated JSON escape".into());
}
let e = self.b[self.i];
self.i += 1;
match e {
b'"' => out.push(b'"'),
b'\\' => out.push(b'\\'),
b'/' => out.push(b'/'),
b'b' => out.push(0x08),
b'f' => out.push(0x0C),
b'n' => out.push(b'\n'),
b'r' => out.push(b'\r'),
b't' => out.push(b'\t'),
b'u' => {
if self.i + 4 > self.b.len() {
return Err("truncated \\u escape".into());
}
let hex = std::str::from_utf8(&self.b[self.i..self.i + 4])
.map_err(|_| "bad \\u hex")?;
let code = u32::from_str_radix(hex, 16).map_err(|_| "bad \\u hex")?;
self.i += 4;
let ch = char::from_u32(code).unwrap_or('\u{FFFD}');
let mut buf = [0u8; 4];
out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
}
_ => return Err("unsupported JSON escape".into()),
}
} else {
out.push(c);
}
}
Err("unterminated JSON string".into())
}
fn parse_val(&mut self, depth: usize) -> Result<JsonVal, String> {
if depth > 64 {
return Err("JSON nesting too deep".into());
}
self.skip_ws();
let &c = self.b.get(self.i).ok_or_else(|| "unexpected EOF in JSON".to_string())?;
match c {
b'"' => Ok(JsonVal::Str(self.parse_str()?)),
b'{' => {
self.i += 1;
let mut map = HashMap::new();
self.skip_ws();
if self.b.get(self.i) == Some(&b'}') {
self.i += 1;
return Ok(JsonVal::Obj(map));
}
loop {
self.skip_ws();
let k = self.parse_str()?;
self.skip_ws();
if self.b.get(self.i) != Some(&b':') {
return Err("expected ':'".into());
}
self.i += 1;
let v = self.parse_val(depth + 1)?;
map.insert(k, v);
self.skip_ws();
match self.b.get(self.i) {
Some(&b',') => self.i += 1,
Some(&b'}') => {
self.i += 1;
return Ok(JsonVal::Obj(map));
}
_ => return Err("expected ',' or '}'".into()),
}
}
}
b'[' => {
self.i += 1;
let mut arr = Vec::new();
self.skip_ws();
if self.b.get(self.i) == Some(&b']') {
self.i += 1;
return Ok(JsonVal::Arr(arr));
}
loop {
arr.push(self.parse_val(depth + 1)?);
self.skip_ws();
match self.b.get(self.i) {
Some(&b',') => self.i += 1,
Some(&b']') => {
self.i += 1;
return Ok(JsonVal::Arr(arr));
}
_ => return Err("expected ',' or ']'".into()),
}
}
}
b't' if self.b[self.i..].starts_with(b"true") => {
self.i += 4;
Ok(JsonVal::Bool(true))
}
b'f' if self.b[self.i..].starts_with(b"false") => {
self.i += 5;
Ok(JsonVal::Bool(false))
}
b'n' if self.b[self.i..].starts_with(b"null") => {
self.i += 4;
Ok(JsonVal::Null)
}
b'-' | b'0'..=b'9' => {
let start = self.i;
if self.b[self.i] == b'-' {
self.i += 1;
}
let mut is_float = false;
while self.i < self.b.len() {
match self.b[self.i] {
b'0'..=b'9' => self.i += 1,
b'.' | b'e' | b'E' | b'+' | b'-' => {
is_float = true;
self.i += 1;
}
_ => break,
}
}
let s = std::str::from_utf8(&self.b[start..self.i]).map_err(|_| "bad number")?;
if !is_float && !s.starts_with('-') {
if let Ok(u) = s.parse::<u64>() {
return Ok(JsonVal::Int(u));
}
}
let f = s.parse::<f64>().map_err(|_| format!("invalid number '{s}'"))?;
Ok(JsonVal::Num(f))
}
_ => Err(format!("unexpected char '{}' in JSON", c as char)),
}
}
}
pub fn parse_json(text: &str) -> Result<JsonVal, String> {
let mut p = JsonParser { b: text.as_bytes(), i: 0 };
let v = p.parse_val(0)?;
p.skip_ws();
if p.i != p.b.len() {
return Err("trailing characters in JSON".into());
}
Ok(v)
}
// ============================================================================
// 2. Checked Safetensors Archive Reader (`pread`, `index.json`, strict bounds)
// ============================================================================
#[derive(Debug, Clone)]
pub struct TensorInfo {
pub shard_idx: usize,
pub dtype: String,
pub shape: Vec<u64>,
pub begin: u64,
pub end: u64,
}
impl TensorInfo {
pub fn byte_len(&self) -> u64 {
self.end - self.begin
}
}
pub struct SafetensorsShard {
pub path: PathBuf,
pub file: File,
pub file_size: u64,
pub data_start: u64,
}
pub struct SafetensorsArchive {
pub dir: PathBuf,
pub shards: Vec<SafetensorsShard>,
pub tensors: HashMap<String, TensorInfo>,
}
const MAX_HEADER_BYTES: u64 = 128 * 1024 * 1024;
impl SafetensorsArchive {
pub fn open(dir: impl AsRef<Path>) -> Result<Self, String> {
let dir = dir.as_ref().to_path_buf();
let shard_paths = discover_shards(&dir)?;
if shard_paths.is_empty() {
return Err(format!("no .safetensors shards found in {}", dir.display()));
}
let mut shards = Vec::with_capacity(shard_paths.len());
let mut tensors = HashMap::new();
for (shard_idx, path) in shard_paths.into_iter().enumerate() {
let file = OpenOptions::new()
.read(true)
.open(&path)
.map_err(|e| format!("open {}: {e}", path.display()))?;
let file_size = file
.metadata()
.map_err(|e| format!("stat {}: {e}", path.display()))?
.len();
if file_size < 8 {
return Err(format!("truncated safetensors file {}", path.display()));
}
let mut len_buf = [0u8; 8];
file.read_exact_at(&mut len_buf, 0)
.map_err(|e| format!("read header len {}: {e}", path.display()))?;
let hlen = u64::from_le_bytes(len_buf);
let data_start = 8u64
.checked_add(hlen)
.ok_or_else(|| format!("header length overflow in {}", path.display()))?;
if hlen == 0 || hlen > MAX_HEADER_BYTES || data_start > file_size {
return Err(format!(
"invalid header length {hlen} (file_size={file_size}) in {}",
path.display()
));
}
let mut hbytes = vec![0u8; hlen as usize];
file.read_exact_at(&mut hbytes, 8)
.map_err(|e| format!("read header {}: {e}", path.display()))?;
let hstr = std::str::from_utf8(&hbytes)
.map_err(|_| format!("non-UTF-8 header in {}", path.display()))?;
let root = parse_json(hstr)?;
let obj = root
.as_obj()
.ok_or_else(|| format!("header root is not JSON object in {}", path.display()))?;
let avail = file_size - data_start;
for (name, val) in obj {
if name == "__metadata__" {
continue;
}
let to = val
.as_obj()
.ok_or_else(|| format!("tensor '{name}' entry is not object"))?;
let dtype = to
.get("dtype")
.and_then(|v| v.as_str())
.ok_or_else(|| format!("tensor '{name}' missing dtype"))?
.to_string();
let shape_arr = to
.get("shape")
.and_then(|v| v.as_arr())
.ok_or_else(|| format!("tensor '{name}' missing shape"))?;
let mut shape = Vec::with_capacity(shape_arr.len());
for d in shape_arr {
shape.push(d.as_u64().ok_or_else(|| format!("tensor '{name}' bad dim"))?);
}
let offs = to
.get("data_offsets")
.and_then(|v| v.as_arr())
.ok_or_else(|| format!("tensor '{name}' missing data_offsets"))?;
if offs.len() != 2 {
return Err(format!("tensor '{name}' data_offsets len != 2"));
}
let begin = offs[0].as_u64().ok_or_else(|| format!("tensor '{name}' bad begin"))?;
let end = offs[1].as_u64().ok_or_else(|| format!("tensor '{name}' bad end"))?;
if end < begin || end > avail {
return Err(format!(
"tensor '{name}' out of shard bounds [{begin}, {end}) vs avail={avail} in {}",
path.display()
));
}
if tensors.contains_key(name) {
return Err(format!("duplicate tensor '{name}' across shards"));
}
tensors.insert(
name.clone(),
TensorInfo {
shard_idx,
dtype,
shape,
begin,
end,
},
);
}
shards.push(SafetensorsShard {
path,
file,
file_size,
data_start,
});
}
Ok(Self { dir, shards, tensors })
}
pub fn total_tensor_bytes(&self) -> u64 {
self.tensors.values().map(|t| t.byte_len()).sum()
}
pub fn read_slice(&self, name: &str, rel_off: u64, dst: &mut [u8]) -> Result<(), String> {
let info = self
.tensors
.get(name)
.ok_or_else(|| format!("tensor not found: {name}"))?;
let total = info.byte_len();
let req = dst.len() as u64;
if rel_off > total || req > total - rel_off {
return Err(format!(
"slice OOB for '{name}': rel_off={rel_off} len={req} total={total}"
));
}
let sh = &self.shards[info.shard_idx];
let file_off = sh
.data_start
.checked_add(info.begin)
.and_then(|v| v.checked_add(rel_off))
.ok_or_else(|| format!("file offset overflow for '{name}'"))?;
sh.file
.read_exact_at(dst, file_off)
.map_err(|e| format!("pread '{}' at {file_off}: {e}", sh.path.display()))
}
}
fn discover_shards(dir: &Path) -> Result<Vec<PathBuf>, String> {
let idx_path = dir.join("model.safetensors.index.json");
if idx_path.is_file() {
let raw = fs::read_to_string(&idx_path)
.map_err(|e| format!("read {}: {e}", idx_path.display()))?;
let root = parse_json(&raw)?;
let wm = root
.as_obj()
.and_then(|o| o.get("weight_map"))
.and_then(|v| v.as_obj())
.ok_or_else(|| format!("missing weight_map in {}", idx_path.display()))?;
let mut uniq = BTreeSet::new();
for v in wm.values() {
if let Some(fname) = v.as_str() {
if !fname.is_empty() {
uniq.insert(dir.join(fname));
}
}
}
return Ok(uniq.into_iter().collect());
}
let entries = fs::read_dir(dir).map_err(|e| format!("list {}: {e}", dir.display()))?;
let mut out = Vec::new();
for entry in entries {
let e = entry.map_err(|e| format!("dir entry {}: {e}", dir.display()))?;
let p = e.path();
if p.is_file() && p.extension().and_then(|x| x.to_str()) == Some("safetensors") {
out.push(p);
}
}
out.sort();
Ok(out)
}
// ============================================================================
// 3. Unified Write-Once `O_RDONLY` NVMe Disk Cache (`VTC1`, PID `.tmp`, anti-OOM)
// ============================================================================
pub const CACHE_MAGIC: [u8; 8] = *b"VTCACHE1";
pub const CACHE_VERSION: u32 = 1;
pub const CACHE_ALIGN: u64 = 4096;
const HEADER_SIZE: usize = 48;
const MIN_REC_BYTES: usize = 1 + 4 * 4 + 4 * 8 + 4; // 53 B minimum per serialized record
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CacheRecord {
pub kind: u8,
pub i0: i32,
pub i1: i32,
pub i2: i32,
pub flags: u32,
pub u0: u64,
pub u1: u64,
pub data_offset: u64,
pub data_bytes: u64,
pub name: String,
}
pub fn fnv1a_u64(bytes: &[u8], seed: u64) -> u64 {
let mut h = seed;
for &b in bytes {
h ^= b as u64;
h = h.wrapping_mul(0x0000_0100_0000_01B3);
}
h
}
pub fn align_up(v: u64, align: u64) -> Result<u64, String> {
let rem = v % align;
if rem == 0 {
Ok(v)
} else {
v.checked_add(align - rem).ok_or_else(|| "align_up overflow".into())
}
}
pub fn serialize_meta(recs: &[CacheRecord]) -> Vec<u8> {
let mut out = Vec::new();
for r in recs {
out.push(r.kind);
out.extend_from_slice(&r.i0.to_le_bytes());
out.extend_from_slice(&r.i1.to_le_bytes());
out.extend_from_slice(&r.i2.to_le_bytes());
out.extend_from_slice(&r.flags.to_le_bytes());
out.extend_from_slice(&r.u0.to_le_bytes());
out.extend_from_slice(&r.u1.to_le_bytes());
out.extend_from_slice(&r.data_offset.to_le_bytes());
out.extend_from_slice(&r.data_bytes.to_le_bytes());
let nlen = r.name.len() as u32;
out.extend_from_slice(&nlen.to_le_bytes());
out.extend_from_slice(r.name.as_bytes());
}
out
}
pub fn deserialize_meta(blob: &[u8], count: u32) -> Result<Vec<CacheRecord>, String> {
// Anti-OOM check BEFORE `Vec::with_capacity(count)` (audit-05 F-05)
if (count as usize) > blob.len() / MIN_REC_BYTES {
return Err(format!(
"corrupt cache metadata: count={count} exceeds blob capacity ({} B)",
blob.len()
));
}
let mut out = Vec::with_capacity(count as usize);
let mut pos = 0usize;
let take = |pos: &mut usize, n: usize| -> Result<&[u8], String> {
if n > blob.len().saturating_sub(*pos) {
return Err("truncated cache metadata".into());
}
let s = &blob[*pos..*pos + n];
*pos += n;
Ok(s)
};
for _ in 0..count {
let kind = take(&mut pos, 1)?[0];
let i0 = i32::from_le_bytes(take(&mut pos, 4)?.try_into().unwrap());
let i1 = i32::from_le_bytes(take(&mut pos, 4)?.try_into().unwrap());
let i2 = i32::from_le_bytes(take(&mut pos, 4)?.try_into().unwrap());
let flags = u32::from_le_bytes(take(&mut pos, 4)?.try_into().unwrap());
let u0 = u64::from_le_bytes(take(&mut pos, 8)?.try_into().unwrap());
let u1 = u64::from_le_bytes(take(&mut pos, 8)?.try_into().unwrap());
let data_offset = u64::from_le_bytes(take(&mut pos, 8)?.try_into().unwrap());
let data_bytes = u64::from_le_bytes(take(&mut pos, 8)?.try_into().unwrap());
let nlen = u32::from_le_bytes(take(&mut pos, 4)?.try_into().unwrap()) as usize;
if nlen > 4096 {
return Err("cache record name too long".into());
}
let nbytes = take(&mut pos, nlen)?;
let name = std::str::from_utf8(nbytes)
.map_err(|_| "non-UTF-8 cache record name")?
.to_string();
out.push(CacheRecord {
kind,
i0,
i1,
i2,
flags,
u0,
u1,
data_offset,
data_bytes,
name,
});
}
if pos != blob.len() {
return Err("trailing bytes in cache metadata".into());
}
Ok(out)
}
pub struct DiskCacheWriter {
final_path: PathBuf,
tmp_path: PathBuf,
file: Option<File>,
fingerprint: u64,
cursor: u64,
records: Vec<CacheRecord>,
}
impl DiskCacheWriter {
pub fn begin(final_path: impl AsRef<Path>, fingerprint: u64) -> Result<Self, String> {
let final_path = final_path.as_ref().to_path_buf();
if let Some(parent) = final_path.parent() {
fs::create_dir_all(parent).map_err(|e| format!("mkdir {}: {e}", parent.display()))?;
}
let pid = std::process::id();
let tmp_path = PathBuf::from(format!("{}.tmp.{pid}", final_path.display()));
let file = OpenOptions::new()
.create(true)
.truncate(true)
.read(true)
.write(true)
.open(&tmp_path)
.map_err(|e| format!("create {}: {e}", tmp_path.display()))?;
Ok(Self {
final_path,
tmp_path,
file: Some(file),
fingerprint,
cursor: CACHE_ALIGN,
records: Vec::new(),
})
}
pub fn write_record(&mut self, mut rec: CacheRecord, payload: &[u8]) -> Result<u64, String> {
let f = self.file.as_ref().ok_or_else(|| "writer closed".to_string())?;
rec.data_offset = align_up(self.cursor, CACHE_ALIGN)?;
rec.data_bytes = payload.len() as u64;
self.cursor = align_up(
rec.data_offset
.checked_add(rec.data_bytes)
.ok_or_else(|| "cache offset overflow".to_string())?,
CACHE_ALIGN,
)?;
f.write_all_at(payload, rec.data_offset)
.map_err(|e| format!("write payload: {e}"))?;
let off = rec.data_offset;
self.records.push(rec);
Ok(off)
}
pub fn commit(mut self) -> Result<PathBuf, String> {
let f = self.file.take().ok_or_else(|| "writer closed".to_string())?;
let meta = serialize_meta(&self.records);
let meta_off = align_up(self.cursor, CACHE_ALIGN)?;
f.write_all_at(&meta, meta_off)
.map_err(|e| format!("write meta: {e}"))?;
let total_bytes = meta_off
.checked_add(meta.len() as u64)
.ok_or_else(|| "total_bytes overflow".to_string())?;
let mut hdr = [0u8; HEADER_SIZE];
hdr[0..8].copy_from_slice(&CACHE_MAGIC);
hdr[8..12].copy_from_slice(&CACHE_VERSION.to_le_bytes());
hdr[12..16].copy_from_slice(&(self.records.len() as u32).to_le_bytes());
hdr[16..24].copy_from_slice(&self.fingerprint.to_le_bytes());
hdr[24..32].copy_from_slice(&meta_off.to_le_bytes());
hdr[32..40].copy_from_slice(&(meta.len() as u64).to_le_bytes());
hdr[40..48].copy_from_slice(&total_bytes.to_le_bytes());
f.write_all_at(&hdr, 0).map_err(|e| format!("write hdr: {e}"))?;
f.sync_all().map_err(|e| format!("fsync cache: {e}"))?;
drop(f);
fs::rename(&self.tmp_path, &self.final_path)
.map_err(|e| format!("rename cache: {e}"))?;
Ok(self.final_path.clone())
}
}
impl Drop for DiskCacheWriter {
fn drop(&mut self) {
if self.file.take().is_some() {
let _ = fs::remove_file(&self.tmp_path);
}
}
}
/// Strictly `O_RDONLY` cache reader (0 SSD writes on every 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}"))
}
}
// Keep unused imports clean if needed
#[allow(dead_code)]
fn _touch_io(_: &mut dyn Read, _: &mut dyn Write) -> io::Result<()> {
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn write_mini_st(path: &Path, name: &str, data: &[u8], truncate: bool, invert: bool) {
let (b, e) = if invert { (data.len(), 0) } else { (0, data.len()) };
let hdr = format!(
"{{\"{name}\":{{\"dtype\":\"F32\",\"shape\":[{}],\"data_offsets\":[{b},{e}]}}}}",
data.len() / 4
);
let mut f = File::create(path).unwrap();
f.write_all(&(hdr.len() as u64).to_le_bytes()).unwrap();
f.write_all(hdr.as_bytes()).unwrap();
let take = if truncate && !data.is_empty() { data.len() - 1 } else { data.len() };
f.write_all(&data[..take]).unwrap();
}
#[test]
fn safetensors_bounds_overflow_and_index_json() {
let root = std::env::temp_dir().join(format!("vetta_io_test_{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).unwrap();
// Non-existent dir fails cleanly
assert!(SafetensorsArchive::open(root.join("missing")).is_err());
// Truncated shard rejected
let d_trunc = root.join("trunc");
fs::create_dir_all(&d_trunc).unwrap();
write_mini_st(&d_trunc.join("a.safetensors"), "w", &[1, 2, 3, 4, 5, 6, 7, 8], true, false);
assert!(SafetensorsArchive::open(&d_trunc).is_err());
// Inverted offsets rejected
let d_inv = root.join("inv");
fs::create_dir_all(&d_inv).unwrap();
write_mini_st(&d_inv.join("a.safetensors"), "w", &[1, 2, 3, 4], false, true);
assert!(SafetensorsArchive::open(&d_inv).is_err());
// Valid + index.json ignoring stray backup + u64 overflow slice check
let d_ok = root.join("ok");
fs::create_dir_all(&d_ok).unwrap();
let bytes = [10u8, 20, 30, 40, 50, 60, 70, 80];
write_mini_st(&d_ok.join("s1.safetensors"), "w", &bytes, false, false);
write_mini_st(&d_ok.join("backup.safetensors"), "w", &bytes, false, false);
fs::write(
d_ok.join("model.safetensors.index.json"),
r#"{"weight_map":{"w":"s1.safetensors"}}"#,
)
.unwrap();
let ar = SafetensorsArchive::open(&d_ok).unwrap();
assert_eq!(ar.shards.len(), 1);
let mut got = [0u8; 4];
ar.read_slice("w", 4, &mut got).unwrap();
assert_eq!(got, [50, 60, 70, 80]);
assert!(ar.read_slice("w", u64::MAX, &mut got).is_err());
let _ = fs::remove_dir_all(&root);
}
#[test]
fn disk_cache_roundtrip_and_anti_oom() {
// Absurd entry count rejected BEFORE Vec::with_capacity
assert!(deserialize_meta(&[0u8; 64], u32::MAX).is_err());
let p = std::env::temp_dir().join(format!("vetta_cache_test_{}.bin", std::process::id()));
let _ = fs::remove_file(&p);
let fp = 0x1234_5678_ABCD_EF01u64;
let payload = vec![0x5Au8; 8192];
let mut wr = 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());
let _ = fs::remove_file(&p);
}
}
-8
View File
@@ -1,8 +0,0 @@
[package]
name = "vetta-telemetry"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
vetta-core = { path = "../vetta-core" }